Skip to content

Commit 96bc473

Browse files
committed
cache : add prune and refresh buttons
1 parent a4d287d commit 96bc473

File tree

4 files changed

+93
-23
lines changed

4 files changed

+93
-23
lines changed

inc/admin/advanced-settings.php

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@ function adminAdvancedSettings()
1212
}, 'crowdsec_advanced_settings');
1313

1414
// Field "crowdsec_stream_mode"
15-
1615
addFieldCheckbox('crowdsec_stream_mode', 'Enable the "Stream" mode', 'crowdsec_plugin_advanced_settings', 'crowdsec_advanced_settings', 'crowdsec_admin_advanced_stream_mode', function () {
1716
// Stream mode just activated.
1817
scheduleBlocklistRefresh();
@@ -21,11 +20,13 @@ function adminAdvancedSettings()
2120
unscheduleBlocklistRefresh();
2221
}, '
2322
<p>With the stream mode, every decision is retrieved in an asynchronous way. 3 advantages: <br>&nbsp;1) Inivisible latency when loading pages<br>&nbsp;2) The IP verifications works even if your CrowdSec is not reachable.<br>&nbsp;3) The API can never be overloaded by the WordPress traffic</p>
24-
<p>Note: This method has one limit: for maximum 60 seconds, all the new decisions may not be taken into account.</p>
25-
');
23+
<p>Note: This method has one limit: for maximum 60 seconds, all the new decisions may not be taken into account.</p>' .
24+
(get_option("crowdsec_stream_mode") ?
25+
'<p><input style="margin-right:10px" type="button" value="Refresh the cache now" class="button button-secondary button-small" onclick="document.getElementById(\'crowdsec_ation_refresh_cache\').submit();"></p>' :
26+
'<p><input style="margin-right:10px" type="button" disabled="disabled" value="Refresh the cache now" class="button button-secondary button-small"></p>'));
2627

2728
// Field "crowdsec_stream_mode_refresh_frequency"
28-
addFieldString('crowdsec_stream_mode_refresh_frequency', 'Resync decisions each', 'crowdsec_plugin_advanced_settings', 'crowdsec_advanced_settings', 'crowdsec_admin_advanced_cache', function ($input) {
29+
addFieldString('crowdsec_stream_mode_refresh_frequency', 'Resync decisions each<br>(stream mode only)', 'crowdsec_plugin_advanced_settings', 'crowdsec_advanced_settings', 'crowdsec_admin_advanced_stream_mode', function ($input) {
2930
$input = (int)$input;
3031
if ($input < 60) {
3132
$input = 60;
@@ -44,10 +45,9 @@ function adminAdvancedSettings()
4445
** Section "Cache" **
4546
********************/
4647

47-
add_settings_section('crowdsec_admin_advanced_cache', 'Caching configuration', function () {
48+
add_settings_section('crowdsec_admin_advanced_cache', 'Caching configuration <input style="margin-left: 7px;margin-top: -3px;" type="button" value="Clear now" class="button button-secondary button-small" onclick="if (confirm(\'Are you sure you want to completely clear the cache?\')) document.getElementById(\'crowdsec_ation_clear_cache\').submit();">', function () {
4849
?>
49-
<p>The File system cache is faster than calling LAPI. Redis or Memcached is faster than the File System cache.</p>
50-
<p><input type="button" value="Clear the cache" class="button button-secondary button-small" onclick="if (confirm('Are you sure you want to completely clear the cache?')) document.getElementById('crowdsec_ation_clear_cache').submit();"></p>
50+
<p>Polish the decisions cache settings by selecting the best technology or the cache durations best suited to your use.</p>
5151
<?php
5252
}, 'crowdsec_advanced_settings');
5353

@@ -60,20 +60,25 @@ function adminAdvancedSettings()
6060

6161
// TODO P1 big bug: fatal error when changing techno without dsn already set at previous state. Quick fix: Add error if no dsn and ask to set dsn then save then select techno.
6262

63-
// Clear old cache before changing system (don't display message and don't warmup)
64-
clearBouncerCache(false, true);
65-
AdminNotice::displaySuccess('Cache system changed. Previous cache data has been cleared.');
63+
$bouncer = getBouncerInstance();
64+
$bouncer->clearCache();
65+
$message = __('Cache system changed. Previous cache data has been cleared.');
6666

6767
// Update wp-cron schedule if stream mode is enabled
6868
if ((bool)get_option("crowdsec_stream_mode")) {
6969
$bouncer = getBouncerInstance($input); // Reload bouncer instance with the new cache system
70-
$bouncer->warmBlocklistCacheUp();
70+
$result = $bouncer->warmBlocklistCacheUp();
71+
$message .= __(' As the stream mode is enabled, the cache has just been warmed up, ' . ($result > 0 ? 'there are now ' . $result . ' decisions' : 'there is now ' . $result . ' decision') . ' in cache.');
7172
scheduleBlocklistRefresh();
7273
}
7374

75+
AdminNotice::displaySuccess($message);
76+
7477

7578
return $input;
76-
}, '<p>Which remediation to apply when CrowdSec advises unhandled remediation.</p>', [
79+
}, ((get_option("crowdsec_cache_system") === CROWDSEC_CACHE_SYSTEM_PHPFS) ?
80+
'<input style="margin-right:10px" type="button" value="Prune now" class="button button-secondary" onclick="document.getElementById(\'crowdsec_ation_prune_cache\').submit();">' : '') .
81+
'<p>The File system cache is faster than calling LAPI. Redis or Memcached is faster than the File System cache.</p>', [
7782
CROWDSEC_CACHE_SYSTEM_PHPFS => 'File system',
7883
CROWDSEC_CACHE_SYSTEM_REDIS => 'Redis',
7984
CROWDSEC_CACHE_SYSTEM_MEMCACHED => 'Memcached',

inc/admin/init.php

Lines changed: 69 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -9,33 +9,92 @@
99

1010
if (is_admin()) {
1111

12-
function clearBouncerCache($dislaySuccessFlashMessage = true, $noWarmup = false)
12+
function clearBouncerCacheInAdminPage()
1313
{
1414
try {
1515
$bouncer = getBouncerInstance();
1616
$bouncer->clearCache();
1717
$message = __('CrowdSec cache has just been cleared.');
1818

1919
// In stream mode, immediatelly warm the cache up.
20-
if (!$noWarmup && get_option("crowdsec_stream_mode")) {
21-
$bouncer->refreshBlocklistCache();
22-
$message .= __(' As the stream is enabled, the cache has just been warmed up.');
20+
if (get_option("crowdsec_stream_mode")) {
21+
$result = $bouncer->warmBlocklistCacheUp();
22+
$message .= __(' As the stream mode is enabled, the cache has just been warmed up, ' . ($result > 0 ? 'there are now '. $result . ' decisions' : 'there is now '. $result . ' decision') . ' in cache.');
2323
}
2424

25-
if ($dislaySuccessFlashMessage) {
26-
AdminNotice::displaySuccess($message);
27-
}
25+
AdminNotice::displaySuccess($message);
2826

2927
// TODO P3 i18n the whole lib https://developer.wordpress.org/plugins/internationalization/how-to-internationalize-your-plugin/
3028
} catch (WordpressCrowdSecBouncerException $e) {
31-
// TODO log error for debug mode only.
32-
AdminNotice::displayError($e->getMessage());
29+
getCrowdSecLoggerInstance()->error(null, [
30+
'type' => 'WP_EXCEPTION_WHILE_CLEARING_CACHE',
31+
'messsage' => $e->getMessage(),
32+
'code' => $e->getCode(),
33+
'file' => $e->getFile(),
34+
'line' => $e->getLine(),
35+
]);
36+
AdminNotice::displayError('Technical error while clearing the cache: ' . $e->getMessage());
37+
}
38+
}
39+
40+
function refreshBouncerCacheInAdminPage()
41+
{
42+
try {
43+
if (!get_option("crowdsec_stream_mode")) {
44+
return false;
45+
}
46+
47+
// In stream mode, immediatelly warm the cache up.
48+
if (get_option("crowdsec_stream_mode")) {
49+
$bouncer = getBouncerInstance();
50+
$result = $bouncer->refreshBlocklistCache();
51+
getCrowdSecLoggerInstance()->error(var_export($result, true));
52+
AdminNotice::displaySuccess(__(' The cache has just been refreshed (' . ($result['new'] > 0 ? $result['new'] . ' new decisions' : $result['new'] . ' new decision') . ', '.$result['deleted'].' deleted).'));
53+
}
54+
} catch (WordpressCrowdSecBouncerException $e) {
55+
getCrowdSecLoggerInstance()->error(null, [
56+
'type' => 'WP_EXCEPTION_WHILE_REFRESHING_CACHE',
57+
'messsage' => $e->getMessage(),
58+
'code' => $e->getCode(),
59+
'file' => $e->getFile(),
60+
'line' => $e->getLine(),
61+
]);
62+
AdminNotice::displayError('Technical error while refreshing the cache: ' . $e->getMessage());
63+
}
64+
}
65+
66+
function pruneBouncerCacheInAdminPage()
67+
{
68+
try {
69+
$bouncer = getBouncerInstance();
70+
$bouncer->pruneCache();
71+
72+
AdminNotice::displaySuccess(__('CrowdSec cache has just been pruned.'));
73+
} catch (WordpressCrowdSecBouncerException $e) {
74+
getCrowdSecLoggerInstance()->error(null, [
75+
'type' => 'WP_EXCEPTION_WHILE_PRUNING',
76+
'messsage' => $e->getMessage(),
77+
'code' => $e->getCode(),
78+
'file' => $e->getFile(),
79+
'line' => $e->getLine(),
80+
]);
81+
AdminNotice::displayError('Technical error while pruning the cache: ' . $e->getMessage());
3382
}
3483
}
3584

3685
// ACTIONS
86+
add_action('admin_post_clear_cache', function () {
87+
clearBouncerCacheInAdminPage();
88+
header("Location: {$_SERVER['HTTP_REFERER']}");
89+
exit(0);
90+
});
3791
add_action('admin_post_refresh_cache', function () {
38-
clearBouncerCache();
92+
refreshBouncerCacheInAdminPage();
93+
header("Location: {$_SERVER['HTTP_REFERER']}");
94+
exit(0);
95+
});
96+
add_action('admin_post_prune_cache', function () {
97+
pruneBouncerCacheInAdminPage();
3998
header("Location: {$_SERVER['HTTP_REFERER']}");
4099
exit(0);
41100
});

inc/plugin-setup.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ function deactivate_crowdsec_plugin()
4646
$apiKey = esc_attr(get_option('crowdsec_api_key'));
4747
if (!empty($apiUrl) && !empty($apiKey)) {
4848
// Clear the bouncer cache.
49-
clearBouncerCache();
49+
clearBouncerCacheInAdminPage();
5050
}
5151

5252
// Clean options.

inc/templates/advanced-settings.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,14 @@
1515

1616
<br/>
1717
<form action="<?php echo admin_url('admin-post.php'); ?>" method="post" id="crowdsec_ation_clear_cache">
18+
<input type="hidden" name="action" value="clear_cache">
19+
</form>
20+
<form action="<?php echo admin_url('admin-post.php'); ?>" method="post" id="crowdsec_ation_refresh_cache">
1821
<input type="hidden" name="action" value="refresh_cache">
1922
</form>
23+
<form action="<?php echo admin_url('admin-post.php'); ?>" method="post" id="crowdsec_ation_prune_cache">
24+
<input type="hidden" name="action" value="prune_cache">
25+
</form>
2026
</div>
2127
</div>
2228
</div>

0 commit comments

Comments
 (0)