check_junos_bgp.pl 13 KB

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