check_junos_bgp.pl 13 KB

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