-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathwp-failover.php
More file actions
591 lines (530 loc) · 21.4 KB
/
wp-failover.php
File metadata and controls
591 lines (530 loc) · 21.4 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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
<?php
/**
* Plugin Name: Failover Status Monitor
* Description: Monitors failover status and provides notifications.
* Version: 1.1.0
* Status: Complete
* Type: mu-plugin
*/
// Prevent direct access
defined('ABSPATH') or die('No script kiddies please!');
/**
*
* Get Nginx Status
* arg $url - URL to Nginx status page
*
* return void
*
*/
function wpfailover_nginx_status($url) {
// Curl stub at https://localhost/nginx_status check if returns 200
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curl_error = curl_errno($ch);
curl_close($ch);
// Check if URL is returning 200
if ($http_code === 200) {
echo $response;
} else {
if ($curl_error === CURLE_RECV_ERROR) {
echo 'Connection reset by peer. URL may be incorrect or NGINX status is not enabled.';
} else {
echo 'NGINX status is not available.';
}
}
}
/**
*
* Sanitize and validate filters
* arg $filters - Filters to sanitize and validate
*
* return array
*/
// Sanitize and validate filters
function wpfailover_sanitize_and_validate_filters($filters) {
// Sanitize the input
$filters = filter_var($filters, FILTER_SANITIZE_STRING);
// Split the input into an array
$filters_array = explode(',', $filters);
// Validate each item in the array
$valid_filters = array();
foreach ($filters_array as $filter_item) {
$filter_item = trim($filter_item); // Remove any extra whitespace
if (!empty($filter_item) && preg_match('/^[a-zA-Z0-9_\-]+$/', $filter_item)) {
$valid_filters[] = $filter_item;
}
}
return $valid_filters;
}
/**
*
* Get Nginx Access Logs
* arg $log - Path to Nginx access log
* arg $filters - Filters to apply
*
* return void
*/
function wpfailover_nginx_accesslogs ($log, $filters) {
$timeWindows = [5, 15, 30]; // Time windows in seconds
if (!file_exists($log)) {
echo "Log file not found.";
return;
} elseif (!is_readable($log)) {
if (!is_readable($log)) {
echo "Log file is not readable.";
return;
}
}
if ($filters == null) {
$filters = [];
}
// Ensure $filters is an array
if (is_string($filters)) {
$filters = wpfailover_sanitize_and_validate_filters($filters);
} elseif ($filters == null) {
$filters = [];
}
// Add current ip to filters
if (isset($_SERVER['SERVER_ADDR'])) {
$current_ip = $_SERVER['SERVER_ADDR'];
$filters[] = $current_ip;
}
// Add client IP to filters
if (isset($_SERVER['REMOTE_ADDR'])) {
$client_ip = $_SERVER['REMOTE_ADDR'];
$filters[] = $client_ip;
}
// Add Cloudflare filters
if (get_option('wpfailover_filters_add_cloudflare')) {
$filters[] = 'Cloudflare-Healthchecks';
$filters[] = 'Cloudflare-Traffic-Manager';
}
$output = 'Applied filters: ' . implode(', ', $filters) . "\n\n";
foreach ($timeWindows as $timeWindow) {
$currentTime = time();
$startTime = $currentTime - $timeWindow;
$requestCount = 0;
$logFile = fopen($log, 'r');
if ($logFile) {
while (($line = fgets($logFile)) !== false) {
// Assuming a standard Nginx log format, extract the timestamp
// You might need to adjust this based on your actual log format
if (preg_match('/^\[(.*?)\]/', $line, $matches)) {
$logTimestamp = strtotime($matches[1]);
// Apply filter BEFORE counting the request
$is_filtered = false;
foreach ($filters as $filter_item) {
if (strpos($line, $filter_item) !== false) {
$is_filtered = true;
break; // No need to check further if already filtered
}
}
if (!$is_filtered && $logTimestamp >= $startTime) {
$requestCount++;
}
}
}
fclose($logFile);
}
$output .= "Requests in the last $timeWindow seconds: $requestCount\n";
}
echo $output;
}
/**
*
* Display NGINX status
* arg $url - URL to Nginx status page
*
* return string
*/
function wpfailover_display_nginx_status($url) {
ob_start();
wpfailover_nginx_status($url);
return ob_get_clean();
}
/**
*
* Generate Status menus
* args none
*
* return void
*/
function wpfailover_status_menu() {
add_menu_page(
'Failover Status',
'Failover Status',
'manage_options',
'wpfailover-status',
'wpfailover_status_page',
'dashicons-networking',
3
);
}
add_action('admin_menu', 'wpfailover_status_menu');
/**
*
* Enqueue wp-color-picker
* args none
*
* return void
*
*/
function wpfailover_enqueue_scripts() {
wp_enqueue_style('wp-color-picker');
wp_enqueue_script('wp-color-picker');
}
add_action('admin_enqueue_scripts', 'wpfailover_enqueue_scripts');
/**
*
* Migrate settings
* args none
*
* return void
*/
function wpfailover_migrate_settings (){
$old_settings = [
'primary_failover_ip',
'secondary_failover_ip',
'enable_admin_bar',
'enable_banner',
'admin_bar_color',
'primary_server_name',
'secondary_server_name',
'nginx_status_url',
'nginx_access_log'
];
//Cycle through and update
foreach ($old_settings as $setting) {
if (get_option($setting)) {
update_option('wpfailover_' . $setting, get_option($setting));
delete_option($setting);
}
}
}
add_action('admin_init', 'wpfailover_migrate_settings');
/**
*
* Register settings
* args none
*
* return void
*/
function wpfailover_register_settings() {
// Rename settings to have wpf_
register_setting('wpfailover_failover_settings', 'wpfailover_primary_failover_ip');
register_setting('wpfailover_failover_settings', 'wpfailover_secondary_failover_ip');
register_setting('wpfailover_failover_settings', 'wpfailover_enable_admin_bar');
register_setting('wpfailover_failover_settings', 'wpfailover_enable_banner');
register_setting('wpfailover_failover_settings', 'wpfailover_admin_bar_color');
register_setting('wpfailover_failover_settings', 'wpfailover_primary_server_name');
register_setting('wpfailover_failover_settings', 'wpfailover_secondary_server_name');
register_setting('wpfailover_failover_settings', 'wpfailover_nginx_status_url');
register_setting('wpfailover_failover_settings', 'wpfailover_nginx_access_log');
register_setting('wpfailover_failover_settings', 'wpfailover_nginx_access_log_filters');
register_setting('wpfailover_failover_settings', 'wpfailover_filters_add_cloudflare');
register_setting('wpfailover_failover_settings', 'wpfailover_cf_loadbalancing_logs_url');
register_setting('wpfailover_failover_settings', 'wpfailover_status_api_key');
}
add_action('admin_init', 'wpfailover_register_settings');
/**
*
* Register REST API status endpoint
* args none
*
* return void
*/
function wpfailover_register_rest_status() {
register_rest_route('wpfailover/v1', '/status', [
'methods' => 'GET',
'callback' => 'wpfailover_rest_status_callback',
'permission_callback' => '__return_true',
]);
}
add_action('rest_api_init', 'wpfailover_register_rest_status');
/**
*
* REST API status callback
* Returns 'primary' or 'secondary' as plain text if valid API key is provided
*
* @param WP_REST_Request $request
* return WP_REST_Response
*/
function wpfailover_rest_status_callback($request) {
$provided_key = $request->get_param('key');
$stored_key = get_option('wpfailover_status_api_key');
if (empty($stored_key) || empty($provided_key) || !hash_equals($stored_key, $provided_key)) {
$response = new WP_REST_Response('unauthorized', 403);
$response->header('Content-Type', 'text/plain');
return $response;
}
$current_ip = $_SERVER['SERVER_ADDR'];
$primary_ip = get_option('wpfailover_primary_failover_ip');
$status = ($current_ip === $primary_ip) ? 'primary' : 'secondary';
$response = new WP_REST_Response($status, 200);
$response->header('Content-Type', 'text/plain');
return $response;
}
/**
*
* Add settings sections
* args none
*
* return void
*/
function wpfailover_add_settings_sections() {
add_settings_section(
'wpfailover_settings_section',
'WP Failover Settings',
'wpfailover_settings_section_callback',
'wpfailover-status'
);
}
add_action('admin_init', 'wpfailover_add_settings_sections');
function wpfailover_settings_section_callback() {
echo '<p>Configure failover settings here.</p>';
}
/**
*
* Failover notification logic
* args none
*
* return void
*/
function wpfailover_notification() {
$current_ip = $_SERVER['SERVER_ADDR'];
$primary_failover_ip = get_option('wpfailover_primary_failover_ip');
$admin_bar_color = get_option('admin_bar_color', '#9a6400'); // Default to #9a6400 if not set
if ($current_ip !== $primary_failover_ip) {
if (get_option('wpfailover_enable_admin_bar')) {
// Admin bar color.
function wpfailover_admin_bar_color() {
global $admin_bar_color;
echo '<style type="text/css">
#wpadminbar { background-color: ' . $admin_bar_color . ' !important; }
</style>';
}
add_action('admin_head', 'wpfailover_admin_bar_color');
// Add "Failover ACTIVE" to admin bar
function wpfailover_admin_bar_node() {
global $wp_admin_bar;
// Get the URL of the failover status page
$failover_page_url = admin_url('admin.php?page=wpfailover-status');
$wp_admin_bar->add_node(array(
'id' => 'failover-active',
'title' => 'Failover ACTIVE',
'href' => $failover_page_url,
'meta' => array(
'class' => 'wpfailover-active-node',
),
));
}
add_action('admin_bar_menu', 'wpfailover_admin_bar_node', 999);
// Style the "Failover ACTIVE" node
function wpfailover_style_admin_bar_node() {
echo '<style type="text/css">
#wpadminbar #wp-admin-bar-failover-active > .ab-item {
color: white !important;
background-color: red;
font-weight: bold;
}
</style>';
}
add_action('admin_head', 'wpfailover_style_admin_bar_node');
}
if (get_option('wpfailover_enable_banner')) {
// Display "Failover ACTIVE" as an admin notice
function wpfailover_display_admin_notice() {
$current_ip = $_SERVER['SERVER_ADDR'];
// Get the URL of the failover status page
$failover_page_url = admin_url('admin.php?page=wpfailover-status');
$failover_server_name = ($current_ip === get_option('secondary_failover_ip'))
? get_option('wpfailover_secondary_server_name', 'Secondary') // Use saved name or default
: get_option('wpfailover_primary_server_name', 'Primary'); // Use saved name or default
echo '<div class="notice notice-error is-dismissible">
<p><strong>Failover ACTIVE on ' . $current_ip . '/' . $failover_server_name . ' - Don\'t make changes as they will be lost</strong> - <a href="' . $failover_page_url . '">View Failover Status</a></p>
</div>';
}
add_action('admin_notices', 'wpfailover_display_admin_notice');
}
}
}
add_action('init', 'wpfailover_notification');
/**
* Failover Status page
* args none
*
* return void
*/
function wpfailover_status_page() {
// Reset opcache.
if (function_exists('opcache_reset')) {
opcache_reset();
}
$current_ip = $_SERVER['SERVER_ADDR'];
$wpfailover_primary_failover_ip = get_option('wpfailover_primary_failover_ip');
$is_failover_active = ($current_ip !== $wpfailover_primary_failover_ip);
?>
<div class="wrap">
<h1>Failover Status</h1>
<hr>
<h2>Introduction</h2>
<p>This is a plugin for monitoring failovers.</p>
<h2>Current Server</h2>
<p>Hostname/IP: <?php echo gethostname() . '/' . $current_ip; ?></p>
<hr>
<h2>Status</h2>
<p>
<?php
if ($is_failover_active) {
echo '<span style="color: red; font-weight: bold;">Failover ACTIVE </span> <span class="dashicons dashicons-no-alt"></span>';
} else {
echo '<span style="color: green; font-weight: bold;">Normal Operation </span> <span class="dashicons dashicons-yes"></span>';
}
?>
</p>
<hr>
<h2>Settings</h2>
<details>
<summary><b>Configure failover settings here.</b></summary>
<form method="post" action="options.php">
<?php
settings_fields('wpfailover_failover_settings');
do_settings_sections('wpfailover-status');
?>
<table class="form-table">
<tr valign="top">
<th scope="row">Primary Failover IP</th>
<td>
<input type="text" name="wpfailover_primary_failover_ip" value="<?php echo esc_attr(get_option('wpfailover_primary_failover_ip')); ?>" />
<input type="text" name="wpfailover_primary_server_name" placeholder="Primary Server Name" value="<?php echo esc_attr(get_option('wpfailover_primary_server_name')); ?>" />
</td>
</tr>
<tr valign="top">
<th scope="row">Secondary Failover IP</th>
<td>
<input type="text" name="wpfailover_secondary_failover_ip" value="<?php echo esc_attr(get_option('wpfailover_secondary_failover_ip')); ?>" />
<input type="text" name="wpfailover_secondary_server_name" placeholder="Secondary Server Name" value="<?php echo esc_attr(get_option('wpfailover_secondary_server_name')); ?>" />
</td>
</tr>
<tr valign="top">
<th scope="row">Failover Notification - Admin Bar</th>
<td><input type="checkbox" name="wpfailover_enable_admin_bar" value="1" <?php checked(get_option('wpfailover_enable_admin_bar'), 1); ?> /></td>
</tr>
<tr valign="top">
<th scope="row">Failover Notification - Banner</th>
<td><input type="checkbox" name="wpfailover_enable_banner" value="1" <?php checked(get_option('wpfailover_enable_banner'), 1); ?> /></td>
</tr>
<tr valign="top">
<th scope="row">Admin Bar Color (Failover)</th>
<td><input id="color-picker" type="text" name="wpfailover_admin_bar_color" class="color-picker" value="<?php echo esc_attr(get_option('wpfailover_admin_bar_color', '#9a6400')); ?>" /></td>
</tr>
<tr valign="top">
<th scope="row">Coudflare Load Balancer Logs URL</th>
<td><input type="text" name="wpfailover_cf_loadbalancing_logs_url" size="60" value="<?php echo esc_attr(get_option('wpfailover_cf_loadbalancing_logs_url', '')); ?>" /></td>
</tr>
<tr valign="top">
<th scope="row">NGINX Status URL</th>
<td><input type="text" name="wpfailover_nginx_status_url" size="60" value="<?php echo esc_attr(get_option('wpfailover_nginx_status_url', 'http://localhost/stub_status')); ?>" /></td>
</tr>
<tr valign="top">
<th scope="row">Nginx Access Log Path</th>
<td><input type="text" name="wpfailover_nginx_access_log" size="60" value="<?php echo esc_attr(get_option('wpfailover_nginx_access_log', '/var/log/nginx/access.log')); ?>" /></td>
</tr>
<tr valign="top">
<th scope="row">Nginx Access Log Filters</th>
<td><input type="text" name="wpfailover_nginx_access_log_filters" size="60" value="<?php echo esc_attr(get_option('wpfailover_nginx_access_log_filters', 'wp-login.php,xmlrpc.php,BetterUptime,Cloudflare-Healthchecks,Cloudflare-Traffic-Manager')); ?>" /></td>
</tr>
<tr valign="top">
<th scope="row">Add Cloudflare-Traffic-Manager and Cloudflare-Healthchecks to Nginx Access Log Filters</th>
<td><input type="checkbox" name="wpfailover_filters_add_cloudflare" value="1" <?php checked(get_option('wpfailover_filters_add_cloudflare'), 1); ?> /></td>
</tr>
<tr valign="top">
<th scope="row">Status API Key</th>
<td>
<input type="text" id="wpfailover_status_api_key" name="wpfailover_status_api_key" size="40" value="<?php echo esc_attr(get_option('wpfailover_status_api_key', '')); ?>" />
<button type="button" class="button" onclick="document.getElementById('wpfailover_status_api_key').value = Array.from(crypto.getRandomValues(new Uint8Array(16))).map(b => b.toString(16).padStart(2, '0')).join('');">Generate Key</button>
<?php if (get_option('wpfailover_status_api_key')) : ?>
<p class="description">Status endpoint URL (click copy):</p>
<input
type="text"
id="wpfailover_status_endpoint_url"
value="<?php echo esc_url(rest_url('wpfailover/v1/status')) . '?key=' . esc_attr(get_option('wpfailover_status_api_key')); ?>"
readonly
size="90"
onclick="this.select();"
/>
<button type="button" class="button" onclick="wpfailoverCopyEndpointUrl()">Copy URL</button>
<span id="wpfailover_copy_status" class="description" style="margin-left:8px;"></span>
<?php else : ?>
<p class="description">Generate or enter an API key, then save to enable the status endpoint.</p>
<?php endif; ?>
</td>
</tr>
</table>
<?php submit_button(); ?>
<button type="button" onclick="location.reload();">Refresh</button>
</form>
</details>
<hr>
<h2>Status</h2>
<h3>Cloudflare Failover</h3>
<div>
<a href="<?php echo get_option('wpfailover_cf_loadbalancing_logs_url'); ?>" target="_blank">Cloudflare Load Balancer Logs</a>
</div>
<div class="failover-wrapper" style="
border: 1px solid black;
border-radius: 15px;
padding: 10px;
margin-top:20px;
background-color: lightgrey;
">
<h3>NGINX Status</h3>
<div id="wpfailover-nginx-status">
<pre><?php wpfailover_nginx_status(get_option('wpfailover_nginx_status_url')); ?></pre>
</div>
<h3>Nginx Access Logs 5/15/30</h3>
<div id="wpfailover-nginx-log">
<p>Filters: <?php echo get_option('wpfailover_nginx_access_log_filters', 'wp-login.php,xmlrpc.php,BetterUptime'); ?> and by default current IP and client IP</p>
<pre><?php wpfailover_nginx_accesslogs(get_option('wpfailover_nginx_access_log'),get_option('wpfailover_nginx_access_log_filters', 'wp-login.php,xmlrpc.php,BetterUptime,Cloudflare-Healthchecks,Cloudflare-Traffic-Manager')); ?></pre>
</div>
</div>
</div>
<script>
jQuery(document).ready(function($) {
$('.color-picker').wpColorPicker();
});
function wpfailoverCopyEndpointUrl() {
var endpointInput = document.getElementById('wpfailover_status_endpoint_url');
var copyStatus = document.getElementById('wpfailover_copy_status');
if (!endpointInput) {
return;
}
endpointInput.select();
endpointInput.setSelectionRange(0, 99999);
var copied = false;
if (navigator.clipboard && navigator.clipboard.writeText) {
navigator.clipboard.writeText(endpointInput.value)
.then(function() {
copied = true;
if (copyStatus) {
copyStatus.textContent = 'Copied';
}
})
.catch(function() {
copied = document.execCommand('copy');
if (copyStatus) {
copyStatus.textContent = copied ? 'Copied' : 'Copy failed';
}
});
return;
}
copied = document.execCommand('copy');
if (copyStatus) {
copyStatus.textContent = copied ? 'Copied' : 'Copy failed';
}
}
</script>
<?php
}