check_junos_bgp.pl 13 KB

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