Ohai.plugin(:TileCache) do
  provides "tilecache"

  def tile_siblings
    recent = Time.now - 600
    times = Hash.new

    # Find performance reports for last few minutes
    # Add up total time taken to download tile grouped by remote server
    # Remove 1 second per successful time report (de-prioritise new servers)
    # Add 10 seconds per failed time report request
    Dir.glob("/srv/tilecache/data/**/tilecache-*.txt").each do |path|
      if File.mtime(path) > recent
        IO.readlines(path).reverse.take(20).each do |sample|
          if sample =~ %r{^(\d+\.\d+),(\d+),https://([^/]+)/} then
            time = Regexp.last_match(1).to_f
            status = Regexp.last_match(2).to_i
            host = Regexp.last_match(3)

            if status == 200 then
              times[host] = times.fetch(host, 0) + time - 1
            else
              times[host] = times.fetch(host, 0) + 10
            end
          end
        end
      end
    end

    # Sort time reports
    # Strip to best 4 server names
    times.to_a.sort_by(&:last).take(4).map(&:first)
  end

  collect_data(:default) do
    tilecache Mash.new

    tilecache[:tile_siblings] = tile_siblings
  end
end

Ohai.plugin(:TileCache) do
  provides "tilecache"

  def tile_siblings
    recent = Time.now - 600
    times = Hash.new

    # Find performance reports for last few minutes
    # Add up total time taken to download tile grouped by remote server
    # Remove 1 second per successful time report (de-prioritise new servers)
    # Add 10 seconds per failed time report request
    Dir.glob("/srv/tilecache/data/**/tilecache-*.txt").each do |path|
      if File.mtime(path) > recent
        IO.readlines(path).reverse.take(20).each do |sample|
          if sample =~ %r{^(\d+\.\d+),(\d+),https://([^/]+)/} then
            time = Regexp.last_match(1).to_f
            status = Regexp.last_match(2).to_i
            host = Regexp.last_match(3)

            if status == 200 then
              times[host] = times.fetch(host, 0) + (time + 1) * (time + 1) - 1
            else
              times[host] = times.fetch(host, 0) + 10
            end
          end
        end
      end
    end

    # Sort time reports
    # Strip to best 4 server names
    times.to_a.sort_by(&:last).take(4).map(&:first)
  end

  collect_data(:default) do
    tilecache Mash.new

    tilecache[:tile_siblings] = tile_siblings
  end
end

Adjust performance scoring for tile siblings
Adjust performance scoring for tile siblings
