Skip to content

Instantly share code, notes, and snippets.

@jcsalterego
Created December 3, 2012 22:39
Show Gist options
  • Select an option

  • Save jcsalterego/4198791 to your computer and use it in GitHub Desktop.

Select an option

Save jcsalterego/4198791 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'optparse'
require 'rubygems'
require 'json'
require 'open-uri'
require 'pp'
require 'nagios'
JENKINS_HOST = 'localhost'
JENKINS_PORT = 8080
def find_latest_build(job)
url = "http://#{JENKINS_HOST}:#{JENKINS_PORT}/jobs/job/#{job}/lastBuild/api/json?pretty=true"
open(url) do |file|
contents = file.read
doc = JSON.parse(contents)
doc['duration'] = Time.now.utc.to_i - Time.at(doc["timestamp"]/1000).to_i
JenkinsJob.new(doc)
end
rescue OpenURI::HTTPError => e
JenkinsJob.new(:error=>:not_found)
rescue => e
JenkinsJob.new(:error=>:unknown)
end
class JenkinsJob
def initialize(info)
@info = info
end
def error?
!@info[:error].nil?
end
def not_found?
@info[:error] = :not_found
end
def duration
@info['duration'].to_i if exists?
end
def is_building?
@info['building'] == true
end
def exists?
!@info["id"].nil?
end
def name
@info['fullDisplayName']
end
def url
@info['url']
end
end
class JenkinsAgePlugin < Nagios::Plugin
def measure
find_latest_build($options[:job_name])
end
def critical(job)
job.is_building? && job.duration > $options[:critical]
end
def warning(job)
job.is_building? && job.duration > $options[:warning]
end
def msg(job)
if !job.exists?
"No job found"
elsif !job.is_building?
"No job currently building"
else
{ :duration=>job.duration,
:url=>job.url,
:name=>job.name,
}.inspect
end
end
alias :ok_msg :msg
alias :warning_msg :msg
alias :critical_msg :msg
end
def main
$options = {}
OptionParser.new do |opts|
opts.on("-w THRESHOLD", Integer) do |threshold|
$options[:warning] = threshold
end
opts.on("-c THRESHOLD", Integer) do |threshold|
$options[:critical] = threshold
end
opts.on("-j JOBNAME") do |job_name|
$options[:job_name] = job_name
end
end.parse!
incomplete = [:warning, :critical, :job_name].any? do |option|
!$options.has_key?(option)
end
if incomplete
puts "#{$0} -w <warning> -c <critical> -j <job_name>"
exit 3
else
JenkinsAgePlugin.new.run!
end
end
if $0 == __FILE__
main
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment