Skip to content

Instantly share code, notes, and snippets.

@rbramley
Created May 10, 2011 10:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rbramley/964246 to your computer and use it in GitHub Desktop.
Save rbramley/964246 to your computer and use it in GitHub Desktop.
Nagios check for Hudson/Jenkins job status using the JSON API
#!/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;
@vavazita
Copy link

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...

@MangeshBiradar
Copy link

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

@aroth-fastprotect
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment