Monitoring apache VirtualHosts activity
For the last few days I've been monitoring (using the classic top utility) the load of apache processes in one of my webservers. Everything went as expected but, from time to time, one of the apache processes went crazy, reaching 40-50% of CPU use. It is not so important, but I began to think about how usefult it would be to know which VirtualHost is accessed by the request managed by such apache process...
Being honest, my first thought was to code something to do it, but soon I realized it should exist already a tool to do it. A quick search through google and I found an option, apachetop (which is already in the FreeBSD ports). This tool simply does some parsing on apache access logs and show in real time the urls that are being accessed.
It is a useful tool, for sure, but it was not what I was searching for. So, I did some more research, just to find apache-top.
Apache-top is a small python script that will monitor an apache web server /server-status url (more info on the mod_status page from the apache project), displaying it's information in a top-like curses interface. This information includes the pid of each apache process, the VirtualHost ServerName for the request handled by such process and a lot more information.
In FreeBSD to get it working you only have to edit /usr/local/etc/apache22/httpd.conf (if you are using other version than apache 2.2, it could be apache2/ or apache/ instead of apache22/) and uncomment the line:
#Include etc/apache22/extra/httpd-info.conf
Then you will have to edit /usr/local/etc/apache22/extra/httpd-info.conf. There you have to locate the <Location /server-status> directive and change:
Allow from .example.com
to
Allow from 127.0.0.1
This way, you will allow only requests from localhost for the /server-status location (just as a security measure).
Next, uncomment the following line (to activate extended reports):
ExtendedStatus On
And comment the following ones (as they are not needed for apache-top:
<Location /server-info> SetHandler server-info Order deny,allow Deny from all Allow from .example.com </Location>
Then you will have to restart apache, to the changes to have effect:
sudo /usr/local/etc/rc.d/apache22 restart
Ok, almost done, now you will have to download apache-top.py (http://www.fr3nd.net/stuff/projects/apache-top/apache-top.py) and you can rename it to get rid of the .py extension:
cd ~/bin && wget http://www.fr3nd.net/stuff/projects/apache-top/apache-top.py && mv apache-top.py apache-top
Finally, you can call apache-top from a shell to get the information:
apache-top -u http://localhost/server-status
and you should get something like:

Nice, isn't it?
There you will see not only the apache process and the related vhost access, but the cpu load, the ip address from the request is coming and even the url accessed. That's pretty much the thing I was searching for :D