# 
# created by Vitalie Lazu on Mon, 05 Nov 2007 20:28:57 +0200
#

require 'rubygems'
require 'hpricot'
require 'open-uri'

class ApacheStatus
  attr_accessor :doc, :data

  def initialize()
    self.data = []
  end

  # row keys
  # :srv, :pid, :acc, :m, :cpu, :ss, :req, :conn, :child, :slot, :client, :vhost, :request
  #
  # Srv     Child Server number - generation
  # PID     OS process ID
  # Acc     Number of accesses this connection / this child / this slot
  # M       Mode of operation
  # CPU     CPU usage, number of seconds
  # SS      Seconds since beginning of most recent request
  # Req     Milliseconds required to process most recent request
  # Conn    Kilobytes transferred this connection
  # Child   Megabytes transferred this child
  # Slot    Total megabytes transferred this slot
  def parse(url)
    self.doc = Hpricot(open(url))
    tab = doc.search("//table").first
    keys = []

    tab.search("//th").each do |e|
      keys << e.inner_text.chomp.downcase.to_sym
    end

    self.data = []

    tab.search("//tr").each do |tr|
      i = 0
      rez = {}

      tr.search("//td").each do |td|
        rez[keys[i]] = td.inner_text.chomp
        i += 1
      end

      data << rez if rez.size > 0
    end
  end
end

cl = ApacheStatus.new
cl.parse("http://localhost/server-status")
kill_pids = {}

cl.data.each do |row|
  if row[:m] == "L" && row[:ss].to_i > 120 # 2 minutes
    kill_pids[row[:pid]] = 1
    puts "Long logging pid: #{row[:pid]}, ss: #{row[:ss]}"
#  elsif row[:m] == "W"
    #puts row[:request]
  end
end

if kill_pids.size > 0
  cmd = "kill -9 #{kill_pids.keys * ' '}"
  puts "I will #{cmd}"
  system(cmd)
end

