#!/usr/bin/ruby
#
# Alert if there are >= 2048 open-files for the brain-process
#
# This is horrid
#



require 'yaml'


class BrainFiles

   # return all possible brain PIDs
   def pids
      ret = []

      `/bin/pidof java`.chomp.split( /\s+/ ).each do |entry|
        ret.push entry
      end

      ret
   end

   # Return the open files for the given PID
   def open( pid )
     count = 0

     `/usr/bin/lsof -p #{pid}`.split( /[\r\n]/ ).each do |line|
       count += 1
     end

     count
   end
end


if __FILE__ == $PROGRAM_NAME

  def verbose(str)
    STDERR.puts(str)
  end

  #
  # Alert(s) to raise
  #
  to_raise = []


  #
  # Helper
  #
  brain  = BrainFiles.new()

  #
  # Get the pids of the brain processes
  #
  # This is an array solely because we might catch the wrong process(es)
  # by accident.
  #
  pids = brain.pids

  #
  # For each PID
  #
  pids.each do |pid|
    open = brain.open( pid )

    verbose( "Process with PID #{pid} has #{open} open files" )

    if ( open > 2048 )
      h = {}
      h[:id]      = 'bigv-brain'
      h[:summary] = "Brain Process #{pid} has #{open} files!"
      h[:detail]  = '<p>This might indicate that it is going to exhaust its limits and cease working, check with <pre>lsof -p #{pid}</pre>, and restart the brain if this keeps rising./p>'

      to_raise.push(h)
    end
  end

  # Show the output.
  puts YAML.dump(to_raise)
  exit(0)
end
