summaryrefslogtreecommitdiffstats
path: root/lib/Nagios/Plugin.pm
diff options
context:
space:
mode:
authorSven Nierlein <sven@nierlein.de>2014-01-20 00:54:34 +0100
committerSven Nierlein <sven@nierlein.de>2014-01-20 00:54:34 +0100
commitb418181dfe80dd75169b6e8a619ac1932155dea2 (patch)
treecad9c0ae0eae8e800cfff60555ead06ad33c6856 /lib/Nagios/Plugin.pm
parent1cd8d1c52cbd47121f344c4074aec84653f412ce (diff)
downloadmonitoring-plugin-perl-b418181dfe80dd75169b6e8a619ac1932155dea2.tar.gz
renamed module into Monitoring::Plugin
since the complete monitoring team has been renamed, we also rename this module. Signed-off-by: Sven Nierlein <sven@nierlein.de>
Diffstat (limited to 'lib/Nagios/Plugin.pm')
-rw-r--r--lib/Nagios/Plugin.pm697
1 files changed, 0 insertions, 697 deletions
diff --git a/lib/Nagios/Plugin.pm b/lib/Nagios/Plugin.pm
deleted file mode 100644
index d85d35a..0000000
--- a/lib/Nagios/Plugin.pm
+++ /dev/null
@@ -1,697 +0,0 @@
1
2package Nagios::Plugin;
3
4use Nagios::Plugin::Functions qw(:codes %ERRORS %STATUS_TEXT @STATUS_CODES);
5use Params::Validate qw(:all);
6
7use strict;
8use warnings;
9
10use Carp;
11use base qw(Class::Accessor::Fast);
12
13Nagios::Plugin->mk_accessors(qw(
14 shortname
15 perfdata
16 messages
17 opts
18 threshold
19 ));
20
21use Exporter;
22our @ISA = qw(Exporter);
23our @EXPORT = (@STATUS_CODES);
24our @EXPORT_OK = qw(%ERRORS %STATUS_TEXT);
25
26# CPAN stupidly won't index this module without a literal $VERSION here,
27# so we're forced to duplicate it explicitly
28# Make sure you update $Nagios::Plugin::Functions::VERSION too
29our $VERSION = "0.36";
30
31sub new {
32 my $class = shift;
33# my %args = @_;
34
35 my %args = validate( @_,
36 {
37 shortname => 0,
38 usage => 0,
39 version => 0,
40 url => 0,
41 plugin => 0,
42 blurb => 0,
43 extra => 0,
44 license => 0,
45 timeout => 0
46 },
47 );
48
49 my $shortname = Nagios::Plugin::Functions::get_shortname(\%args);
50 delete $args{shortname} if (exists $args{shortname});
51 my $self = {
52 shortname => $shortname,
53 perfdata => [], # to be added later
54 messages => {
55 warning => [],
56 critical => [],
57 ok => []
58 },
59 opts => undef, # see below
60 threshold => undef, # defined later
61 };
62 bless $self, $class;
63 if (exists $args{usage}) {
64 require Nagios::Plugin::Getopt;
65 $self->opts( new Nagios::Plugin::Getopt(%args) );
66 }
67 return $self;
68}
69
70sub add_perfdata {
71 my ($self, %args) = @_;
72 require Nagios::Plugin::Performance;
73 my $perf = Nagios::Plugin::Performance->new(%args);
74 push @{$self->perfdata}, $perf;
75}
76sub all_perfoutput {
77 my $self = shift;
78 return join(" ", map {$_->perfoutput} (@{$self->perfdata}));
79}
80
81sub set_thresholds {
82 my $self = shift;
83 require Nagios::Plugin::Threshold;
84 return $self->threshold( Nagios::Plugin::Threshold->set_thresholds(@_));
85}
86
87# NP::Functions wrappers
88sub nagios_exit {
89 my $self = shift;
90 Nagios::Plugin::Functions::nagios_exit(@_, { plugin => $self });
91}
92sub nagios_die {
93 my $self = shift;
94 Nagios::Plugin::Functions::nagios_die(@_, { plugin => $self });
95}
96sub die {
97 my $self = shift;
98 Nagios::Plugin::Functions::nagios_die(@_, { plugin => $self });
99}
100sub max_state {
101 Nagios::Plugin::Functions::max_state(@_);
102}
103sub max_state_alt {
104 Nagios::Plugin::Functions::max_state_alt(@_);
105}
106
107# top level interface to Nagios::Plugin::Threshold
108sub check_threshold {
109 my $self = shift;
110
111 my %args;
112
113 if ( $#_ == 0 && (! ref $_[0] || ref $_[0] eq "ARRAY" )) { # one positional param
114 %args = (check => shift);
115 }
116 else {
117 %args = validate ( @_, { # named params
118 check => 1,
119 warning => 0,
120 critical => 0,
121 } );
122 }
123
124 # in order of preference, get warning and critical from
125 # 1. explicit arguments to check_threshold
126 # 2. previously explicitly set threshold object
127 # 3. implicit options from Getopts object
128 if ( exists $args{warning} || exists $args{critical} ) {
129 $self->set_thresholds(
130 warning => $args{warning},
131 critical => $args{critical},
132 );
133 }
134 elsif ( defined $self->threshold ) {
135 # noop
136 }
137 elsif ( defined $self->opts ) {
138 $self->set_thresholds(
139 warning => $self->opts->warning,
140 critical => $self->opts->critical,
141 );
142 }
143 else {
144 return UNKNOWN;
145 }
146
147 return $self->threshold->get_status($args{check});
148}
149
150# top level interface to my Nagios::Plugin::Getopt object
151sub add_arg {
152 my $self = shift;
153 $self->opts->arg(@_) if $self->_check_for_opts;
154}
155sub getopts {
156 my $self = shift;
157 $self->opts->getopts(@_) if $self->_check_for_opts;
158}
159
160sub _check_for_opts {
161 my $self = shift;
162 croak
163 "You have to supply a 'usage' param to Nagios::Plugin::new() if you want to use Getopts from your Nagios::Plugin object."
164 unless ref $self->opts() eq 'Nagios::Plugin::Getopt';
165 return $self;
166}
167
168
169
170# -------------------------------------------------------------------------
171# NP::Functions::check_messages helpers and wrappers
172
173sub add_message {
174 my $self = shift;
175 my ($code, @messages) = @_;
176
177 croak "Invalid error code '$code'"
178 unless defined($ERRORS{uc $code}) || defined($STATUS_TEXT{$code});
179
180 # Store messages using strings rather than numeric codes
181 $code = $STATUS_TEXT{$code} if $STATUS_TEXT{$code};
182 $code = lc $code;
183 croak "Error code '$code' not supported by add_message"
184 if $code eq 'unknown' || $code eq 'dependent';
185
186 $self->messages($code, []) unless $self->messages->{$code};
187 push @{$self->messages->{$code}}, @messages;
188}
189
190sub check_messages {
191 my $self = shift;
192 my %args = @_;
193
194 # Add object messages to any passed in as args
195 for my $code (qw(critical warning ok)) {
196 my $messages = $self->messages->{$code} || [];
197 if ($args{$code}) {
198 unless (ref $args{$code} eq 'ARRAY') {
199 if ($code eq 'ok') {
200 $args{$code} = [ $args{$code} ];
201 } else {
202 croak "Invalid argument '$code'"
203 }
204 }
205 push @{$args{$code}}, @$messages;
206 }
207 else {
208 $args{$code} = $messages;
209 }
210 }
211
212 Nagios::Plugin::Functions::check_messages(%args);
213}
214
215# -------------------------------------------------------------------------
216
2171;
218
219#vim:et:sw=4
220
221__END__
222
223=head1 NAME
224
225Nagios::Plugin - A family of perl modules to streamline writing Nagios
226plugins
227
228=head1 SYNOPSIS
229
230 # Constants OK, WARNING, CRITICAL, and UNKNOWN are exported by default
231 # See also Nagios::Plugin::Functions for a functional interface
232 use Nagios::Plugin;
233
234 # Constructor
235 $np = Nagios::Plugin->new; # OR
236 $np = Nagios::Plugin->new( shortname => "PAGESIZE" ); # OR
237
238
239 # use Nagios::Plugin::Getopt to process the @ARGV command line options:
240 # --verbose, --help, --usage, --timeout and --host are defined automatically.
241 $np = Nagios::Plugin->new(
242 usage => "Usage: %s [ -v|--verbose ] [-H <host>] [-t <timeout>] "
243 . "[ -c|--critical=<threshold> ] [ -w|--warning=<threshold> ]",
244 );
245
246 # add valid command line options and build them into your usage/help documentation.
247 $np->add_arg(
248 spec => 'warning|w=s',
249 help => '-w, --warning=INTEGER:INTEGER . See '
250 . 'http://nagiosplug.sourceforge.net/developer-guidelines.html#THRESHOLDFORMAT '
251 . 'for the threshold format. ',
252 );
253
254 # Parse @ARGV and process standard arguments (e.g. usage, help, version)
255 $np->getopts;
256
257
258 # Exit/return value methods - nagios_exit( CODE, MESSAGE ),
259 # nagios_die( MESSAGE, [CODE])
260 $page = retrieve_page($page1)
261 or $np->nagios_exit( UNKNOWN, "Could not retrieve page" );
262 # Return code: 3;
263 # output: PAGESIZE UNKNOWN - Could not retrieve page
264 test_page($page)
265 or $np->nagios_exit( CRITICAL, "Bad page found" );
266
267 # nagios_die() is just like nagios_exit(), but return code defaults
268 # to UNKNOWN
269 $page = retrieve_page($page2)
270 or $np->nagios_die( "Could not retrieve page" );
271 # Return code: 3;
272 # output: PAGESIZE UNKNOWN - Could not retrieve page
273
274 # Threshold methods
275 $code = $np->check_threshold(
276 check => $value,
277 warning => $warning_threshold,
278 critical => $critical_threshold,
279 );
280 $np->nagios_exit( $code, "Threshold check failed" ) if $code != OK;
281
282
283 # Message methods (EXPERIMENTAL AND SUBJECT TO CHANGE) -
284 # add_message( CODE, $message ); check_messages()
285 for (@collection) {
286 if (m/Error/) {
287 $np->add_message( CRITICAL, $_ );
288 } else {
289 $np->add_message( OK, $_ );
290 }
291 }
292 ($code, $message) = $np->check_messages();
293 nagios_exit( $code, $message );
294 # If any items in collection matched m/Error/, returns CRITICAL and
295 # the joined set of Error messages; otherwise returns OK and the
296 # joined set of ok messages
297
298
299 # Perfdata methods
300 $np->add_perfdata(
301 label => "size",
302 value => $value,
303 uom => "kB",
304 threshold => $threshold,
305 );
306 $np->add_perfdata( label => "time", ... );
307 $np->nagios_exit( OK, "page size at http://... was ${value}kB" );
308 # Return code: 0;
309 # output: PAGESIZE OK - page size at http://... was 36kB \
310 # | size=36kB;10:25;25: time=...
311
312
313=head1 DESCRIPTION
314
315Nagios::Plugin and its associated Nagios::Plugin::* modules are a
316family of perl modules to streamline writing Nagios plugins. The main
317end user modules are Nagios::Plugin, providing an object-oriented
318interface to the entire Nagios::Plugin::* collection, and
319Nagios::Plugin::Functions, providing a simpler functional interface to
320a useful subset of the available functionality.
321
322The purpose of the collection is to make it as simple as possible for
323developers to create plugins that conform the Nagios Plugin guidelines
324(http://nagiosplug.sourceforge.net/developer-guidelines.html).
325
326
327=head2 EXPORTS
328
329Nagios status code constants are exported by default:
330
331 OK
332 WARNING
333 CRITICAL
334 UNKNOWN
335 DEPENDENT
336
337The following variables are also exported on request:
338
339=over 4
340
341=item %ERRORS
342
343A hash mapping error strings ("CRITICAL", "UNKNOWN", etc.) to the
344corresponding status code.
345
346=item %STATUS_TEXT
347
348A hash mapping status code constants (OK, WARNING, CRITICAL, etc.) to the
349corresponding error string ("OK", "WARNING, "CRITICAL", etc.) i.e. the
350reverse of %ERRORS.
351
352=back
353
354
355=head2 CONSTRUCTOR
356
357 Nagios::Plugin->new;
358
359 Nagios::Plugin->new( shortname => 'PAGESIZE' );
360
361 Nagios::Plugin->new(
362 usage => "Usage: %s [ -v|--verbose ] [-H <host>] [-t <timeout>]
363 [ -c|--critical=<critical threshold> ] [ -w|--warning=<warning threshold> ] ",
364 version => $VERSION,
365 blurb => $blurb,
366 extra => $extra,
367 url => $url,
368 license => $license,
369 plugin => basename $0,
370 timeout => 15,
371 );
372
373Instantiates a new Nagios::Plugin object. Accepts the following named
374arguments:
375
376=over 4
377
378=item shortname
379
380The 'shortname' for this plugin, used as the first token in the plugin
381output by the various exit methods. Default: uc basename $0.
382
383=item usage ("Usage: %s --foo --bar")
384
385Passing a value for the usage() argument makes Nagios::Plugin
386instantiate its own C<Nagios::Plugin::Getopt> object so you can start
387doing command line argument processing. See
388L<Nagios::Plugin::Getopt/CONSTRUCTOR> for more about "usage" and the
389following options:
390
391=item version
392
393=item url
394
395=item blurb
396
397=item license
398
399=item extra
400
401=item plugin
402
403=item timeout
404
405=back
406
407=head2 OPTION HANDLING METHODS
408
409C<Nagios::Plugin> provides these methods for accessing the functionality in C<Nagios::Plugin::Getopt>.
410
411=over 4
412
413=item add_arg
414
415Examples:
416
417 # Define --hello argument (named parameters)
418 $plugin->add_arg(
419 spec => 'hello=s',
420 help => "--hello\n Hello string",
421 required => 1,
422 );
423
424 # Define --hello argument (positional parameters)
425 # Parameter order is 'spec', 'help', 'default', 'required?'
426 $plugin->add_arg('hello=s', "--hello\n Hello string", undef, 1);
427
428See L<Nagios::Plugin::Getopt/ARGUMENTS> for more details.
429
430=item getopts()
431
432Parses and processes the command line options you've defined,
433automatically doing the right thing with help/usage/version arguments.
434
435See L<Nagios::Plugin::Getopt/GETOPTS> for more details.
436
437=item opts()
438
439Assuming you've instantiated it by passing 'usage' to new(), opts()
440returns the Nagios::Plugin object's C<Nagios::Plugin::Getopt> object,
441with which you can do lots of great things.
442
443E.g.
444
445 if ( $plugin->opts->verbose ) {
446 print "yah yah YAH YAH YAH!!!";
447 }
448
449 # start counting down to timeout
450 alarm $plugin->opts->timeout;
451 your_long_check_step_that_might_time_out();
452
453 # access any of your custom command line options,
454 # assuming you've done these steps above:
455 # $plugin->add_arg('my_argument=s', '--my_argument [STRING]');
456 # $plugin->getopts;
457 print $plugin->opts->my_argument;
458
459Again, see L<Nagios::Plugin::Getopt>.
460
461=back
462
463=head2 EXIT METHODS
464
465=over 4
466
467=item nagios_exit( <CODE>, $message )
468
469Exit with return code CODE, and a standard nagios message of the
470form "SHORTNAME CODE - $message".
471
472=item nagios_die( $message, [<CODE>] )
473
474Same as nagios_exit(), except that CODE is optional, defaulting
475to UNKNOWN. NOTE: exceptions are not raised by default to calling code.
476Set C<$_use_die> flag if this functionality is required (see test code).
477
478=item die( $message, [<CODE>] )
479
480Alias for nagios_die(). Deprecated.
481
482=item max_state, max_state_alt
483
484These are wrapper function for Nagios::Plugin::Functions::max_state and
485Nagios::Plugin::Functions::max_state_alt.
486
487=back
488
489=head2 THRESHOLD METHODS
490
491These provide a top level interface to the
492C<Nagios::Plugin::Threshold> module; for more details, see
493L<Nagios::Plugin::Threshold> and L<Nagios::Plugin::Range>.
494
495=over 4
496
497=item check_threshold( $value )
498
499=item check_threshold( check => $value, warning => $warn, critical => $crit )
500
501Evaluates $value against the thresholds and returns OK, CRITICAL, or
502WARNING constant. The thresholds may be:
503
5041. explicitly set by passing 'warning' and/or 'critical' parameters to
505 C<check_threshold()>, or,
506
5072. explicitly set by calling C<set_thresholds()> before C<check_threshold()>, or,
508
5093. implicitly set by command-line parameters -w, -c, --critical or
510 --warning, if you have run C<< $plugin->getopts() >>.
511
512You can specify $value as an array of values and each will be checked against
513the thresholds.
514
515The return value is ready to pass to C <nagios_exit>, e . g .,
516
517 $p->nagios_exit(
518 return_code => $p->check_threshold($result),
519 message => " sample result was $result"
520 );
521
522
523=item set_thresholds(warning => "10:25", critical => "~:25")
524
525Sets the acceptable ranges and creates the plugin's
526Nagios::Plugins::Threshold object. See
527http://nagiosplug.sourceforge.net/developer-guidelines.html#THRESHOLDFORMAT
528for details and examples of the threshold format.
529
530=item threshold()
531
532Returns the object's C<Nagios::Plugin::Threshold> object, if it has
533been defined by calling set_thresholds(). You can pass a new
534Threshold object to it to replace the old one too, but you shouldn't
535need to do that from a plugin script.
536
537=back
538
539=head2 MESSAGE METHODS
540
541EXPERIMENTAL AND SUBJECT TO CHANGE
542
543add_messages and check_messages are higher-level convenience methods to add
544and then check a set of messages, returning an appropriate return code
545and/or result message. They are equivalent to maintaining a set of @critical,
546@warning, and and @ok message arrays (add_message), and then doing a final
547if test (check_messages) like this:
548
549 if (@critical) {
550 nagios_exit( CRITICAL, join(' ', @critical) );
551 }
552 elsif (@warning) {
553 nagios_exit( WARNING, join(' ', @warning) );
554 }
555 else {
556 nagios_exit( OK, join(' ', @ok) );
557 }
558
559=over 4
560
561=item add_message( <CODE>, $message )
562
563Add a message with CODE status to the object. May be called multiple times.
564The messages added are checked by check_messages, following.
565
566Only CRITICAL, WARNING, and OK are accepted as valid codes.
567
568
569=item check_messages()
570
571Check the current set of messages and return an appropriate nagios return
572code and/or a result message. In scalar context, returns only a return
573code; in list context returns both a return code and an output message,
574suitable for passing directly to nagios_exit() e.g.
575
576 $code = $np->check_messages;
577 ($code, $message) = $np->check_messages;
578
579check_messages returns CRITICAL if any critical messages are found, WARNING
580if any warning messages are found, and OK otherwise. The message returned
581in list context defaults to the joined set of error messages; this may be
582customised using the arguments below.
583
584check_messages accepts the following named arguments (none are required):
585
586=over 4
587
588=item join => SCALAR
589
590A string used to join the relevant array to generate the message
591string returned in list context i.e. if the 'critical' array @crit
592is non-empty, check_messages would return:
593
594 join( $join, @crit )
595
596as the result message. Default: ' ' (space).
597
598=item join_all => SCALAR
599
600By default, only one set of messages are joined and returned in the
601result message i.e. if the result is CRITICAL, only the 'critical'
602messages are included in the result; if WARNING, only the 'warning'
603messages are included; if OK, the 'ok' messages are included (if
604supplied) i.e. the default is to return an 'errors-only' type
605message.
606
607If join_all is supplied, however, it will be used as a string to
608join the resultant critical, warning, and ok messages together i.e.
609all messages are joined and returned.
610
611=item critical => ARRAYREF
612
613Additional critical messages to supplement any passed in via add_message().
614
615=item warning => ARRAYREF
616
617Additional warning messages to supplement any passed in via add_message().
618
619=item ok => ARRAYREF | SCALAR
620
621Additional ok messages to supplement any passed in via add_message().
622
623=back
624
625=back
626
627
628=head2 PERFORMANCE DATA METHODS
629
630=over 4
631
632=item add_perfdata( label => "size", value => $value, uom => "kB", threshold => $threshold )
633
634Add a set of performance data to the object. May be called multiple times.
635The performance data is included in the standard plugin output messages by
636the various exit methods.
637
638See the Nagios::Plugin::Performance documentation for more information on
639performance data and the various field definitions, as well as the relevant
640section of the Nagios Plugin guidelines
641(http://nagiosplug.sourceforge.net/developer-guidelines.html#AEN202).
642
643=back
644
645
646=head1 EXAMPLES
647
648"Enough talk! Show me some examples!"
649
650See the file 'check_stuff.pl' in the 't' directory included with the
651Nagios::Plugin distribution for a complete working example of a plugin
652script.
653
654
655=head1 VERSIONING
656
657The Nagios::Plugin::* modules are currently experimental and so the
658interfaces may change up until Nagios::Plugin hits version 1.0, although
659every attempt will be made to keep them as backwards compatible as
660possible.
661
662
663=head1 SEE ALSO
664
665See L<Nagios::Plugin::Functions> for a simple functional interface to a subset
666of the available Nagios::Plugin functionality.
667
668See also L<Nagios::Plugin::Getopt>, L<Nagios::Plugin::Range>,
669L<Nagios::Plugin::Performance>, L<Nagios::Plugin::Range>, and
670L<Nagios::Plugin::Threshold>.
671
672The Nagios Plugin project page is at http://nagiosplug.sourceforge.net.
673
674
675=head1 BUGS
676
677Please report bugs in these modules to the Nagios Plugin development team:
678nagiosplug-devel@lists.sourceforge.net.
679
680
681=head1 AUTHOR
682
683Maintained by the Nagios Plugin development team -
684http://nagiosplug.sourceforge.net.
685
686Originally by Ton Voon, E<lt>ton.voon@altinity.comE<gt>.
687
688=head1 COPYRIGHT AND LICENSE
689
690Copyright (C) 2006 by Nagios Plugin Development Team
691
692This library is free software; you can redistribute it and/or modify it
693under the same terms as Perl itself, either Perl version 5.8.4 or, at your
694option, any later version of Perl 5 you may have available.
695
696=cut
697