# -*- encoding: utf-8 -*- require 'coolio' require 'evented_bluepill/util/rotational_array' module EventedBluepill module ProcessConditions class HistoryValue < Struct.new(:value, :critical) end class ProcessCondition < Coolio::TimerWatcher attr_accessor :logger attr_reader :every, :process_condition, :fires, :process, :name def initialize(name, process, options = {}) @name = name @logger = options.delete(:logger) @fires = options.delete(:fires) || :restart @every = options.delete(:every) @times = options.delete(:times) || [1,1] @times = [@times, @times] unless @times.is_a?(Array) # handles :times => 5 @process = process self.clear_history! super(@every, true) end def run raise "Implement in subclass!" end def check(value) raise "Implement in subclass!" end def format_value(value) value end def clear_history! @history = EventedBluepill::Util::RotationalArray.new(@times.last) end def to_s data = @history.collect {|v| "#{v.value}#{'*' unless v.critical}"}.join(", ") "#{@name}: [#{data}]" end protected def fired? @history.count {|v| not v.critical} >= @times.first end private def on_timer value = self.run @history << HistoryValue.new(self.format_value(value), self.check(value)) self.logger.info(self.to_s) if self.fired? @process.dispatch!(self.fires, self.to_s) logger.info "#{self.name} dispatched: #{self.fires}" end end end end end