#!/bin/sh
# $Id$
# lame quickie script to snarf a core of a hung asterisk process.
# bugs to snarfastcore, blinky-lights.org  (derrick daugherty)

DATE=`date +%Y%m%d%H%M`
DUMPDIR=/var/tmp
HOSTNAME=`hostname`
ADMINEMAIL="root@localhost"

#the following should be improved
if [ -e /etc/asterisk/asterisk.conf ]; then
	RUNDIR=`grep astrundir /etc/asterisk/asterisk.conf| awk '{print $3}'`
	PID=`cat ${RUNDIR}/asterisk.pid`
else 
	PID=`ps auxwf|grep asterisk|grep vv|head -1|awk '{print $2}'`
fi

echo Snarfing asterisk core, this could take a few seconds depending
echo on how much memory is in use.
echo
echo \*\*\* WARNING \*\*\*  If the system is not already locked this will cause the 
echo \*\*\* WARNING \*\*\*  process to STOP while memory is dumped to disk.
echo

/usr/bin/gdb > /dev/null << EOF
	attach ${PID}
	gcore ${DUMPDIR}/asterisk_${DATE}.core.${PID}
	detach
	quit
EOF

echo Snarfed!  ${DUMPDIR}/asterisk_${DATE}.core.${PID}
echo


echo Trying for a backtrace of the captured core.
/usr/bin/gdb /usr/sbin/asterisk ${DUMPDIR}/asterisk_${DATE}.core.${PID} > /tmp/gdb_dump.${PID} 2> /dev/null << EOF
set prompt \n
echo --------------------------------------------------------------------------------\n
echo INFO THREAD
info thread
echo --------------------------------------------------------------------------------\n
echo THREAD APPLY ALL BT
thread apply all bt
echo --------------------------------------------------------------------------------\n
echo THREAD APPLY ALL BT FULL
thread apply all bt full
quit
EOF
echo Done trying for a bt.


echo Notifying admins of the core.
/usr/bin/mail -s "${HOSTNAME} core dumped at ${DUMPDIR}/asterisk_${DATE}.core.${PID}" ${ADMINEMAIL} < /tmp/gdb_dump.${PID}
/bin/rm /tmp/gdb_dump.${PID}
echo Done.
echo
echo Reproducible deadlocks should be posted with a full backtrace and instructions
echo to reproduce the issue at http://bugs.digium.com/    Thanks!
