public
Last active

Nagios check for Hudson/Jenkins job status using the JSON API

  • Download Gist
check_hudson_job.pl
Perl
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
#!/usr/bin/perl
use strict;
use LWP::UserAgent;
use JSON;
 
#
# Check Hudson job status using the JSON API
#
# (c) 2009 Robin Bramley, Opsera Ltd.
# Copying and distribution of this file, with or without modification,
# are permitted in any medium without royalty provided the copyright
# notice and this notice are preserved. This file is offered as-is,
# without any warranty.
#
 
# Nagios return values
# OK = 0
# WARNING = 1
# CRITICAL = 2
# UNKNOWN = 3
 
my $retStr = "Unknown - plugin error";
my @alertStrs = ("OK", "WARNING", "CRITICAL", "UNKNOWN");
my $exitCode = 3;
my $numArgs = $#ARGV + 1;
 
# check arguments
if ( $numArgs != 2 && $numArgs != 4 ) {
print "Usage: check_hudson_job url jobname [username password]\n";
exit $exitCode;
}
 
my $jobName = $ARGV[1];
 
my $ua = LWP::UserAgent->new;
my $req = HTTP::Request->new( GET => $ARGV[0] );
 
# perform basic auth if necessary
if ( $numArgs == 4 ) {
$req->authorization_basic( $ARGV[2], $ARGV[3] );
}
 
# make request to Hudson
my $res = $ua->request($req);
 
# if we have a HTTP 200 OK response
if ( $res->is_success ) {
my $json = new JSON;
 
# get content
my $obj = $json->decode( $res->content );
 
# loop counter
my $n = 0;
 
# loop through the jobs (this depends on 'overall' read permission
# AND 'jobs' read permission in a secure Hudson config)
while ( $obj->{'jobs'}[$n] ) {
 
# is this the job we're looking for?
if ( $obj->{'jobs'}[$n]->{name} eq $jobName ) {
$retStr = "$obj->{'jobs'}[$n]->{name} = $obj->{'jobs'}[$n]->{color}";
 
if ( $obj->{'jobs'}[$n]->{color} eq "blue" ) {
$exitCode = 0;
}
elsif ( $obj->{'jobs'}[$n]->{color} eq "red" ) {
$exitCode = 2;
}
 
last;
}
 
$n++;
}
 
}
else {
$retStr = $res->status_line;
$exitCode = 1;
}
 
print $alertStrs[$exitCode] . " - $retStr\n";
exit $exitCode;

Hi,

in this line: my $obj = $json->decode( $res->content );

i got the error:

malformed JSON string, neither array, object, number, string or atom, at character offset 0 (before "

\n \n...") at huson_teste.pl line 40

Need help please...

facing same error.
malformed JSON string, neither array, object, number, string or atom, at character offset 4 (before "<!DOCTYPE html><html...") at each_job.pl line 45

i had the same problem, but when i checked the returned document is regular HTML not JSON. So check Google and found that you have to add /api/json (e.g. http://server/jenkins/api/json) to your URL and them it's working just fine.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.