Skip to content

Writing Custom Conditions

Gurpartap edited this page Dec 25, 2012 · 8 revisions

Writing conditions for Cognizant is easy. Cognizant provides a PollCondition class which can be subclassed to write custom conditions.

module Cognizant
  class Process
    module Conditions
      class PollCondition
        def initialize(options = {})
          @options = options
        end

        def run(pid)
          raise "Implement in subclass!"
        end

        def check(value)
          raise "Implement in subclass!"
        end

        def format_value(value)
          value
        end
      end
    end
  end
end

Here are a few examples to follow:

Always True

module Cognizant
  class Process
    module Conditions
      class AlwaysTrue < PollCondition
        def run(pid)
          1
        end

        def check(value)
          true
        end
      end
    end
  end
end
# Implementation
process.check :always_true, :every => 2.seconds, :times => 3, :do => :restart

CPU Usage

module Cognizant
  class Process
    module Conditions
      class CpuUsage < PollCondition
        def initialize(options = {})
          # Accept a custom argument for condition. e.g. threshold.
          @above = options[:above].to_f
        end

        def run(pid)
          # Check for current value for the given process pid.
          Cognizant::System.cpu_usage(pid).to_f
        end

        def check(value)
          # Evaluate the value with threshold.
          # The result of this decides condition invoking.
          value > @above
        end
      end
    end
  end
end
# Implementation
process.check :cpu_usage, :every => 3.seconds, :above => 60, :times => 3, :do => :stop