Sha256: 35bc5a6f1870ff2d29de20da8edce2b71f6e3daed6e5eb05d462b03c127c5e14

Contents?: true

Size: 1.98 KB

Versions: 1

Compression:

Stored size: 1.98 KB

Contents

require 'yaml'
require 'open-uri'
require 'cgi'

def eval_and_fetch_constants(x)
  old = Module.constants.map{|c| c.to_s}
  eval(x)
  new = (Module.constants.map{|c| c.to_s} - old)
  new.map{|const| const_get(const) }
end

class Scout
  class Plugin
    def report(metrics)
      metrics.each do |key, value|
        Deputy.send_report "#{self.class.to_s.split('::')[1..-1]}.#{key}", value
      end
    end
  end

  def self.plugins(code)
    eval_and_fetch_constants(code).map do |container|
      interval = container.interval
      next unless plugin = plugin_in_container(container)
      [interval, plugin]
    end.compact
  end

  def self.plugin_in_container(container)
    constants = container.constants.map{|constant_name| container.const_get(constant_name)}
    constants.detect do |constant|
      constant.instance_methods.map{|m| m.to_sym }.include?(:build_report)
    end
  end
end

module Deputy
  START_MINUTE = (Time.now.to_i + 30) / 60 # we could start at 58..02 seconds -> always in middle of minute
  VERSION = File.read( File.join(File.dirname(__FILE__),'..','VERSION') ).strip

  def self.install_cron
    `crontab -l | { cat; echo "* * * * * deputy --run-plugins 2>&1 >> /tmp/deputy.log"; } | crontab -`
  end

  def self.run_plugins
    content = get("/plugins.rb")
    Scout.plugins(content).each do |interval, plugin|
      run_every_n_minutes = interval/60
      plugin.new.build_report if START_MINUTE % run_every_n_minutes == 0
    end
  end

  def self.send_report(metric, value)
    get "/report/#{CGI.escape metric}/#{CGI.escape value.to_s}"
  end

  def self.get(path)
    url = "#{sheriff_url}#{path}"
    open(url).read
  rescue => e
    e.message << url
    raise e
  end

  def self.sheriff_url
    config['sheriff_url'].sub(%r{/$},'')
  end

  def self.config
    home = File.expand_path('~')
    ["#{home}/.deputy.yml", '/etc/deputy.yml'].each do |file|
      return YAML.load(File.read(file)) if File.exist?(file)
    end
    raise "No deputy.yml found in /etc or #{home}"
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
deputy-0.1.6 lib/deputy.rb