Skip to content

Creating your own process condition

przeroone edited this page Nov 21, 2011 · 3 revisions

Bluepill comes with only two process conditions: CPU and Memory, but it’s simple to create your own. This article shows you how to do that.

The CPU ProcessCondition looks like this (a less verbose version is also available, see bottom of page):

module Bluepill
  module ProcessConditions
    class CpuUsage < ProcessCondition
      def initialize(options = {})
        @below = options[:below]
      end
      def run(pid)
        System.cpu_usage(pid).to_f
      end
      def check(value)
        value < @below
      end
    end
  end
end

And you use it like this
process.checks :cpu_usage, :every => 10, :below => 0.5, :times => [5, 5]

The :cpuusage needs to match up to the class name of your ProcessCondition, the every and times options are handled externally to your implementation of ProcessCondition. The run method should return a value which is stored by Bluepill based on the parameters to the :times option. The check method should return _true or false based on whether it is within range or not. A true value means everything is okay and a false value means it’s not.

The run method is called based on the interval set by the every option and it is passed the process’ current PID. Bluepill then calls the check method with the value returned by run and stores its return value internally as well.

The following 3 options are handled by bluepill: times, every, and fires. Anything else is passed onto the ProcessCondition and expects to be handled there.

You can optionally implement a format_value method that gets the value returned from run and formats it for the log file. You can use this to change the scale from KB to MB, or add units, or whatever else makes sense for your ProcessCondition.

Once you’ve implemented your ProcessCondition, just include it at the top of your pill config file and bluepill will detect it by its name. Make sure it’s wrapped by the right set of modules: Bluepill::ProcessConditions and it inherits from ProcessCondition, like in the example above.

Alternate Definition Format

As of version 0.0.29 you can define your process conditions like this instead of the more verbose method used above:

Bluepill.define_process_condition(:cpu_usage) do
  def run(pid)
    # do work
  end

  def check(value)
    # check value
  end
end

You must define at least run and check, and you can optionally implement format_value and initialize. The default constructor takes the options hash and puts them in a instance variable named @options.

Clone this wiki locally