check_junos_bgp.pl 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  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] [-t <timeout] \
  54. [-H <host>] [-p <port>] [-U <user>] [-P <password] \
  55. [-L <logical-system-name>] [-I <name of instance>] check-tuple [...] ",
  56. license =>
  57. "This nagios plugin is free software, and comes with ABSOLUTELY NO WARRANTY.
  58. It may be used, redistributed and/or modified under the terms of the 3-Clause
  59. BSD License (see http://opensource.org/licenses/BSD-3-Clause).",
  60. extra => "
  61. This plugin connects to a Juniper™ Router device and requests BGP table
  62. information using the 'show bgp neighbor' command. It then checks the
  63. specified thresholds depending on the specified checks.
  64. A check-tuple consists of the name of the check and, optionally, a \"target\"
  65. (e.g., peer address), and warning and critical thresholds:
  66. checkname[,target[,warning[,critical]]]
  67. The following checks are available:
  68. * peers_count: Total number of peers. If a target is specified, only peers
  69. matching that target are taken into account.
  70. * prefix_count: Number of active prefixes for a single peer. If multiple
  71. peers match the specified target, each of those is checked against the
  72. specified thresholds.
  73. Targets are either specified as IPv4/IPv6 addresses or regular expressions /
  74. strings. In the former case, the target is compared against the peer's
  75. address, else against the peer's description. When specifying regular
  76. expressions, they have to be enclosed in '/'. Else, the pattern is treated as
  77. verbatim string that has to be matched.
  78. Warning and critical thresholds may be specified in the format documented at
  79. http://nagiosplug.sourceforge.net/developer-guidelines.html#THRESHOLDFORMAT.",
  80. );
  81. # Predefined arguments (by Nagios::Plugin)
  82. my @predefined_args = qw(
  83. usage
  84. help
  85. version
  86. extra-opts
  87. timeout
  88. verbose
  89. );
  90. my @args = (
  91. {
  92. spec => 'host|H=s',
  93. usage => '-H, --host=HOSTNAME',
  94. desc => 'Hostname/IP of Juniper box to connect to',
  95. default => 'localhost',
  96. },
  97. {
  98. spec => 'port|p=i',
  99. usage => '-p, --port=PORT',
  100. desc => 'Port to connect to',
  101. default => 22,
  102. },
  103. {
  104. spec => 'user|U=s',
  105. usage => '-U, --user=USERNAME',
  106. desc => 'Username to log into box as',
  107. default => 'root',
  108. },
  109. {
  110. spec => 'password|P=s',
  111. usage => '-P, --password=PASSWORD',
  112. desc => 'Password for login username',
  113. default => '<prompt>',
  114. },
  115. {
  116. spec => 'logical-router|L=s',
  117. usage => '-L, --logical-router=ROUTER',
  118. desc => 'Logical Router',
  119. },
  120. {
  121. spec => 'instance|I=s',
  122. usage => '-I, --instance=INSTANCE',
  123. desc => 'Instance',
  124. },
  125. );
  126. my %conf = ();
  127. my $junos = undef;
  128. my $neigh_info = undef;
  129. my @peers = ();
  130. foreach my $arg (@args) {
  131. add_arg($plugin, $arg);
  132. }
  133. $plugin->getopts;
  134. # Initialize this first, so it may be used right away.
  135. $conf{'verbose'} = $plugin->opts->verbose;
  136. foreach my $arg (@args) {
  137. my @c = get_conf($plugin, $arg);
  138. $conf{$c[0]} = $c[1];
  139. }
  140. foreach my $arg (@predefined_args) {
  141. $conf{$arg} = $plugin->opts->$arg;
  142. }
  143. add_checks(\%conf, @ARGV);
  144. if (! $plugin->opts->password) {
  145. my $term = POSIX::Termios->new();
  146. my $lflag;
  147. print "Password: ";
  148. $term->getattr(fileno(STDIN));
  149. $lflag = $term->getlflag;
  150. $term->setlflag($lflag & ~POSIX::ECHO);
  151. $term->setattr(fileno(STDIN), TCSANOW);
  152. $conf{'password'} = <STDIN>;
  153. chomp($conf{'password'});
  154. $term->setlflag($lflag | POSIX::ECHO);
  155. $term->setattr(fileno(STDIN), TCSAFLUSH);
  156. print "\n";
  157. }
  158. verbose(1, "Connecting to host $conf{'host'} as user $conf{'user'}.");
  159. $junos = JUNOS::Device->new(
  160. hostname => $conf{'host'},
  161. login => $conf{'user'},
  162. password => $conf{'password'},
  163. access => 'ssh',
  164. 'ssh-compress' => 0);
  165. if (! ref $junos) {
  166. $plugin->die("ERROR: failed to connect to " . $conf{'host'} . "!");
  167. }
  168. verbose(1, "Querying BGP neighbor information.");
  169. $neigh_info = get_neighbor_information($junos);
  170. if (! ref $neigh_info) {
  171. $plugin->die($neigh_info);
  172. }
  173. @peers = $neigh_info->getElementsByTagName('bgp-peer');
  174. if ($conf{'verbose'} >= 3) {
  175. my @p = map { (get_peer_address($_) // "<unknown address>")
  176. . " => " . (get_peer_description($_) // "<unknown description>") } @peers;
  177. verbose(3, "Peers: " . join(", ", @p));
  178. }
  179. foreach my $check (@{$conf{'checks'}}) {
  180. my $code;
  181. my $value;
  182. my @relevant_peers = get_relevant_peers($check, @peers);
  183. if ($conf{'verbose'} >= 2) {
  184. my @p = map { (get_peer_address($_) // "<unknown address>")
  185. . " => " . (get_peer_description($_) // "<unknown description>") } @relevant_peers;
  186. verbose(2, "Relevant peers: " . join(", ", @p));
  187. }
  188. $plugin->set_thresholds(
  189. warning => $check->{'warning'},
  190. critical => $check->{'critical'},
  191. );
  192. if ($check->{'name'} eq 'peers_count') {
  193. $value = scalar(@relevant_peers);
  194. $code = $plugin->check_threshold($value);
  195. $plugin->add_message($code, "$value peer" . (($value == 1) ? "" : "s"));
  196. $plugin->add_perfdata(
  197. label => 'peers_count',
  198. value => $value,
  199. min => 0,
  200. max => undef,
  201. uom => '',
  202. threshold => $plugin->threshold(),
  203. );
  204. }
  205. elsif ($check->{'name'} eq 'prefix_count') {
  206. foreach my $peer (@relevant_peers) {
  207. my $peer_addr = get_peer_address($peer);
  208. if (! defined($peer_addr)) {
  209. $peer_addr = "<unknown address>";
  210. }
  211. $value = get_peer_element($peer, 'peer-state');
  212. if (! defined($value)) {
  213. $value = "<unknown state>";
  214. }
  215. verbose(2, "Peer $peer_addr: peer-state = $value.");
  216. if ($value eq 'Established') {
  217. $value = $peer->getElementsByTagName('bgp-rib');
  218. $value = get_peer_element($value->[0], 'active-prefix-count');
  219. if (! $value) {
  220. $value = 0;
  221. }
  222. $code = $plugin->check_threshold($value);
  223. $plugin->add_message($code, "peer $peer_addr: $value prefix"
  224. . (($value == 1) ? "" : "es"));
  225. verbose(2, "Peer $peer_addr: active-prefix-count = $value.");
  226. }
  227. else {
  228. $value = "";
  229. $code = CRITICAL;
  230. $plugin->add_message($code,
  231. "peer $peer_addr: no established connection");
  232. }
  233. $plugin->add_perfdata(
  234. label => '\'prefix_count[' . $peer_addr . ']\'',
  235. value => $value,
  236. min => 0,
  237. max => undef,
  238. uom => '',
  239. threshold => $plugin->threshold(),
  240. );
  241. }
  242. }
  243. }
  244. my ($code, $msg) = $plugin->check_messages(join => ', ');
  245. $junos->disconnect();
  246. $plugin->nagios_exit($code, $msg);
  247. sub send_query
  248. {
  249. my $device = shift;
  250. my $query = shift;
  251. my $queryargs = shift;
  252. my $res;
  253. my $err;
  254. verbose(3, "Sending query '$query' to router.");
  255. if (ref $queryargs) {
  256. $res = $device->$query(%$queryargs);
  257. } else {
  258. $res = $device->$query();
  259. }
  260. verbose(5, "Got response: " . Dumper(\$res));
  261. if (! ref $res) {
  262. return "ERROR: Failed to execute query '$query'";
  263. }
  264. $err = $res->getFirstError();
  265. if ($err) {
  266. return "ERROR: " . $err->{message};
  267. }
  268. return $res;
  269. }
  270. sub get_neighbor_information
  271. {
  272. my $device = shift;
  273. my @table;
  274. my $query = "get_bgp_summary_information";
  275. my $res;
  276. my %args;
  277. if ($conf{'logical-router'} || $conf{'instance'}) {
  278. if ($conf{'logical-router'})
  279. $args{'logical-router'} = $conf{'logical-router'};
  280. if ($conf{'instance'})
  281. $args{'instance'} = $conf{'instance'};
  282. $res = send_query($device, $query, \%args);
  283. } else {
  284. my $res = send_query($device, $query);
  285. }
  286. my $err;
  287. if (! ref $res) {
  288. return $res;
  289. }
  290. $err = $res->getFirstError();
  291. if ($err) {
  292. return "ERROR: " . $err->{message};
  293. }
  294. return $res;
  295. }
  296. sub add_arg
  297. {
  298. my $plugin = shift;
  299. my $arg = shift;
  300. my $spec = $arg->{'spec'};
  301. my $help = $arg->{'usage'};
  302. if (defined $arg->{'desc'}) {
  303. my @desc;
  304. if (ref($arg->{'desc'})) {
  305. @desc = @{$arg->{'desc'}};
  306. }
  307. else {
  308. @desc = ( $arg->{'desc'} );
  309. }
  310. foreach my $d (@desc) {
  311. $help .= "\n $d";
  312. }
  313. if (defined $arg->{'default'}) {
  314. $help .= " (default: $arg->{'default'})";
  315. }
  316. }
  317. elsif (defined $arg->{'default'}) {
  318. $help .= "\n (default: $arg->{'default'})";
  319. }
  320. $plugin->add_arg(
  321. spec => $spec,
  322. help => $help,
  323. );
  324. }
  325. sub get_conf
  326. {
  327. my $plugin = shift;
  328. my $arg = shift;
  329. my ($name, undef) = split(m/\|/, $arg->{'spec'});
  330. my $value = $plugin->opts->$name || $arg->{'default'};
  331. if ($name eq 'password') {
  332. verbose(3, "conf: password => "
  333. . (($value eq '<prompt>') ? '<prompt>' : '<hidden>'));
  334. }
  335. else {
  336. verbose(3, "conf: $name => $value");
  337. }
  338. return ($name => $value);
  339. }
  340. sub add_single_check
  341. {
  342. my $conf = shift;
  343. my @check = split(m/,/, shift);
  344. my %c = ();
  345. if ($check[0] !~ m/\b(?:$valid_checks)\b/) {
  346. return "ERROR: invalid check '$check[0]'";
  347. }
  348. $c{'name'} = $check[0];
  349. if ((! defined($check[1])) || ($check[1] eq "")) {
  350. $c{'target'} = qr//,
  351. $c{'ttype'} = 'address',
  352. }
  353. elsif ($check[1] =~ m/^(?:$RE{'net'}{'IPv4'}|$IPv6_re)$/) {
  354. $c{'target'} = $check[1];
  355. $c{'ttype'} = 'address';
  356. }
  357. elsif ($check[1] =~ m/^\/(.*)\/$/) {
  358. $c{'target'} = qr/$1/;
  359. $c{'ttype'} = 'description';
  360. }
  361. else {
  362. $c{'target'} = $check[1];
  363. $c{'ttype'} = 'description';
  364. }
  365. $c{'warning'} = $check[2];
  366. $c{'critical'} = $check[3];
  367. # check for valid thresholds
  368. # set_threshold() will die if any threshold is not valid
  369. $plugin->set_thresholds(
  370. warning => $c{'warning'},
  371. critical => $c{'critical'},
  372. ) || $plugin->die("ERROR: Invalid thresholds: "
  373. . "warning => $c{'warning'}, critical => $c{'critical'}");
  374. push @{$conf->{'checks'}}, \%c;
  375. }
  376. sub add_checks
  377. {
  378. my $conf = shift;
  379. my @checks = @_;
  380. my $err_str = "ERROR:";
  381. if (scalar(@checks) == 0) {
  382. $conf->{'checks'}[0] = {
  383. name => 'peers_count',
  384. target => qr//,
  385. ttype => 'address',
  386. warning => undef,
  387. critical => undef,
  388. };
  389. return 1;
  390. }
  391. $conf->{'checks'} = [];
  392. foreach my $check (@checks) {
  393. my $e;
  394. $e = add_single_check($conf, $check);
  395. if ($e =~ m/^ERROR: (.*)$/) {
  396. $err_str .= " $1,";
  397. }
  398. }
  399. if ($err_str ne "ERROR:") {
  400. $err_str =~ s/,$//;
  401. $plugin->die($err_str);
  402. }
  403. }
  404. sub get_relevant_peers
  405. {
  406. my $check = shift;
  407. my @peers = @_;
  408. my @rpeers = ();
  409. my $cmp = sub {
  410. my ($a, $b, undef) = @_;
  411. if (ref $b) {
  412. my $r = $a =~ $b;
  413. verbose(3, "Checking peer '$a' against regex '$b' -> "
  414. . ($r ? "true" : "false") . ".");
  415. return $r;
  416. }
  417. else {
  418. my $r = $a eq $b;
  419. verbose(3, "Comparing peer '$a' with string '$b' -> "
  420. . ($r ? "true" : "false") . ".");
  421. return $r;
  422. }
  423. };
  424. my $get_peer_elem;
  425. if ($check->{'ttype'} eq 'description') {
  426. $get_peer_elem = \&get_peer_description;
  427. }
  428. else {
  429. $get_peer_elem = \&get_peer_address;
  430. }
  431. @rpeers = grep { $cmp->($get_peer_elem->($_), $check->{'target'}) } @peers;
  432. return @rpeers;
  433. }
  434. sub get_peer_element
  435. {
  436. my $peer = shift;
  437. my $elem = shift;
  438. my $e;
  439. if (! $peer) {
  440. print STDERR "Cannot retrieve element '$elem' "
  441. . "from undefined value.\n";
  442. return;
  443. }
  444. $e = $peer->getElementsByTagName($elem);
  445. if ((! $e) || (! $e->item(0))) {
  446. print STDERR "Attribute '$elem' not found for peer.\n";
  447. verbose(4, "Peer was: " . Dumper($peer));
  448. return;
  449. }
  450. return $e->item(0)->getFirstChild->getNodeValue;
  451. }
  452. sub get_peer_description
  453. {
  454. my $peer = shift;
  455. return get_peer_element($peer, 'description');
  456. }
  457. sub get_peer_address
  458. {
  459. my $peer = shift;
  460. return get_peer_element($peer, 'peer-address');
  461. }
  462. sub verbose
  463. {
  464. my $level = shift;
  465. my @msgs = @_;
  466. if ($level > $conf{'verbose'}) {
  467. return;
  468. }
  469. foreach my $msg (@msgs) {
  470. print "V$level: $msg\n";
  471. }
  472. }