class Nagios::PluginBase

Constants

CODES

exit codes

OPTOINS

well known options

VERSION

Public Class Methods

check!(*args,&block) click to toggle source

instant check

# File lib/nagios_plugin_base.rb, line 111
def self.check!(*args,&block)
  opt = self.new(args)
  opt.parse!(ARGV)
  opt.run do |opta|
    opt.instance_eval(&block)
  end
end
new(args=[]) click to toggle source

@param [Array<Symbol>] args option parser arguments

# File lib/nagios_plugin_base.rb, line 84
def initialize(args=[])
  @opt = OptionParser.new
  args.each{|a| option(a)}
end

Public Instance Methods

exit_(code) click to toggle source

Print status (ex: OK) and exit @param [Integer] :code

# File lib/nagios_plugin_base.rb, line 53
def exit_(code)
  if CODES[code]
    puts "#{CODES[code]}"
    exit code
  else
    raise "unknown exit code #{code}"
  end
end
invalid_args!(message=nil) click to toggle source

Print message and option helps, and exit as UNKNOWN. this is default style of argument error.

# File lib/nagios_plugin_base.rb, line 46
def invalid_args!(message=nil)
  puts message if message
  puts @opt.help
  unknown!
end
option(arg) click to toggle source

set option to option parser @param [Symbol] :arg option from OPTIONS

# File lib/nagios_plugin_base.rb, line 76
def option(arg)
  if OPTOINS[arg]
    set_default_option(arg, OPTOINS[arg])
  else
    raise "unknwon nagios plugin option #{arg}"
  end
end
parse!(argv) click to toggle source

parse option @param [Array] argv cmmand line argumetns

# File lib/nagios_plugin_base.rb, line 90
def parse!(argv)
  begin
    @opt.parse!(argv)
  rescue OptionParser::InvalidOption => e
    invalid_args!(e.to_s)
  end
end
run() { || ... } click to toggle source

Run block with timeout. @yield Main check callback block. @yieldreturn [Integer] exit code.

# File lib/nagios_plugin_base.rb, line 100
def run
  Timeout.timeout(@timeout) do
    ret = yield
    raise "block need exit code" unless ret
    exit_(ret)
  end
rescue Timeout::Error => e
  puts "timeout"
  critical!
end
set_default_option(arg, options) click to toggle source

Add option to option parser and create attribute-reader to self @param [Symbol] arg Option name @param [Array] options Option arguments for optparse

# File lib/nagios_plugin_base.rb, line 64
    def set_default_option(arg, options)
      @opt.on(*options){|v|
        instance_variable_set("@#{arg}".to_sym, v)
      }
      eval <<-CODE
        class << self
          define_method(:#{arg}){ @#{arg} }
        end
      CODE
    end