require 'set' require_relative 'error' require_relative 'ext/num_ext' require_relative 'check_dsl' require 'forwardable' module Remon class Config using NumExt LOAD_PATHS = ["#{__dir__}/checks"] extend Forwardable def initialize(config_file: nil, config_dir: nil, load_paths: []) @config_file = config_file @config_dir = config_dir @schedule = {} @scheduler_offset = 0 @workers = 1 @task_group = { interval: 0, offset: 15, randomize: false } load_paths = Set.new(load_paths).merge(LOAD_PATHS) @dsl = CheckDsl.new load_paths.to_a end def config @config_read ||= begin read_config true end { schedule: @schedule, scheduler_offset: @scheduler_offset, process_proc: @process_proc, workers: @workers } end private def_delegators :@dsl, :check, :defcheck, :proc_check def host(host) Remon.host = host end def every(secs, randomize: false, offset: 0, &block) raise Error, "offset must be less than interval" if offset > secs before = @task_group @task_group = { interval: secs, offset: offset, randomize: randomize } yield ensure @task_group = before end def scheduler_offset(offset) @scheduler_offset = offset end def process_event(&block) @process_proc = block end def workers(workers) @workers = workers end def schedule_check(check, args = [], kwargs = {}) @schedule[@task_group] ||= Set.new if not check.is_a? Check kwargs[:ttl] ||= default_ttl(@task_group[:interval]) klass = self.check(check) check = klass.new(*args, **kwargs) end @schedule[@task_group] << check end def default_ttl(interval) 3 * interval end def read_config read_config_file @config_file if @config_file if @config_dir Dir.glob("#{@config_dir}/*.rb").each { |f| read_config_file f } end end def read_config_file(file) if not File.readable? file raise Error, "config #{file} not readable" end instance_eval(File.read(file)) rescue NoMethodError => e raise Error, "invalid option used in config: #{e.name}" end alias_method :run_check, :schedule_check end end