check_junos_bgp.pl 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  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($_) // "<unknown address>")
  165. . " => " . (get_peer_description($_) // "<unkown description>") } @peers;
  166. verbose(3, "Peers: " . join(", ", @p));
  167. }
  168. foreach my $check (@{$conf{'checks'}}) {
  169. my $code;
  170. my $value;
  171. my @relevant_peers = get_relevant_peers($check, @peers);
  172. if ($conf{'verbose'} >= 2) {
  173. my @p = map { (get_peer_address($_) // "<unknown address>")
  174. . " => " . (get_peer_description($_) // "<unkown description>") } @relevant_peers;
  175. verbose(2, "Relevant peers: " . join(", ", @p));
  176. }
  177. $plugin->set_thresholds(
  178. warning => $check->{'warning'},
  179. critical => $check->{'critical'},
  180. );
  181. if ($check->{'name'} eq 'peers_count') {
  182. $value = scalar(@relevant_peers);
  183. $code = $plugin->check_threshold($value);
  184. $plugin->add_message($code, "$value peer" . (($value == 1) ? "" : "s"));
  185. $plugin->add_perfdata(
  186. label => 'peers_count',
  187. value => $value,
  188. min => 0,
  189. max => undef,
  190. uom => '',
  191. threshold => $plugin->threshold(),
  192. );
  193. }
  194. elsif ($check->{'name'} eq 'prefix_count') {
  195. foreach my $peer (@relevant_peers) {
  196. my $peer_addr = get_peer_address($peer);
  197. if (! defined($peer_addr)) {
  198. $peer_addr = "<unkown address>";
  199. }
  200. $value = get_peer_element($peer, 'peer-state');
  201. if (! defined($value)) {
  202. $value = "<unknown state>";
  203. }
  204. verbose(2, "Peer $peer_addr: peer-state = $value.");
  205. if ($value eq 'Established') {
  206. $value = $peer->getElementsByTagName('bgp-rib');
  207. $value = get_peer_element($value->[0], 'active-prefix-count');
  208. if (! $value) {
  209. $value = 0;
  210. }
  211. $code = $plugin->check_threshold($value);
  212. $plugin->add_message($code, "peer $peer_addr: $value prefix"
  213. . (($value == 1) ? "" : "es"));
  214. verbose(2, "Peer $peer_addr: active-prefix-count = $value.");
  215. }
  216. else {
  217. $value = "";
  218. $code = CRITICAL;
  219. $plugin->add_message($code,
  220. "peer $peer_addr: no established connection");
  221. }
  222. $plugin->add_perfdata(
  223. label => '\'prefix_count[' . $peer_addr . ']\'',
  224. value => $value,
  225. min => 0,
  226. max => undef,
  227. uom => '',
  228. threshold => $plugin->threshold(),
  229. );
  230. }
  231. }
  232. }
  233. my ($code, $msg) = $plugin->check_messages(join => ', ');
  234. $junos->disconnect();
  235. $plugin->nagios_exit($code, $msg);
  236. sub send_query
  237. {
  238. my $device = shift;
  239. my $query = shift;
  240. my $queryargs = shift;
  241. my $res;
  242. my $err;
  243. verbose(3, "Sending query '$query' to router.");
  244. if (ref $queryargs) {
  245. $res = $device->$query(%$queryargs);
  246. } else {
  247. $res = $device->$query();
  248. }
  249. verbose(5, "Got response: " . Dumper(\$res));
  250. if (! ref $res) {
  251. return "ERROR: Failed to execute query '$query'";
  252. }
  253. $err = $res->getFirstError();
  254. if ($err) {
  255. return "ERROR: " . $err->{message};
  256. }
  257. return $res;
  258. }
  259. sub get_neighbor_information
  260. {
  261. my $device = shift;
  262. my @table;
  263. my $query = "get_bgp_summary_information";
  264. my $res = send_query($device, $query);
  265. my $err;
  266. if (! ref $res) {
  267. return $res;
  268. }
  269. $err = $res->getFirstError();
  270. if ($err) {
  271. return "ERROR: " . $err->{message};
  272. }
  273. return $res;
  274. }
  275. sub add_arg
  276. {
  277. my $plugin = shift;
  278. my $arg = shift;
  279. my $spec = $arg->{'spec'};
  280. my $help = $arg->{'usage'};
  281. if (defined $arg->{'desc'}) {
  282. my @desc;
  283. if (ref($arg->{'desc'})) {
  284. @desc = @{$arg->{'desc'}};
  285. }
  286. else {
  287. @desc = ( $arg->{'desc'} );
  288. }
  289. foreach my $d (@desc) {
  290. $help .= "\n $d";
  291. }
  292. if (defined $arg->{'default'}) {
  293. $help .= " (default: $arg->{'default'})";
  294. }
  295. }
  296. elsif (defined $arg->{'default'}) {
  297. $help .= "\n (default: $arg->{'default'})";
  298. }
  299. $plugin->add_arg(
  300. spec => $spec,
  301. help => $help,
  302. );
  303. }
  304. sub get_conf
  305. {
  306. my $plugin = shift;
  307. my $arg = shift;
  308. my ($name, undef) = split(m/\|/, $arg->{'spec'});
  309. my $value = $plugin->opts->$name || $arg->{'default'};
  310. if ($name eq 'password') {
  311. verbose(3, "conf: password => "
  312. . (($value eq '<prompt>') ? '<prompt>' : '<hidden>'));
  313. }
  314. else {
  315. verbose(3, "conf: $name => $value");
  316. }
  317. return ($name => $value);
  318. }
  319. sub add_single_check
  320. {
  321. my $conf = shift;
  322. my @check = split(m/,/, shift);
  323. my %c = ();
  324. if ($check[0] !~ m/\b(?:$valid_checks)\b/) {
  325. return "ERROR: invalid check '$check[0]'";
  326. }
  327. $c{'name'} = $check[0];
  328. if ((! defined($check[1])) || ($check[1] eq "")) {
  329. $c{'target'} = qr//,
  330. $c{'ttype'} = 'address',
  331. }
  332. elsif ($check[1] =~ m/^(?:$RE{'net'}{'IPv4'}|$IPv6_re)$/) {
  333. $c{'target'} = $check[1];
  334. $c{'ttype'} = 'address';
  335. }
  336. elsif ($check[1] =~ m/^\/(.*)\/$/) {
  337. $c{'target'} = qr/$1/;
  338. $c{'ttype'} = 'description';
  339. }
  340. else {
  341. $c{'target'} = $check[1];
  342. $c{'ttype'} = 'description';
  343. }
  344. $c{'warning'} = $check[2];
  345. $c{'critical'} = $check[3];
  346. # check for valid thresholds
  347. # set_threshold() will die if any threshold is not valid
  348. $plugin->set_thresholds(
  349. warning => $c{'warning'},
  350. critical => $c{'critical'},
  351. ) || $plugin->die("ERROR: Invalid thresholds: "
  352. . "warning => $c{'warning'}, critical => $c{'critical'}");
  353. push @{$conf->{'checks'}}, \%c;
  354. }
  355. sub add_checks
  356. {
  357. my $conf = shift;
  358. my @checks = @_;
  359. my $err_str = "ERROR:";
  360. if (scalar(@checks) == 0) {
  361. $conf->{'checks'}[0] = {
  362. name => 'peers_count',
  363. target => qr//,
  364. ttype => 'address',
  365. warning => undef,
  366. critical => undef,
  367. };
  368. return 1;
  369. }
  370. $conf->{'checks'} = [];
  371. foreach my $check (@checks) {
  372. my $e;
  373. $e = add_single_check($conf, $check);
  374. if ($e =~ m/^ERROR: (.*)$/) {
  375. $err_str .= " $1,";
  376. }
  377. }
  378. if ($err_str ne "ERROR:") {
  379. $err_str =~ s/,$//;
  380. $plugin->die($err_str);
  381. }
  382. }
  383. sub get_relevant_peers
  384. {
  385. my $check = shift;
  386. my @peers = @_;
  387. my @rpeers = ();
  388. my $cmp = sub {
  389. my ($a, $b, undef) = @_;
  390. if (ref $b) {
  391. my $r = $a =~ $b;
  392. verbose(3, "Checking peer '$a' against regex '$b' -> "
  393. . ($r ? "true" : "false") . ".");
  394. return $r;
  395. }
  396. else {
  397. my $r = $a eq $b;
  398. verbose(3, "Comparing peer '$a' with string '$b' -> "
  399. . ($r ? "true" : "false") . ".");
  400. return $r;
  401. }
  402. };
  403. my $get_peer_elem;
  404. if ($check->{'ttype'} eq 'description') {
  405. $get_peer_elem = \&get_peer_description;
  406. }
  407. else {
  408. $get_peer_elem = \&get_peer_address;
  409. }
  410. @rpeers = grep { $cmp->($get_peer_elem->($_), $check->{'target'}) } @peers;
  411. return @rpeers;
  412. }
  413. sub get_peer_element
  414. {
  415. my $peer = shift;
  416. my $elem = shift;
  417. my $e;
  418. if (! $peer) {
  419. print STDERR "Cannot retrieve element '$elem' "
  420. . "from undefined value.\n";
  421. return;
  422. }
  423. $e = $peer->getElementsByTagName($elem);
  424. if ((! $e) || (! $e->item(0))) {
  425. print STDERR "Attribute '$elem' not found for peer.\n";
  426. verbose(4, "Peer was: " . Dumper($peer));
  427. return;
  428. }
  429. return $e->item(0)->getFirstChild->getNodeValue;
  430. }
  431. sub get_peer_description
  432. {
  433. my $peer = shift;
  434. return get_peer_element($peer, 'description');
  435. }
  436. sub get_peer_address
  437. {
  438. my $peer = shift;
  439. return get_peer_element($peer, 'peer-address');
  440. }
  441. sub verbose
  442. {
  443. my $level = shift;
  444. my @msgs = @_;
  445. if ($level > $conf{'verbose'}) {
  446. return;
  447. }
  448. foreach my $msg (@msgs) {
  449. print "V$level: $msg\n";
  450. }
  451. }