check_junos_bgp.pl 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. #!/usr/bin/perl
  2. #############################################################################
  3. # (c) 2001, 2003 Juniper Networks, Inc. #
  4. # (c) 2011 Sebastian "tokkee" Harl <sh@teamix.net> #
  5. # and team(ix) GmbH, Nuernberg, Germany #
  6. # #
  7. # This file is part of "team(ix) Monitoring Plugins" #
  8. # URL: http://oss.teamix.org/projects/monitoringplugins/ #
  9. # #
  10. # All rights reserved. #
  11. # Redistribution and use in source and binary forms, with or without #
  12. # modification, are permitted provided that the following conditions #
  13. # are met: #
  14. # 1. Redistributions of source code must retain the above copyright #
  15. # notice, this list of conditions and the following disclaimer. #
  16. # 2. Redistributions in binary form must reproduce the above copyright #
  17. # notice, this list of conditions and the following disclaimer in the #
  18. # documentation and/or other materials provided with the distribution. #
  19. # 3. The name of the copyright owner may not be used to endorse or #
  20. # promote products derived from this software without specific prior #
  21. # written permission. #
  22. # #
  23. # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR #
  24. # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED #
  25. # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE #
  26. # DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, #
  27. # INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES #
  28. # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR #
  29. # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) #
  30. # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, #
  31. # STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING #
  32. # IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE #
  33. # POSSIBILITY OF SUCH DAMAGE. #
  34. #############################################################################
  35. use strict;
  36. use warnings;
  37. use utf8;
  38. use Data::Dumper;
  39. use POSIX qw( :termios_h );
  40. use Nagios::Plugin;
  41. use Regexp::Common;
  42. use Regexp::IPv6 qw( $IPv6_re );
  43. use JUNOS::Device;
  44. binmode STDOUT, ":utf8";
  45. my $valid_checks = "peers_count|prefix_count";
  46. my $plugin = Nagios::Plugin->new(
  47. plugin => 'check_junos_bgp',
  48. shortname => 'check_junos_bgp',
  49. version => '0.1',
  50. url => 'http://oss.teamix.org/projects/monitoringplugins',
  51. blurb => 'Monitor Juniper™ Router\'s BGP tables.',
  52. usage =>
  53. "Usage: %s [-v|--verbose] [-H <host>] [-p <port>] [-t <timeout]
  54. [-U <user>] [-P <password] check-tuple [...]",
  55. license =>
  56. "This nagios plugin is free software, and comes with ABSOLUTELY NO WARRANTY.
  57. It may be used, redistributed and/or modified under the terms of the 3-Clause
  58. BSD License (see http://opensource.org/licenses/BSD-3-Clause).",
  59. extra => "
  60. This plugin connects to a Juniper™ Router device and requests BGP table
  61. information using the 'show bgp neighbor' command. It then checks the
  62. specified thresholds depending on the specified checks.
  63. A check-tuple consists of the name of the check and, optionally, a \"target\"
  64. (e.g., peer address), and warning and critical thresholds:
  65. checkname[,target[,warning[,critical]]]
  66. The following checks are available:
  67. * peers_count: Total number of peers. If a target is specified, only peers
  68. matching that target are taken into account.
  69. * prefix_count: Number of active prefixes for a single peer. If multiple
  70. peers match the specified target, each of those is checked against the
  71. specified thresholds.
  72. Targets are either specified as IPv4/IPv6 addresses or regular expressions /
  73. strings. In the former case, the target is compared against the peer's
  74. address, else against the peer's description. When specifying regular
  75. expressions, they have to be enclosed in '/'. Else, the pattern is treated as
  76. verbatim string that has to be matched.
  77. Warning and critical thresholds may be specified in the format documented at
  78. http://nagiosplug.sourceforge.net/developer-guidelines.html#THRESHOLDFORMAT.",
  79. );
  80. # Predefined arguments (by Nagios::Plugin)
  81. my @predefined_args = qw(
  82. usage
  83. help
  84. version
  85. extra-opts
  86. timeout
  87. verbose
  88. );
  89. my @args = (
  90. {
  91. spec => 'host|H=s',
  92. usage => '-H, --host=HOSTNAME',
  93. desc => 'Hostname/IP of Juniper box to connect to',
  94. default => 'localhost',
  95. },
  96. {
  97. spec => 'port|p=i',
  98. usage => '-p, --port=PORT',
  99. desc => 'Port to connect to',
  100. default => 22,
  101. },
  102. {
  103. spec => 'user|U=s',
  104. usage => '-U, --user=USERNAME',
  105. desc => 'Username to log into box as',
  106. default => 'root',
  107. },
  108. {
  109. spec => 'password|P=s',
  110. usage => '-P, --password=PASSWORD',
  111. desc => 'Password for login username',
  112. default => '<prompt>',
  113. },
  114. );
  115. my %conf = ();
  116. my $junos = undef;
  117. my $neigh_info = undef;
  118. my @peers = ();
  119. foreach my $arg (@args) {
  120. add_arg($plugin, $arg);
  121. }
  122. $plugin->getopts;
  123. # Initialize this first, so it may be used right away.
  124. $conf{'verbose'} = $plugin->opts->verbose;
  125. foreach my $arg (@args) {
  126. my @c = get_conf($plugin, $arg);
  127. $conf{$c[0]} = $c[1];
  128. }
  129. foreach my $arg (@predefined_args) {
  130. $conf{$arg} = $plugin->opts->$arg;
  131. }
  132. add_checks(\%conf, @ARGV);
  133. if (! $plugin->opts->password) {
  134. my $term = POSIX::Termios->new();
  135. my $lflag;
  136. print "Password: ";
  137. $term->getattr(fileno(STDIN));
  138. $lflag = $term->getlflag;
  139. $term->setlflag($lflag & ~POSIX::ECHO);
  140. $term->setattr(fileno(STDIN), TCSANOW);
  141. $conf{'password'} = <STDIN>;
  142. chomp($conf{'password'});
  143. $term->setlflag($lflag | POSIX::ECHO);
  144. $term->setattr(fileno(STDIN), TCSAFLUSH);
  145. print "\n";
  146. }
  147. verbose(1, "Connecting to host $conf{'host'} as user $conf{'user'}.");
  148. $junos = JUNOS::Device->new(
  149. hostname => $conf{'host'},
  150. login => $conf{'user'},
  151. password => $conf{'password'},
  152. access => 'ssh',
  153. 'ssh-compress' => 0);
  154. if (! ref $junos) {
  155. $plugin->die("ERROR: failed to connect to " . $conf{'host'} . "!");
  156. }
  157. verbose(1, "Querying BGP neighbor information.");
  158. $neigh_info = get_neighbor_information($junos);
  159. if (! ref $neigh_info) {
  160. $plugin->die($neigh_info);
  161. }
  162. @peers = $neigh_info->getElementsByTagName('bgp-peer');
  163. if ($conf{'verbose'} >= 3) {
  164. my @p = map { get_peer_address($_) . " => " . get_peer_description($_) } @peers;
  165. verbose(3, "Peers: " . join(", ", @p));
  166. }
  167. foreach my $check (@{$conf{'checks'}}) {
  168. my $code;
  169. my $value;
  170. my @relevant_peers = get_relevant_peers($check, @peers);
  171. if ($conf{'verbose'} >= 2) {
  172. my @p = map { get_peer_address($_) . " => " . get_peer_description($_) } @relevant_peers;
  173. verbose(2, "Relevant peers: " . join(", ", @p));
  174. }
  175. $plugin->set_thresholds(
  176. warning => $check->{'warning'},
  177. critical => $check->{'critical'},
  178. );
  179. if ($check->{'name'} eq 'peers_count') {
  180. $value = scalar(@relevant_peers);
  181. $code = $plugin->check_threshold($value);
  182. $plugin->add_message($code, "$value peer" . (($value == 1) ? "" : "s"));
  183. $plugin->add_perfdata(
  184. label => 'peers_count',
  185. value => $value,
  186. min => 0,
  187. max => undef,
  188. uom => '',
  189. threshold => $plugin->threshold(),
  190. );
  191. }
  192. elsif ($check->{'name'} eq 'prefix_count') {
  193. foreach my $peer (@relevant_peers) {
  194. my $peer_addr = get_peer_address($peer);
  195. $value = get_peer_element($peer, 'peer-state');
  196. verbose(2, "Peer $peer_addr: peer-state = $value.");
  197. if ($value eq 'Established') {
  198. $value = $peer->getElementsByTagName('bgp-rib');
  199. $value = get_peer_element($value->[0], 'active-prefix-count');
  200. $code = $plugin->check_threshold($value);
  201. $plugin->add_message($code, "peer $peer_addr: $value prefix"
  202. . (($value == 1) ? "" : "es"));
  203. verbose(2, "Peer $peer_addr: active-prefix-count = $value.");
  204. }
  205. else {
  206. $value = "";
  207. $code = CRITICAL;
  208. $plugin->add_message($code,
  209. "peer $peer_addr: no established connection");
  210. }
  211. $plugin->add_perfdata(
  212. label => '\'prefix_count[' . $peer_addr . ']\'',
  213. value => $value,
  214. min => 0,
  215. max => undef,
  216. uom => '',
  217. threshold => $plugin->threshold(),
  218. );
  219. }
  220. }
  221. }
  222. my ($code, $msg) = $plugin->check_messages(join => ', ');
  223. $junos->disconnect();
  224. $plugin->nagios_exit($code, $msg);
  225. sub send_query
  226. {
  227. my $device = shift;
  228. my $query = shift;
  229. my $queryargs = shift;
  230. my $res;
  231. my $err;
  232. verbose(3, "Sending query '$query' to router.");
  233. if (ref $queryargs) {
  234. $res = $device->$query(%$queryargs);
  235. } else {
  236. $res = $device->$query();
  237. }
  238. verbose(5, "Got response: " . Dumper(\$res));
  239. if (! ref $res) {
  240. return "ERROR: Failed to execute query '$query'";
  241. }
  242. $err = $res->getFirstError();
  243. if ($err) {
  244. return "ERROR: " . $err->{message};
  245. }
  246. return $res;
  247. }
  248. sub get_neighbor_information
  249. {
  250. my $device = shift;
  251. my @table;
  252. my $query = "get_bgp_summary_information";
  253. my $res = send_query($device, $query);
  254. my $err;
  255. if (! ref $res) {
  256. return $res;
  257. }
  258. $err = $res->getFirstError();
  259. if ($err) {
  260. return "ERROR: " . $err->{message};
  261. }
  262. return $res;
  263. }
  264. sub add_arg
  265. {
  266. my $plugin = shift;
  267. my $arg = shift;
  268. my $spec = $arg->{'spec'};
  269. my $help = $arg->{'usage'};
  270. if (defined $arg->{'desc'}) {
  271. my @desc;
  272. if (ref($arg->{'desc'})) {
  273. @desc = @{$arg->{'desc'}};
  274. }
  275. else {
  276. @desc = ( $arg->{'desc'} );
  277. }
  278. foreach my $d (@desc) {
  279. $help .= "\n $d";
  280. }
  281. if (defined $arg->{'default'}) {
  282. $help .= " (default: $arg->{'default'})";
  283. }
  284. }
  285. elsif (defined $arg->{'default'}) {
  286. $help .= "\n (default: $arg->{'default'})";
  287. }
  288. $plugin->add_arg(
  289. spec => $spec,
  290. help => $help,
  291. );
  292. }
  293. sub get_conf
  294. {
  295. my $plugin = shift;
  296. my $arg = shift;
  297. my ($name, undef) = split(m/\|/, $arg->{'spec'});
  298. my $value = $plugin->opts->$name || $arg->{'default'};
  299. if ($name eq 'password') {
  300. verbose(3, "conf: password => "
  301. . (($value eq '<prompt>') ? '<prompt>' : '<hidden>'));
  302. }
  303. else {
  304. verbose(3, "conf: $name => $value");
  305. }
  306. return ($name => $value);
  307. }
  308. sub add_single_check
  309. {
  310. my $conf = shift;
  311. my @check = split(m/,/, shift);
  312. my %c = ();
  313. if ($check[0] !~ m/\b(?:$valid_checks)\b/) {
  314. return "ERROR: invalid check '$check[0]'";
  315. }
  316. $c{'name'} = $check[0];
  317. if ((! defined($check[1])) || ($check[1] eq "")) {
  318. $c{'target'} = qr//,
  319. $c{'ttype'} = 'address',
  320. }
  321. elsif ($check[1] =~ m/^(?:$RE{'net'}{'IPv4'}|$IPv6_re)$/) {
  322. $c{'target'} = $check[1];
  323. $c{'ttype'} = 'address';
  324. }
  325. elsif ($check[1] =~ m/^\/(.*)\/$/) {
  326. $c{'target'} = qr/$1/;
  327. $c{'ttype'} = 'description';
  328. }
  329. else {
  330. $c{'target'} = $check[1];
  331. $c{'ttype'} = 'description';
  332. }
  333. $c{'warning'} = $check[2];
  334. $c{'critical'} = $check[3];
  335. # check for valid thresholds
  336. # set_threshold() will die if any threshold is not valid
  337. $plugin->set_thresholds(
  338. warning => $c{'warning'},
  339. critical => $c{'critical'},
  340. ) || $plugin->die("ERROR: Invalid thresholds: "
  341. . "warning => $c{'warning'}, critical => $c{'critical'}");
  342. push @{$conf->{'checks'}}, \%c;
  343. }
  344. sub add_checks
  345. {
  346. my $conf = shift;
  347. my @checks = @_;
  348. my $err_str = "ERROR:";
  349. if (scalar(@checks) == 0) {
  350. $conf->{'checks'}[0] = {
  351. name => 'peers_count',
  352. target => qr//,
  353. ttype => 'address',
  354. warning => undef,
  355. critical => undef,
  356. };
  357. return 1;
  358. }
  359. $conf->{'checks'} = [];
  360. foreach my $check (@checks) {
  361. my $e;
  362. $e = add_single_check($conf, $check);
  363. if ($e =~ m/^ERROR: (.*)$/) {
  364. $err_str .= " $1,";
  365. }
  366. }
  367. if ($err_str ne "ERROR:") {
  368. $err_str =~ s/,$//;
  369. $plugin->die($err_str);
  370. }
  371. }
  372. sub get_relevant_peers
  373. {
  374. my $check = shift;
  375. my @peers = @_;
  376. my @rpeers = ();
  377. my $cmp = sub {
  378. my ($a, $b, undef) = @_;
  379. if (ref $b) {
  380. my $r = $a =~ $b;
  381. verbose(3, "Checking peer '$a' against regex '$b' -> "
  382. . ($r ? "true" : "false") . ".");
  383. return $r;
  384. }
  385. else {
  386. my $r = $a eq $b;
  387. verbose(3, "Comparing peer '$a' with string '$b' -> "
  388. . ($r ? "true" : "false") . ".");
  389. return $r;
  390. }
  391. };
  392. my $get_peer_elem;
  393. if ($check->{'ttype'} eq 'description') {
  394. $get_peer_elem = \&get_peer_description;
  395. }
  396. else {
  397. $get_peer_elem = \&get_peer_address;
  398. }
  399. @rpeers = grep { $cmp->($get_peer_elem->($_), $check->{'target'}) } @peers;
  400. return @rpeers;
  401. }
  402. sub get_peer_element
  403. {
  404. my $peer = shift;
  405. my $elem = shift;
  406. $elem = $peer->getElementsByTagName($elem);
  407. return $elem->item(0)->getFirstChild->getNodeValue;
  408. }
  409. sub get_peer_description
  410. {
  411. my $peer = shift;
  412. return get_peer_element($peer, 'description');
  413. }
  414. sub get_peer_address
  415. {
  416. my $peer = shift;
  417. return get_peer_element($peer, 'peer-address');
  418. }
  419. sub verbose
  420. {
  421. my $level = shift;
  422. my @msgs = @_;
  423. if ($level > $conf{'verbose'}) {
  424. return;
  425. }
  426. foreach my $msg (@msgs) {
  427. print "V$level: $msg\n";
  428. }
  429. }