Sunday, July 5, 2015

Estimating a MaxClients/MaxRequestWorkers base value for your MPM Prefork Apache configuration

The script below will generate a base value that you can use for MaxClient/MaxRequestWorkers in your mpm_prefork Apache configuration. The value guarantees that no disk swapping, which slows down the system, will not occur because there is enough memory for the Apache processes. Remember that this is just a base value, you can increase this number if you observe that there is still available memory. The script was tested in Ubuntu 14.04.

#!/bin/bash
#email jachermocilla@gmail.com

echo -n "Enter percent of free memory to use for Apache(1-100): "
read PERCENT_OF_FREE_FOR_APACHE

#restart apache
service apache2 restart > /dev/null

#PERCENT_FREE_FOR_APACHE=75
echo "Percent of free memory to allocate to apache(%): $PERCENT_OF_FREE_FOR_APACHE"

#MEM_TOTAL=`cat /proc/meminfo | grep MemTotal | awk '{print $2}'`
#echo "Total system memory (kB): $MEM_TOTAL"

MEM_SINGLE_APACHE=`ps -o pid -C apache2 | tail -1 | xargs pmap -x | grep  total | awk '{print $4}'`
echo "Estimated memory used by a single Apache process (kB): $MEM_SINGLE_APACHE"

echo "Estimating free memory without Apache..please wait"
service apache2 stop > /dev/null
sleep 20
MEM_FREE_NO_APACHE=`free | grep buffers/cache | awk '{print $4'}`
service apache2 start > /dev/null
echo "Free memory without Apache: $MEM_FREE_NO_APACHE"


MEM_FREE_FOR_APACHE=`echo "scale=2;($PERCENT_OF_FREE_FOR_APACHE/100.0)*$MEM_FREE_NO_APACHE" | bc`
echo "Estimated free memory usable by Apache (kB): $MEM_FREE_FOR_APACHE"

#some constants
MAGIC=2.5

MAX_CLIENTS=`echo "scale=0;($MEM_FREE_FOR_APACHE/($MEM_SINGLE_APACHE))*$MAGIC" | bc`
echo "Recommended MaxClients/MaxRequestWorkers: $MAX_CLIENTS"