blib/lib/JMX/Jmx4Perl/Nagios/CheckJmx4Perl.pm untested

filter: Statementstmt 0.0% 0 / 474 Branchbran 0.0% 0 / 160 Conditioncond 0.0% 0 / 87 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 46 Podpod 0.0% 0 / 33 totaltotal 0.0% 0 / 800 SCAR 88.0
CC
81
Cov
0%
_replace_placeholder
240.0
execute
110.0
_extract_checks
72.0
CRAP 6642.0
1 package JMX::Jmx4Perl::Nagios::CheckJmx4Perl;
2  
3 use strict;
4 use warnings;
5 use JMX::Jmx4Perl::Nagios::SingleCheck;
6 use JMX::Jmx4Perl::Nagios::MessageHandler;
7 use JMX::Jmx4Perl;
8 use JMX::Jmx4Perl::Request;
9 use JMX::Jmx4Perl::Response;
10 use Data::Dumper;
11 use Nagios::Plugin;
12 use Nagios::Plugin::Functions qw(:codes %ERRORS %STATUS_TEXT);
13 use Time::HiRes qw(gettimeofday tv_interval);
14 use Carp;
15 use Text::ParseWords;
16  
17 our $AUTOLOAD;
18  
19 =head1 NAME
20  
21 JMX::Jmx4Perl::Nagios::CheckJmx4Perl - Module for encapsulating the functionality of
22 L<check_jmx4perl>
23  
24 =head1 SYNOPSIS
25  
26 # One line in check_jmx4perl to rule them all
27 JMX::Jmx4Perl::Nagios::CheckJmx4Perl->new()->execute();
28  
29 =head1 DESCRIPTION
30  
31 The purpose of this module is to encapsulate a single run of L<check_jmx4perl>
32 in a perl object. This allows for C<check_jmx4perl> to run within the embedded
33 Nagios perl interpreter (ePN) wihout interfering with other, potential
34 concurrent, runs of this check. Please refer to L<check_jmx4perl> for
35 documentation on how to use this check. This module is probably I<not> of
36 general interest and serves only the purpose described above.
37  
38 Its main task is to set up one ore more L<JMX::Jmx4Perl::Nagios::SingleCheck>
39 objects from command line arguments and optionally from a configuration file.
40  
41 =head1 METHODS
42  
43 =over
44  
45 =item $check = new $JMX::Jmx4Perl::Nagios::CheckJmx4Perl()
46  
47 Set up a object used for a single check. It will parse the command line
48 arguments and any configuation file given.
49  
50 =cut
51  
52 sub new {
53 my $class = shift;
54 my $self = { };
55 bless $self,(ref($class) || $class);
56 $self->{np} = $self->create_nagios_plugin();
57 $self->{cmd_args} = [ @ARGV ];
58  
59 $self->_print_doc_and_exit($self->{np}->opts->{doc}) if defined $self->{np}->opts->{doc};
60 $self->_verify_and_initialize();
61 return $self;
62 }
63  
64 =back
65  
66 =head1 $check->execute()
67  
68 Send the JMX request to the server monitored and print out a nagios output.
69  
70 =cut
71  
72 sub execute {
73 my $self = shift;
74 my $np = $self->{np};
75 eval {
76 # Request
77 my @optional = ();
78  
79 my $error_stat = { };
80 my $target_config = $self->target_config;
81 my $jmx = JMX::Jmx4Perl->new(mode => "agent", url => $self->url, user => $self->user,
82 password => $self->password,
83 product => $self->product,
84 proxy => $self->proxy_config,
85 timeout => $np->opts->{timeout} || 180,
86 target => $target_config,
87 # For Jolokia agents < 1.0
88 'legacy-escape' => $self->legacy_escape);
89 my @requests;
90 for my $check (@{$self->{checks}}) {
91 push @requests,@{$check->get_requests($jmx,\@ARGV)};
92 }
93 my $responses = $self->_send_requests($jmx,@requests);
94 #print Dumper($responses);
95 my @extra_requests = ();
96 my $nr_checks = scalar(@{$self->{checks}});
97 if ($nr_checks == 1) {
98 eval {
99 my @r = $self->{checks}->[0]->extract_responses($responses,\@requests,{ target => $target_config });
100 push @extra_requests,@r if @r;
101 };
102 $self->nagios_die($@) if $@;
103 } else {
104 my $i = 1;
105 for my $check (@{$self->{checks}}) {
106 # A check can consume more than one response
107 my $prefix = $self->_multi_check_prefix($check,$i++,$nr_checks);
108 eval {
109 my @r = $check->extract_responses($responses,\@requests,
110 {
111 target => $target_config,
112 prefix => $prefix,
113 error_stat => $error_stat
114 });
115 push @extra_requests,@r if @r;
116 };
117 if ($@) {
118 my $txt = $@;
119 $txt =~ s/^(.*?)\n.*$/$1/s;
120 my $code = $np->opts->{'unknown-is-critical'} ? CRITICAL : UNKNOWN;
121 $check->update_error_stats($error_stat,$code);
122 $prefix =~ s/\%c/$STATUS_TEXT{$code}/g;
123 my $msg_handler = $np->{msg_handler} || $np;
124 $msg_handler->add_message($code,$prefix . $txt);
125 }
126 }
127 }
128 # Send extra requests, e.g. for switching on the history
129 if (@extra_requests) {
130 $self->_send_requests($jmx,@extra_requests);
131 }
132  
133 # Different outputs for multi checks/single checks
134 $self->do_exit($error_stat);
135 };
136 if ($@) {
137 # p1.pl, the executing script of the embedded nagios perl interpreter
138 # uses this tag to catch an exit code of a plugin. We rethrow this
139 # exception if we detect this pattern.
140 if ($@ !~ /^ExitTrap:/) {
141 $self->nagios_die("Error: $@");
142 } else {
143 die $@;
144 }
145 }
146 }
147  
148 =head1 $check->exit()
149  
150 Write out result and exit. This method can be overridden to provide a custom
151 output, which can be extracted from NagiosPlugin object.
152  
153 =cut
154  
155 sub do_exit {
156 my $self = shift;
157 my $error_stat = shift;
158 my $np = $self->{np};
159  
160 my $msg_handler = $np->{msg_handler} || $np;
161 my ($code,$message) = $msg_handler->check_messages(join => "\n", join_all => "\n");
162 ($code,$message) = $self->_prepare_multicheck_message($np,$code,$message,$error_stat) if scalar(@{$self->{checks}}) > 1;
163
164 $np->nagios_exit($code, $message);
165 }
166  
167 sub _prepare_multicheck_message {
168 my $self = shift;
169 my $np = shift;
170 my $code = shift;
171 my $message = shift;
172 my $error_stat = shift;
173  
174 my $summary;
175 my $labels = $self->{multi_check_labels} || {};
176 my $nr_checks = scalar(@{$self->{checks}});
177 $code = $self->_check_for_UNKNOWN($error_stat,$code);
178 if ($code eq OK) {
179 $summary = $self->_format_multicheck_ok_summary($labels->{summary_ok} ||
180 "All %n checks OK",$nr_checks);
181 } else {
182 $summary = $self->_format_multicheck_failure_summary($labels->{summary_failure} ||
183 "%e of %n checks failed [%d]",
184 $nr_checks,
185 $error_stat);
186 }
187 return ($code,$summary . "\n" . $message);
188 }
189  
190 # UNKNOWN shadows everything else
191 sub _check_for_UNKNOWN {
192 my $self = shift;
193 my $error_stat = shift;
194 my $code = shift;
195 return $error_stat->{UNKNOWN} && scalar(@$error_stat->{UNKNOWN}) ? UNKNOWN : $code;
196 }
197  
198 sub _format_multicheck_ok_summary {
199 my $self = shift;
200 my $format = shift;
201 my $nr_checks = shift;
202 my $ret = $format;
203 $ret =~ s/\%n/$nr_checks/g;
204 return $ret;
205 }
206  
207 sub _format_multicheck_failure_summary {
208 my $self = shift;
209 my $format = shift;
210 my $nr_checks = shift;
211 my $error_stat = shift;
212  
213 my $ret = $format;
214  
215 my $details = "";
216 my $total_errors = 0;
217 for my $code (UNKNOWN,CRITICAL,WARNING) {
218 if (my $errs = $error_stat->{$code}) {
219 $details .= scalar(@$errs) . " " . $STATUS_TEXT{$code} . " (" . join (",",@$errs) . "), ";
220 $total_errors += scalar(@$errs);
221 }
222 }
223 if ($total_errors > 0) {
224 # Cut off extra chars at the end
225 $details = substr($details,0,-2);
226 }
227
228 $ret =~ s/\%d/$details/g;
229 $ret =~ s/\%e/$total_errors/g;
230 $ret =~ s/\%n/$nr_checks/g;
231 return $ret;
232 }
233  
234 # Create a formatted prefix for multicheck output
235 sub _multi_check_prefix {
236 my $self = shift;
237 my $check = shift;
238 my $idx = shift;
239 my $max = shift;
240
241 my $c = $check->{config};
242  
243 my $l = length($max);
244
245 return sprintf("[%$l.${l}s] %%c ",$idx)
246 if (defined($c->{multicheckprefix}) && !length($c->{multicheckprefix}));
247
248 my $label = $c->{multicheckprefix} || $c->{name} || $c->{key} || "";
249 return sprintf("[%$l.${l}s] %%c %s: ",$idx,$label);
250 }
251  
252  
253 # Send the requests via the build up agent
254 sub _send_requests {
255 my ($self,$jmx,@requests) = @_;
256 my $o = $self->{opts};
257  
258 my $start_time;
259 if ($o->verbose) {
260 # TODO: Print summary of request (GET vs POST)
261 if ($self->user) {
262 print "Remote User: ",$o->user,"\n";
263 }
264 $start_time = [gettimeofday];
265 }
266 # Detangle request for direct method calls and JMX requests to call:
267 my $req_map = $self->_detangle_requests(\@requests);
268 my @responses = ();
269
270 $self->_execute_scripts(\@responses,$req_map);
271 $self->_execute_requests(\@responses,$req_map,$jmx);
272  
273 if ($o->verbose) {
274 print "Result fetched in ",tv_interval($start_time) * 1000," ms:\n";
275 print Dumper(\@responses);
276 }
277 return \@responses;
278 }
279  
280 # Split up request for code-requests (i.e. scripts given in the configuration)
281 # and 'real' requests. Remember the index, too so that the response can be
282 # weave together
283 sub _detangle_requests {
284 my $self = shift;
285 my $requests = shift;
286 my $req_map = {};
287 my $idx = 0;
288 for my $r (@$requests) {
289 push @{$req_map->{ref($r) eq "CODE" ? "code" : "request"}},[$r,$idx];
290 $idx++;
291 }
292 return $req_map;
293 }
294  
295 # Execute subrefs created out of scripts. Put it in the right place of the
296 # result array according to the remembered index
297 sub _execute_scripts {
298 my $self = shift;
299 my $responses = shift;
300 my $req_map = shift;
301 for my $e (@{$req_map->{"code"}}) {
302 # Will die on error which will bubble up
303 $responses->[$e->[1]] = &{$e->[0]}();;
304 }
305 }
306  
307 # Execute requests and put it in the received responses in the right place for
308 # the returned array. The index has been extracted beforehand and stored in the
309 # given req_map
310 sub _execute_requests {
311 my $self = shift;
312 my $responses = shift;
313 my $req_map = shift;
314 my $jmx = shift;
315  
316 # Call remote JMX and weave in
317 my $reqs2send = $req_map->{"request"};
318 if ($reqs2send) {
319 my @resp_received = $jmx->request(map { $_->[0] } @$reqs2send);
320 for my $r (@$reqs2send) {
321 $responses->[$r->[1]] = shift @resp_received;
322 }
323 }
324 }
325  
326  
327 # Print online manual and exit (somewhat crude, I know)
328 sub _print_doc_and_exit {
329 my $self = shift;
330 my $section = shift;
331 if (!eval "require Pod::Usage; Pod::Usage->import(qw(pod2usage)); 1;") {
332 print "Please install Pod::Usage for creating the online help\n";
333 exit 1;
334 }
335 if ($section) {
336 my %sects = (
337 tutorial => "TUTORIAL",
338 reference => "REFERENCE",
339 options => "COMMAND LINE",
340 config => "CONFIGURATION",
341 );
342 my $real_section = $sects{lc $section};
343 if ($real_section) {
344 pod2usage(-verbose => 99, -sections => $real_section );
345 } else {
346 print "Unknown documentation section '$section' (known: ",join (",",sort keys %sects),")\n";
347 exit 1;
348 }
349 } else {
350 pod2usage(-verbose => 99);
351 }
352 }
353  
354  
355 # Initialize this object and validate the mandatory parameters (obtained from
356 # the command line or a configuration file). It will also build up
357 # one or more SingleCheck which are later on sent as a bulk request to
358 # the server.
359 sub _verify_and_initialize {
360 my $self = shift;
361 my $np = $self->{np};
362 my $o = $np->opts;
363
364 $self->{opts} = $self->{np}->opts;
365  
366 # Fetch configuration
367 my $config = $self->_get_config($o->config);
368 # Now, if a specific check is given, extract it, too.
369 my $check_configs;
370 #print Dumper($config);
371 $check_configs = $self->_extract_checks($config,$o->check);
372 #print Dumper($check_configs);
373 if ($check_configs) {
374 for my $c (@$check_configs) {
375 my $s_c = new JMX::Jmx4Perl::Nagios::SingleCheck($np,$c);
376 push @{$self->{checks}},$s_c;
377 }
378 } else {
379 $self->{checks} = [ new JMX::Jmx4Perl::Nagios::SingleCheck($np) ];
380 }
381 # If a server name is given, we use that for the connection parameters
382 if ($o->server) {
383 $self->{server_config} = $config->get_server_config($o->server)
384 || $self->nagios_die("No server configuration for " . $o->server . " found");
385 }
386  
387 # Sanity checks
388 $self->nagios_die("No Server URL given") unless $self->url;
389  
390 for my $check (@{$self->{checks}}) {
391 my $name = $check->name ? " [Check: " . $check->name . "]" : "";
392 $self->nagios_die("An MBean name and a attribute/operation must be provided " . $name)
393 if ((!$check->mbean || (!$check->attribute && !$check->operation)) && !$check->alias && !$check->value && !$check->script);
394 }
395 }
396  
397 # Extract one or more check configurations which can be
398 # simple <Check>s or <MultiCheck>s
399 sub _extract_checks {
400 my $self = shift;
401 my $config = shift;
402 my $check = shift;
403
404 my $np = $self->{np};
405 if ($check) {
406 $self->nagios_die("No configuration given") unless $config;
407 $self->nagios_die("No checks defined in configuration") unless $config->{check};
408  
409 my $check_configs;
410 unless ($config->{check}->{$check}) {
411 $check_configs = $self->_resolve_multicheck($config,$check,$self->{cmd_args});
412 $self->_retrieve_mc_summary_label($config,$check);
413 } else {
414 my $check_config = $config->{check}->{$check};
415 $check_configs = ref($check_config) eq "ARRAY" ? $check_config : [ $check_config ];
416 $check_configs->[0]->{key} = $check;
417 }
418 $self->nagios_die("No check configuration with name " . $check . " found") unless (@{$check_configs});
419  
420 #print Dumper($check_configs);
421  
422 # Resolve parent values
423 for my $c (@{$check_configs}) {
424 #print "[A] ",Dumper($c);
425 $self->_resolve_check_config($c,$config,$self->{cmd_args});
426
427 #print "[B] ",Dumper($c);
428 # Finally, resolve any left over place holders
429 for my $k (keys(%$c)) {
430 $c->{$k} = $self->_replace_placeholder($c->{$k},undef) unless ref($c->{$k});
431 }
432 #print "[C] ",Dumper($c);
433 }
434 return $check_configs;
435 } else {
436 return undef;
437 }
438 }
439  
440 # Resolve a multicheck configuration (<MultiCheck>)
441 sub _resolve_multicheck {
442 my $self = shift;
443 my $config = shift;
444 my $check = shift;
445 my $args = shift;
446 my $np = $self->{np};
447 my $multi_checks = $config->{multicheck};
448 my $check_config = [];
449 if ($multi_checks) {
450 my $m_check = $multi_checks->{$check};
451 if ($m_check) {
452 # Resolve all checks
453 my $c_names = [];
454 for my $type( qw(check multicheck)) {
455 if ($m_check->{$type}) {
456 push @$c_names, ref($m_check->{$type}) eq "ARRAY" ? @{$m_check->{$type}} : $m_check->{$type};
457 }
458 }
459 for my $name (@$c_names) {
460 my ($c_name,$c_args) = $self->_parse_check_ref($name);
461 my $args_merged = $self->_merge_multicheck_args($c_args,$args);
462 $self->nagios_die("Unknown check '" . $c_name . "' for multi check " . $check)
463 unless defined($config->{check}->{$c_name}) or defined($multi_checks->{$c_name});
464 if ($config->{check}->{$c_name}) {
465 # We need a copy of the check hash to avoid mangling it up
466 # if it is referenced multiple times
467 my $check = { %{$config->{check}->{$c_name}} };
468 $check->{key} = $c_name;
469 $check->{args} = $args_merged;
470 push @{$check_config},$check;
471 } else {
472 # It's a multi check referenced via <Check> or <MultiCheck> ....
473 push @{$check_config},@{$self->_resolve_multicheck($config,$c_name,$args_merged)};
474 }
475 }
476 }
477 }
478 return $check_config;
479 }
480  
481 sub _retrieve_mc_summary_label {
482 my $self = shift;
483 my $config = shift;
484 my $check = shift;
485  
486 my $multi_checks = $config->{multicheck};
487 if ($multi_checks) {
488 my $m_check = $multi_checks->{$check};
489 if ($m_check && ($m_check->{summaryok} || $m_check->{summaryfailure})) {
490 my $mc_labels =
491 $self->{multi_check_labels} = {
492 summary_ok => $m_check->{summaryok},
493 summary_failure => $m_check->{summaryfailure}
494 };
495 }
496 }
497 }
498  
499 sub _merge_multicheck_args {
500 my $self = shift;
501 my $check_params = shift;
502 my $args = shift;
503 if (!$args || !$check_params) {
504 return $check_params;
505 }
506 my $ret = [ @$check_params ]; # Copy it over
507 for my $i (0 .. $#$check_params) {
508 if ($check_params->[$i] =~ /^\$(\d+)$/) {
509 my $j = $1;
510 if ($j <= $#$args) {
511 $ret->[$i] = $args->[$j];
512 next;
513 }
514 # Nothing to replace
515 $ret->[$i] = $check_params->[$i];
516 }
517 }
518 return $ret;
519 }
520  
521 # Resolve a singe <Check> configuration
522 sub _resolve_check_config {
523 my $self = shift;
524 my $check = shift;
525 my $config = shift;
526 # Args can come from the outside, but also as part of a multicheck (stored
527 # in $self->{args})
528 my $args = $check->{args} && @{$check->{args}} ? $check->{args} : shift;
529 my $np = $self->{np};
530 if ($check->{use}) {
531 # Resolve parents
532 my $parents = ref($check->{use}) eq "ARRAY" ? $check->{use} : [ $check->{use} ];
533 my $parent_merged = {};
534 for my $p (@$parents) {
535 my ($p_name,$p_args) = $self->_parse_check_ref($p);
536 $self->nagios_die("Unknown parent check '" . $p_name . "' for check '" .
537 ($check->{key} ? $check->{key} : $check->{name}) . "'")
538 unless $config->{check}->{$p_name};
539 # Clone it to avoid side effects when replacing checks inline
540 my $p_check = { %{$config->{check}->{$p_name}} };
541 $p_check->{key} = $p_name;
542 # print "::::: ",Dumper($p_check,$p_args);
543  
544 $self->_resolve_check_config($p_check,$config,$p_args);
545  
546 #$self->_replace_args($p_check,$config,$p_args);
547 $parent_merged->{$_} = $p_check->{$_} for keys %$p_check;
548 }
549 # Replace inherited values
550 for my $k (keys %$parent_merged) {
551 my $parent_val = defined($parent_merged->{$k}) ? $parent_merged->{$k} : "";
552 if (defined($check->{$k})) {
553 $check->{$k} =~ s/\$BASE/$parent_val/g;
554 } else {
555 $check->{$k} = $parent_val;
556 }
557 }
558 }
559 $self->_replace_args($check,$config,$args);
560 #print Dumper($check);
561 return $check;
562 }
563  
564 # Replace argument placeholders with a given list of arguments
565 sub _replace_args {
566 my $self = shift;
567 my $check = shift;
568 my $config = shift;
569 my $args = shift;
570 for my $k (keys(%$check)) {
571 next if $k =~ /^(key|args)$/; # Internal keys
572 $check->{$k} =
573 $self->_replace_placeholder($check->{$k},$args)
574 if ($args && @$args && !ref($check->{$k}));
575 }
576 }
577  
578 sub _replace_placeholder {
579 my $self = shift;
580 my $val = shift;
581 my $args = shift;
582 my $index = defined($args) ? join "|",0 ... $#$args : "\\d+";
583  
584 my $regexp_s = <<'EOP';
585 ^(.*?) # Start containing no args
586  
587 \$( # Variable starts with '$'
588 ($index) | # $0 without default value
589 \{\s*($index)\s* # ${0:12300} with default value
590 (?: :([^\}]+) )*\} # ?: --> clustering group, optional (${0} is also ok)
591 )
592  
593 (.*|$) # The rest which will get parsed next
594 EOP
595 $regexp_s =~ s/\$index/$index/g;
596 my $regexp = qr/$regexp_s/sx;
597 die "Cannot create placeholder regexp" if $@;
598 my $rest = $val;
599 my $ret = "";
600 while (defined($rest) && length($rest) && $rest =~ $regexp) {
601 # $1: start with no placeholder
602 # $2: literal variable as it is defined
603 # $3: variable name (0,1,2,3,...)
604 # $4: same as $3, but either $3 or $4 is defined
605 # $5: default value (if any)
606 # $6: rest which is processed next in the loop
607 my $start = defined($1) ? $1 : "";
608 my $orig_val = '$' . $2;
609 my $i = defined($3) ? $3 : $4;
610 my $default = $5;
611 my $end = defined($6) ? $6 : "";
612 $default =~ s/^\s*(.*)+?\s*$/$1/ if $default; # Trim whitespace
613 #print Dumper({start => $start, orig => $orig_val,end => $end, default=> $default, rest => $rest, i => $i});
614 if (defined($args)) {
615 my $repl = $args->[$i];
616 if (defined($repl)) {
617 if ($repl =~ /^\$(\d+)$/) {
618 my $new_index = $1;
619 #print "============== $val $new_index\n";
620 # Val is a placeholder itself
621 if (defined($default)) {
622 $ret .= $start . '${' . $new_index . ':' . $default . '}';
623 } else {
624 $ret .= $start . '$' . $new_index;
625 }
626 } else {
627 $ret .= $start . $repl;
628 }
629 } else {
630 $ret .= $start . $orig_val;
631 }
632 } else {
633 # We have to replace any left over placeholder either with its
634 # default value or with an empty value
635 if (defined($default)) {
636 $ret .= $start . $default;
637 } elsif (length($start) || length($end)) {
638 $ret .= $start;
639 } else {
640 if (!length($ret)) {
641 # No default value, nothing else for this value. We
642 # consider it undefined
643 return undef;
644 }
645 }
646 }
647 $rest = $end;
648 #print "... $ret$rest\n";
649 }
650 return $ret . (defined($rest) ? $rest : "");
651 }
652  
653 # Split up a 'Use' parent config reference, including possibly arguments
654 sub _parse_check_ref {
655 my $self = shift;
656 my $check_ref = shift;
657 if ($check_ref =~/^\s*(.+?)\((.*)\)\s*$/) {
658 my $name = $1;
659 my $args_s = $2;
660 my $args = [ parse_line('\s*,\s*',0,$args_s) ];
661 return ($name,$args);
662 } else {
663 return $check_ref;
664 }
665 }
666  
667 # Get the configuration as a hash
668 sub _get_config {
669 my $self = shift;
670 my $path = shift;
671 my $np = $self->{np};
672 $self->nagios_die("No configuration file " . $path . " found")
673 if ($path && ! -e $path);
674 return new JMX::Jmx4Perl::Config($path);
675 }
676  
677 # The global server config part
678 sub _server_config {
679 return shift->{server_config};
680 }
681  
682 # Create the nagios plugin used for preparing the nagios output
683 sub create_nagios_plugin {
684 my $self = shift;
685 my $np = Nagios::Plugin->
686 new(
687 usage =>
688 "Usage: %s -u <agent-url> -m <mbean> -a <attribute> -c <threshold critical> -w <threshold warning>\n" .
689 " [--alias <alias>] [--value <shortcut>] [--base <alias/number/mbean>] [--delta <time-base>]\n" .
690 " [--name <perf-data label>] [--label <output-label>] [--product <product>]\n".
691 " [--user <user>] [--password <password>] [--proxy <proxy>]\n" .
692 " [--target <target-url>] [--target-user <user>] [--target-password <password>]\n" .
693 " [--legacy-escape]\n" .
694 " [--config <config-file>] [--check <check-name>] [--server <server-alias>] [-v] [--help]\n" .
695 " arg1 arg2 ....",
696 version => $JMX::Jmx4Perl::VERSION,
697 url => "http://www.jmx4perl.org",
698 plugin => "check_jmx4perl",
699 blurb => "This plugin checks for JMX attribute values on a remote Java application server",
700 extra => "\n\nYou need to deploy jolokia.war on the target application server or an intermediate proxy.\n" .
701 "Please refer to the documentation for JMX::Jmx4Perl for further details.\n\n" .
702 "For a complete documentation please consult the man page of check_jmx4perl or use the option --doc"
703 );
704 $np->shortname(undef);
705 $self->add_common_np_args($np);
706 $self->add_nagios_np_args($np);
707 $np->{msg_handler} = new JMX::Jmx4Perl::Nagios::MessageHandler();
708 $np->getopts();
709 return $np;
710 }
711  
712 sub add_common_np_args {
713 my $self = shift;
714 my $np = shift;
715  
716 $np->add_arg(
717 spec => "url|u=s",
718 help => "URL to agent web application (e.g. http://server:8080/jolokia/)",
719 );
720 $np->add_arg(
721 spec => "product=s",
722 help => "Name of app server product. (e.g. \"jboss\")",
723 );
724 $np->add_arg(
725 spec => "alias=s",
726 help => "Alias name for attribte (e.g. \"MEMORY_HEAP_USED\")",
727 );
728 $np->add_arg(
729 spec => "mbean|m=s",
730 help => "MBean name (e.g. \"java.lang:type=Memory\")",
731 );
732 $np->add_arg(
733 spec => "attribute|a=s",
734 help => "Attribute name (e.g. \"HeapMemoryUsage\")",
735 );
736 $np->add_arg(
737 spec => "operation|o=s",
738 help => "Operation to execute",
739 );
740 $np->add_arg(
741 spec => "value=s",
742 help => "Shortcut for specifying mbean/attribute/path. Slashes within names must be escaped with \\",
743 );
744 $np->add_arg(
745 spec => "delta|d:s",
746 help => "Switches on incremental mode. Optional argument are seconds used for normalizing.",
747 );
748 $np->add_arg(
749 spec => "path|p=s",
750 help => "Inner path for extracting a single value from a complex attribute or return value (e.g. \"used\")",
751 );
752 $np->add_arg(
753 spec => "target=s",
754 help => "JSR-160 Service URL specifing the target server"
755 );
756 $np->add_arg(
757 spec => "target-user=s",
758 help => "Username to use for JSR-160 connection (if --target is set)"
759 );
760 $np->add_arg(
761 spec => "target-password=s",
762 help => "Password to use for JSR-160 connection (if --target is set)"
763 );
764 $np->add_arg(
765 spec => "proxy=s",
766 help => "Proxy to use"
767 );
768 $np->add_arg(
769 spec => "user=s",
770 help => "User for HTTP authentication"
771 );
772 $np->add_arg(
773 spec => "password=s",
774 help => "Password for HTTP authentication"
775 );
776 $np->add_arg(
777 spec => "name|n=s",
778 help => "Name to use for output. Optional, by default a standard value based on the MBean ".
779 "and attribute will be used"
780 );
781 $np->add_arg(
782 spec => "legacy-escape!",
783 help => "Use legacy escape mechanism for Jolokia agents < 1.0"
784 );
785 $np->add_arg(
786 spec => "config=s",
787 help => "Path to configuration file. Default: ~/.j4p"
788 );
789 $np->add_arg(
790 spec => "server=s",
791 help => "Symbolic name of server url to use, which needs to be configured in the configuration file"
792 );
793 $np->add_arg(
794 spec => "check=s",
795 help => "Name of a check configuration as defined in the configuration file"
796 );
797 $np->add_arg(
798 spec => "method=s",
799 help => "HTTP method to use. Either \"get\" or \"post\""
800 );
801 $np->add_arg(
802 spec => "doc:s",
803 help => "Print the documentation of check_jmx4perl, optionally specifying the section (tutorial, args, config)"
804 );
805 }
806  
807 sub add_nagios_np_args {
808 my $self = shift;
809 my $np = shift;
810  
811 $np->add_arg(
812 spec => "base|base-alias|b=s",
813 help => "Base name, which when given, interprets critical and warning values as relative in the range 0 .. 100%. Must be given in the form mbean/attribute/path",
814 );
815 $np->add_arg(
816 spec => "base-mbean=s",
817 help => "Base MBean name, interprets critical and warning values as relative in the range 0 .. 100%. Requires a base-attribute, too",
818 );
819 $np->add_arg(
820 spec => "base-attribute=s",
821 help => "Base attribute for a relative check. Used together with base-mbean",
822 );
823 $np->add_arg(
824 spec => "base-path=s",
825 help => "Base path for relatie checks, where this path is used on the base attribute's value",
826 );
827 $np->add_arg(
828 spec => "unit=s",
829 help => "Unit of measurement of the data retreived. Recognized values are [B|KB|MN|GB|TB] for memory values and [us|ms|s|m|h|d] for time values"
830 );
831 $np->add_arg(
832 spec => "null=s",
833 help => "Value which should be used in case of a null return value of an operation or attribute. Is \"null\" by default"
834 );
835 $np->add_arg(
836 spec => "string",
837 help => "Force string comparison for critical and warning checks"
838 );
839 $np->add_arg(
840 spec => "numeric",
841 help => "Force numeric comparison for critical and warning checks"
842 );
843 $np->add_arg(
844 spec => "critical|c=s",
845 help => "Critical Threshold for value. " .
846 "See http://nagiosplug.sourceforge.net/developer-guidelines.html#THRESHOLDFORMAT " .
847 "for the threshold format.",
848 );
849 $np->add_arg(
850 spec => "warning|w=s",
851 help => "Warning Threshold for value.",
852 );
853 $np->add_arg(
854 spec => "label|l=s",
855 help => "Label to be used for printing out the result of the check. Placeholders can be used."
856 );
857 $np->add_arg(
858 spec => "perfdata=s",
859 help => "Whether performance data should be omitted, which are included by default."
860 );
861 $np->add_arg(
862 spec => "unknown-is-critical",
863 help => "Map UNKNOWN errors to errors with a CRITICAL status"
864 );
865 }
866  
867 # Access to configuration informations
868 # Known config options (key: cmd line arguments, values: keys in config);
869 my $SERVER_CONFIG_KEYS = {
870 "url" => "url",
871 "user" => "user",
872 "password" => "password",
873 "product" => "product",
874 "legacy_escape" => "legacyconfig"
875 };
876  
877 # Get target configuration or undef if no jmx-proxy mode
878 # is used
879 sub target_config {
880 return shift->_target_or_proxy_config("target","target-user","target-password");
881 }
882  
883 # Get proxy configuration or undef if no proxy configuration
884 # is used
885 sub proxy_config {
886 return shift->_target_or_proxy_config("proxy","proxy-user","proxy-password");
887 }
888  
889 sub _target_or_proxy_config {
890 my $self = shift;
891
892 my $main_key = shift;
893 my $user_opt = shift;
894 my $password_opt = shift;
895  
896 my $np = $self->{np};
897 my $opts = $np->opts;
898 my $server_config = $self->_server_config;
899 if ($opts->{$main_key}) {
900 # Use configuration from the command line:
901 return {
902 url => $opts->{$main_key},
903 user => $opts->{$user_opt},
904 password => $opts->{$password_opt}
905 }
906 } elsif ($server_config && $server_config->{$main_key}) {
907 # Use configuration directly from the server definition:
908 return $server_config->{$main_key}
909 } else {
910 return undef;
911 }
912 }
913  
914 # Autoloading is used to fetch the proper connection parameters
915 sub AUTOLOAD {
916 my $self = shift;
917 my $np = $self->{np};
918 my $name = $AUTOLOAD;
919 $name =~ s/.*://; # strip fully-qualified portion
920 my $opts_name = $name;
921 $opts_name =~ s/_/-/;
922  
923 if ($SERVER_CONFIG_KEYS->{$name}) {
924 return $np->opts->{$opts_name} if $np->opts->{$opts_name};
925 my $c = $SERVER_CONFIG_KEYS->{$name};
926 if ($c) {
927 my @parts = split "/",$c;
928 my $h = $self->_server_config ||
929 return undef;
930 while (@parts) {
931 my $p = shift @parts;
932 return undef unless $h->{$p};
933 $h = $h->{$p};
934 return $h unless @parts;
935 }
936 } else {
937 return undef;
938 }
939 } else {
940 $self->nagios_die("No config attribute \"" . $name . "\" known");
941 }
942 }
943  
944 sub nagios_die {
945 my $self = shift;
946 my @args = @_;
947  
948 my $np = $self->{np};
949 $np->nagios_die(join("",@args),$np->opts->{'unknown-is-critical'} ? CRITICAL : UNKNOWN)
950 }
951  
952 # Declared here to avoid AUTOLOAD confusions
953 sub DESTROY {
954  
955 }
956  
957 =head1 LICENSE
958  
959 This file is part of jmx4perl.
960  
961 Jmx4perl is free software: you can redistribute it and/or modify
962 it under the terms of the GNU General Public License as published by
963 the Free Software Foundation, either version 2 of the License, or
964 (at your option) any later version.
965  
966 jmx4perl is distributed in the hope that it will be useful,
967 but WITHOUT ANY WARRANTY; without even the implied warranty of
968 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
969 GNU General Public License for more details.
970  
971 You should have received a copy of the GNU General Public License
972 along with jmx4perl. If not, see <http://www.gnu.org/licenses/>.
973  
974 =head1 AUTHOR
975  
976 roland@cpan.org
977  
978 =cut
979  
980 1;