All..... The script came from user Remzej. I have it on a cron job to check every 5 minutes (we are a busy proxy environment)...
*/2 * * * * root /usr/bin/nice -n20 /usr/local/bin/php-cgi -f /usr/local/pkg/monitor_memory_usage.php
#!/usr/local/bin/php-cgi -f
<?php
/*
monitor_memory_usage.php
part of pfSense (https://www.pfsense.org)
Copyright (c) 2011-2015 Rubicon Communications, LLC (Netgate)
All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
require_once('config.inc');
require_once('util.inc');
require_once('squid.inc');
global $config;
// Monitor memory usage by remzej
// Get SWAP usage funtion
function swap_usage() {
exec("/usr/sbin/swapinfo", $swap_info);
$swap_used = "";
foreach ($swap_info as $line) {
if (preg_match('/(\d+)%$/', $line, $matches)) {
$swap_used = $matches[1];
break;
}
}
return $swap_used;
}
// Get memory usage function
function mem_usage() {
$memory = "";
exec("/sbin/sysctl -n vm.stats.vm.v_page_count vm.stats.vm.v_inactive_count " .
"vm.stats.vm.v_cache_count vm.stats.vm.v_free_count", $memory);
$totalMem = $memory[0];
$availMem = $memory[1] + $memory[2] + $memory[3];
$usedMem = $totalMem - $availMem;
$memUsage = round(($usedMem * 100) / $totalMem, 0);
return $memUsage;
}
// Get memory and SWAP usage value
$memusage_pct = mem_usage();
$swapusage_pct = swap_usage();
// Display memory usage
echo "Memory Usage: " . $memusage_pct . "%" . PHP_EOL;
echo "SWAP Usage: " . $swapusage_pct . "%" . PHP_EOL;
// If memory usage is above 90%, stop and restart squid services.
if (($memusage_pct > 90) or ($swapusage_pct > 80)) {
squid_stop_monitor();
if (is_service_running('squid')) {
stop_service("squid");
}
squid_restart_services();
log_error(gettext(sprintf("[squid] Memory usage is $memusage_pct percent, Swap Usage is $swap_usage percent, stopping and restarting services.")));
}
log_error(gettext(sprintf("[squid] Memory usage is $memusage_pct percent and Swap Usage is $swapusage_pct")));
?>