Skip to content

Instantly share code, notes, and snippets.

@kwakwaversal
Last active September 18, 2017 14:23
Show Gist options
  • Save kwakwaversal/d72c7a3d8a1121f32d39 to your computer and use it in GitHub Desktop.
Save kwakwaversal/d72c7a3d8a1121f32d39 to your computer and use it in GitHub Desktop.
Nagios check - checks JSON url and path and outputs a nagios friendly response #perl #shell
#!/usr/bin/env perl
use Mojo::Base -strict;
use Mojo::UserAgent;
die "Usage: $0 http://api.github.com/v1/connected /users[=10] [API_NAME]\n"
unless scalar @ARGV >= 2;
my $url = shift;
my $path = shift;
my $program = shift // 'JSON';
# It is possible to compare the value of a path with an expected value
#
# This is achieved by added =SOMEVALUE to the path.
my $compare = undef;
my $cmp_op = undef;
if ($path =~ m,^(.*?)([=><])(.*)$,) {
$path = $1;
$cmp_op = $2;
$compare = $3;
}
my $ua = Mojo::UserAgent->new;
my $tx = $ua->get($url);
if (my $res = $tx->success) {
my $data = $res->json($path);
if ($data) {
my $value = $data;
if (ref $data && ref $data eq 'HASH') {
$value = scalar keys %{$data};
}
elsif (ref $data && ref $data eq 'ARRAY') {
$value = scalar @{$data};
}
# compare the expected output if $compare exists, else just print response
if (defined $compare) {
if ($cmp_op eq '=') {
if ($value ne $compare) {
nagios_response(status => "WARNING $value ne $compare", value => $value);
}
}
elsif ($cmp_op eq '>') {
if ($value < $compare) {
nagios_response(status => "WARNING $value !> $compare", value => $value);
}
}
elsif ($cmp_op eq '<') {
if ($value > $compare) {
nagios_response(status => "WARNING $value !< $compare", value => $value);
}
}
}
nagios_response(status => 'OK', value => $value);
}
# the JSON path does not exist, or is undef
nagios_response(status => 'WARNING');
}
else {
my $err = $tx->error;
$err->{code} //= '';
$err->{message} //= '';
nagios_response(
status => "CRITICAL $err->{code} response: $err->{message}");
}
sub nagios_response {
my %params = @_;
$params{status} //= 'OK';
$params{value} //= 0;
$params{warn_value} = '';
$params{crit_value} = '';
$params{bottom_line} = 0;
$params{top_line} //= 100;
unless (defined $params{exit}) {
if ($params{status} =~ m,OK,) {
$params{exit} = 0;
}
elsif ($params{status} =~ m,WARNING,) {
$params{exit} = 1;
}
elsif ($params{status} =~ m,CRITICAL,) {
$params{exit} = 2;
}
elsif ($params{status} =~ m,UNKNOWN,) {
$params{exit} = 3;
}
}
# prepend the name of the program to the status
$params{status} = "$program $params{status}";
printf "%s | Value=%s;%s;%s;%s;%s\n", $params{status}, $params{value},
$params{warn_value}, $params{crit_value}, $params{bottom_line},
$params{top_line};
exit $params{exit};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment