I have a Dreamhost VPS account and have been running out of memory and experiencing the dreaded forced reboots dh impose. I found it difficult to identify the offending sites that take up all that memory on my server. Every time I login and run top it was too late or I would find a website being crawled by a search bot. How to find a trend over time, without getting too complicated? My solution was to track the memory usage with ps and write that to individual files, then sort all those files and derive the top offenders in one list. Which is web accessible (or not) for easy viewing later. If my VPS reboots, I can go back to the individual files before the forced reboot and get details of whats causing the problem.
#!/bin/bash
#no trailing slash. Be sure this dir exists.
path=/home/jason/jasonschaefer.com/memusages
logfile=index.txt
#how many days to keep files, remove after..
removeafter=5
# ps -[e]everything, [o]format
# rss is resident set size in kilobytes
# user:20 username with 20 char space so it won't revert to uid on usernames longer than 8 chars
# cmd:40 running command with 40 char column, stime=start time of cmd
# [h]hide headers, --sort=rss sorts on rss column
/bin/ps -eo rss,user:20,cmd:40,stime,pid h --sort=rss > $path/mem`date +"%F_%k-%M"`.txt
# sort unique, numeric on column 5 the pid, so we don't show duplicate processes.
# then sort numeric, reverse on column 1 the memory usage, write the top 200 lines to our logfile.
/usr/bin/sort -u -n -k 5 $path/mem*.txt | /usr/bin/sort -n -r -k 1 | head -n 200 > $path/$logfile
#find files older than $removeafter days and remove them
/usr/bin/find $path -mtime $removeafter -exec rm -fr {} \;
Don’t forget to make it executable
chmod 755 /home/jason/memusages.sh
Then setup to run in cron, to run every ten minutes of every hour, every day, every month and every day of week. Change as needed.. I have it running every minute right now. Depending on your setup you may need to run this as root to see all system processes.
crontab -e
*/10 * * * * /home/jason/memusages.sh