#!/usr/bin/perl

use strict;
use warnings;

my $debug = 0;

print "===== Stop Runaway Hadoop Nodes =====\n";

print " * Searching running processes...\n";
open(FIN, 'ps ax -o pid,command |') or die($!);
my $line = '';
my $found_process = 0;
while (($line = <FIN>))
{
  # Kill import processes
  if ($line =~ /^\s*(\d+)\s+(.*)java -Dproc_(datanode|jobtracker|namenode|secondarynamenode|tasktracker)/)
  {
    my $pid = $1;
    my $prefix = $2;
    my $type = $3;
    print " - Found " . $type . " process: [" . $pid . "]... ";
    my $cmd = 'kill -KILL ' . $pid;
    if ($debug)
    {
      print "[DEBUG] " . $cmd . "\n";
    }
    else
    {
      `$cmd`;
      print "Process killed!\n";
    }
    $found_process = 1;
  }
}
close(FIN);

if (!$found_process)
{
  print " * No running Hadoop processes found!\n";
}

print "Complete!\n\n";

exit;
