Monday, October 25, 2010

The horrible Linux out-of-memory killer and Java


The symptoms : your favorite Java process is being terminated with no apparent cause. sometimes you may see the mysterious "Killed" as a last note on the stderr, but sometimes even this last grace will be denied.

To verify : cat /var/log/syslog | grep "Out of memory" , and look for your process id. 

What is the out-of-memory killer (hence OOMK), and why it is horrible : some facts (and views) can be found in the following links :
I'll just summarize by saying it's like a mad banker - it gives the client (a process) IOU notes ( "memory" ), when the client wishes to cash-in (use the memory) , it gives it some real money (physical memory - ram or swap) , but if there is currently not enough money, it selects one of the clients and kills him ...


What to do : remember , the fact process X had been chosen by the OOMK does not mean it is leaking, or even consuming more memory than before.  in fact, in the specific case I was exploring, it seems the OOMK was very fond of killing Java (and mysql server ) processes , probably due to their memory allocation pattern - i.e. allocating ,and using, large self-managed buffers . 

So, in my case, the solution was to monitor the system carefully with the following script (let's call it psmon)
#!/bin/bash

FREQ=60

while getopts pmf:t OPT; do
case "$OPT" in
    p)    PROCESSMEM="true"
        ;;
    m)    SYSMEM="true"
        ;;
    f)    FREQ=$OPTARG
         ;;
     t)    TIMESTAMP="true"
        ;;
    esac
done

while [ 1 ]; do
    echo "-------------------------------------------"
    if [ "$TIMESTAMP" == "true" ]; then
        date +%s
    fi
    if [ "$PROCESSMEM" == "true" ]; then
        ps -eo pid,ppid,rss,vsize,pcpu,pmem,cmd -ww --sort=pid
    fi
    if [ "$SYSMEM" == "true" ]; then
        free -mt
    fi
    sleep $FREQ   
done

for example :
psmon -f 1 -p -m -t >/tmp/psmon.out &
and then run the application, and wait for the OOMK.

I could then read from the syslog the time when the  OOMK was invoked ,
and look at the memory consumption per process just prior to that time, and sure enough, I've found a very short , very high peak usage of both RAM and virtual memory in one of our native processes (which was never harmed by the OOMK).








 



No comments:

Post a Comment