#!/bin/bash
# Copyright (c) 2013 Cloudera, Inc. All rights reserved.

# This script is passed as a value to the -XX:OnOutOfMemoryError JVM option.
# Upon outofmemory error, JVM will fork a new process and exec this script.
# This script sends SIGKILL to the JVM (parent process). It also creates
# a file in the process' current working directory indicating that it exited
# due to an OOM.
# Note: We use this script instead of directly passing the "kill -9 %p" value
# because several CDH startup scripts do not double-quote the command line
# argument containing this value. This leads to a broken JVM command line.

# Enable tracing
set -x

# If dash is the system shell, there is an extra process between us and the
# JVM we want to kill
grep -q "OnOutOfMemoryError" /proc/$PPID/cmdline
RET=$?

if [ $RET -eq 0 ]; then
  TARGET=$PPID
else
  # Get the grandparent PID
  TARGET=`ps -p $PPID -o ppid=`
fi

echo `date` > killed_by_killparent_on_oom
kill -9 $TARGET
