Debian Codegraph @

check_email_delivery/src/check_email_delivery_epn

raw ◀ ▶
2 Debian patches touch this file
1 #!/usr/bin/perl
2 use strict;
3 my $VERSION = '0.7.1';
4 my $COPYRIGHT = 'Copyright (C) 2005-2011 Jonathan Buhacoff <[email protected]>';
5 my $LICENSE = 'http://www.gnu.org/licenses/gpl.txt';
6 my %status = ( 'OK' => 0, 'WARNING' => 1, 'CRITICAL' => 2, 'UNKNOWN' => 3 );
7
8 # look for required modules
9 exit $status{UNKNOWN} unless load_modules(qw/Getopt::Long/);
10
11 BEGIN {
12 if( grep { /^--hires$/ } @ARGV ) {
13 eval "use Time::HiRes qw(time);";
14 warn "Time::HiRes not installed\n" if $@;
15 }
16 }
17
18 # get options from command line
19 Getopt::Long::Configure("bundling");
20 my $verbose = 0;
21 my $help = "";
22 my $help_usage = "";
23 my $show_version = "";
24 my $host = "";
25 my $smtp_server = "";
26 my $smtp_port = "";
27 my $imap_server = "";
28 my $smtp_username = "";
29 my $smtp_password = "";
30 my $smtp_tls = "";
31 my $imap_port = "";
32 my $imap_username = "";
33 my $imap_password = "";
34 my $imap_mailbox = "";
35 my $username = "";
36 my $password = "";
37 my $ssl = "";
38 my $imap_ssl = "";
•39 my $mailto = "";
40 my $mailfrom = "";
41 my @header = ();
42 my $body = "";
43 my $warnstr = "";
44 my $critstr = "";
45 my $waitstr = "";
46 my $delay_warn = 95;
47 my $delay_crit = 300;
48 my $smtp_warn = 15;
49 my $smtp_crit = 30;
50 my $imap_warn = 15;
51 my $imap_crit = 30;
52 my $timeout = "";
53 my @alert_plugins = ();
54 my $imap_interval = 5;
55 my $imap_retries = 5;
56 my @plugins = ();
57 my @token_formats = ();
58 my $tokenfile = "";
59 my $default_crit = 30;
60 my $default_warn = 15;
61 my $default_wait = 5;
62 my $default_timeout = 60;
63 my $time_hires = "";
64 my $libexec = "/usr/local/nagios/libexec";
•65 my $ok;
66 $ok = Getopt::Long::GetOptions(
67 "V|version"=>\$show_version,
68 "v|verbose+"=>\$verbose,"h|help"=>\$help,"usage"=>\$help_usage,
69 "w|warning=s"=>\$warnstr,"c|critical=s"=>\$critstr, "t|timeout=s"=>\$timeout,
70 "libexec=s"=>\$libexec,
71 # plugin settings
72 "p|plugin=s"=>\@plugins, "T|token=s"=>\@token_formats,
73 "A|alert=i"=>\@alert_plugins,
74 "F|file=s"=>\$tokenfile,
75 # common settings
76 "H|hostname=s"=>\$host,
77 "U|username=s"=>\$username,"P|password=s"=>\$password,
78 "ssl!"=>\$ssl,
79 # smtp settings
80 "smtp-server=s"=>\$smtp_server,"smtp-port=i"=>\$smtp_port,
81 "mailto=s"=>\$mailto, "mailfrom=s",\$mailfrom,
82 "header=s"=>\@header, "body=s"=>\$body,
83 # smtp-tls settings
84 "smtptls!"=>\$smtp_tls,
85 "smtp-username=s"=>\$smtp_username,"smtp-password=s"=>\$smtp_password,
86 # delay settings
87 "wait=s"=>\$waitstr,
88 # imap settings
89 "imap-server=s"=>\$imap_server,"imap-port=i"=>\$imap_port,
90 "imap-username=s"=>\$imap_username,"imap-password=s"=>\$imap_password,
91 "imap-mailbox=s"=>\$imap_mailbox,
92 "imap-check-interval=i"=>\$imap_interval,"imap-retries=i"=>\$imap_retries,
93 "imapssl!"=>\$imap_ssl,
94 # Time
•95 "hires"=>\$time_hires,
96 );
97
98 if( $show_version ) {
99 print "$VERSION\n";
100 if( $verbose ) {
101 print "Warning threshold: $delay_warn seconds\n";
102 print "Critical threshold: $delay_crit seconds\n";
103 print "Default wait: $default_wait seconds\n";
104 print "Default timeout: $default_timeout seconds\n";
105 }
106 exit $status{UNKNOWN};
107 }
108
109 if( $help ) {
110 exec "perldoc", $0 or print "Try `perldoc $0`\n";
111 exit $status{UNKNOWN};
112 }
113
114 if( $host ) {
115 $smtp_server = $host if $smtp_server eq "";
116 $imap_server = $host if $imap_server eq "";
117 }
118
119 if( $username ) {
120 $smtp_username = $username if $smtp_username eq "";
121 $imap_username = $username if $imap_username eq "";
122 }
123
124 if( $password ) {
125 $smtp_password = $password if $smtp_password eq "";
126 $imap_password = $password if $imap_password eq "";
127 }
128
129 if( $ssl ) {
130 $imap_ssl = $ssl if $imap_ssl eq "";
131 $smtp_tls = $ssl if $smtp_tls eq "";
132 }
•133
134 if( $help_usage
135 ||
136 (
137 scalar(@plugins) == 0
138 &&
139 (
140 $smtp_server eq "" || $mailto eq "" || $mailfrom eq ""
141 || $imap_server eq "" || $username eq "" || $password eq ""
142 )
143 )
144 ) {
145 print "Usage 1: $0 -H host \n\t".
146 "--mailto recipient\@your.net --mailfrom sender\@your.net --body 'message' \n\t".
147 "--username username --password password \n\t".
148 "[-w <seconds>] [-c <seconds>]\n\t" .
149 "[--imap-check-interval <seconds> ] [--imap-retries <times> ]\n";
150 print "Usage 2: $0 \n\t".
151 "-p 'first plugin command with %TOKEN1% embedded' \n\t".
152 "-p 'second plugin command with %TOKEN1% embedded' \n\t".
153 "[-w <seconds1>,<seconds2>] [-c <seconds1>,<seconds2>] \n";
154 exit $status{UNKNOWN};
155 }
156
157 # determine thresholds
158 my @warning_times = split(",", $warnstr);
159 my @critical_times = split(",", $critstr);
160 my @alarm_times = split(",", $timeout);
161 my @wait_times = split(",", $waitstr);
162 my ($dw,$sw,$rw) = split(",", $warnstr);
163 my ($dc,$sc,$rc) = split(",", $critstr);
164 my ($wait) = split(",", $waitstr);
165 $delay_warn = $dw if defined $dw and $dw ne "";
166 $smtp_warn = $sw if defined $sw and $sw ne "";
167 $imap_warn = $rw if defined $rw and $rw ne "";
168 $delay_crit = $dc if defined $dc and $dc ne "";
169 $smtp_crit = $sc if defined $sc and $sc ne "";
170 $imap_crit = $rc if defined $rc and $rc ne "";
171 my $smtp_thresholds = "";
172 $smtp_thresholds .= "-w $smtp_warn " if defined $smtp_warn and $smtp_warn ne "";
173 $smtp_thresholds .= "-c $smtp_crit " if defined $smtp_crit and $smtp_crit ne "";
174 my $imap_thresholds = "";
175 $imap_thresholds .= "-w $imap_warn " if defined $imap_warn and $imap_warn ne "";
176 $imap_thresholds .= "-c $imap_crit " if defined $imap_crit and $imap_crit ne "";
177 $imap_thresholds .= "--imap-check-interval $imap_interval " if defined $imap_interval and $imap_interval ne "";
178 $imap_thresholds .= "--imap-retries $imap_retries " if defined $imap_retries and $imap_retries ne "";
179 if( scalar(@alarm_times) == 1 ) {
180 $default_timeout = shift(@alarm_times);
181 }
182
183 # determine which other options to include
184 my $smtp_options = "";
185 $smtp_options .= "-H $smtp_server " if defined $smtp_server and $smtp_server ne "";
186 $smtp_options .= "-p $smtp_port " if defined $smtp_port and $smtp_port ne "";
187 $smtp_options .= "--tls " if defined $smtp_tls and $smtp_tls;
188 $smtp_options .= "-U ".shellquote($smtp_username)." " if defined $smtp_username and $smtp_username ne "";
189 $smtp_options .= "-P ".shellquote($smtp_password)." " if defined $smtp_password and $smtp_password ne "";
190 $smtp_options .= "--mailto ".shellquote($mailto)." " if defined $mailto and $mailto ne "";
191 $smtp_options .= "--mailfrom ".shellquote($mailfrom)." " if defined $mailfrom and $mailfrom ne "";
192 foreach my $h( @header ) {
193 $smtp_options .= "--header ".shellquote($h)." ";
194 }
195 my $imap_options = "";
196 $imap_options .= "-H $imap_server " if defined $imap_server and $imap_server ne "";
197 $imap_options .= "-p $imap_port " if defined $imap_port and $imap_port ne "";
198 $imap_options .= "-U ".shellquote($imap_username)." " if defined $imap_username and $imap_username ne "";
199 $imap_options .= "-P ".shellquote($imap_password)." " if defined $imap_password and $imap_password ne "";
200 $imap_options .= "--mailbox ".shellquote($imap_mailbox)." " if defined $imap_mailbox and $imap_mailbox ne "";
201 $imap_options .= "--ssl " if defined $imap_ssl and $imap_ssl;
202
203
204 # create the report object
•205 my $report = new PluginReport;
206 my @report_plugins = (); # populated later with either (smtp,imap) or (plugin1,plugin2,...)
207 my $time_start; # initialized later with time the work actually starts
208
209 # create token formats for use with the plugins
210 my @alpha = qw/a b c d e f g h i j k l m n o p q r s t u v w x y z/;
211 my @numeric = qw/0 1 2 3 4 5 6 7 8 9/;
212 my @hex = qw/0 1 2 3 4 5 6 7 8 9 a b c d e f/;
213 my @pgp_even = qw/aardvark absurd accrue acme adrift adult afflict ahead aimless Algol allow alone ammo ancient apple artist assume Athens atlas Aztec baboon backfield backward banjo beaming bedlamp beehive beeswax befriend Belfast berserk billiard bison blackjack blockade blowtorch bluebird bombast bookshelf brackish breadline breakup brickyard briefcase Burbank button buzzard cement chairlift chatter checkup chisel choking chopper Christmas clamshell classic classroom cleanup clockwork cobra commence concert cowbell crackdown cranky crowfoot crucial crumpled crusade cubic dashboard deadbolt deckhand dogsled dragnet drainage dreadful drifter dropper drumbeat drunken Dupont dwelling eating edict egghead eightball endorse endow enlist erase escape exceed eyeglass eyetooth facial fallout flagpole flatfoot flytrap fracture framework freedom frighten gazelle Geiger glitter glucose goggles goldfish gremlin guidance hamlet highchair hockey indoors indulge inverse involve island jawbone keyboard kickoff kiwi klaxon locale lockup merit minnow miser Mohawk mural music necklace Neptune newborn nightbird Oakland obtuse offload optic orca payday peachy pheasant physique playhouse Pluto preclude prefer preshrunk printer prowler pupil puppy python quadrant quiver quota ragtime ratchet rebirth reform regain reindeer rematch repay retouch revenge reward rhythm ribcage ringbolt robust rocker ruffled sailboat sawdust scallion scenic scorecard Scotland seabird select sentence shadow shamrock showgirl skullcap skydive slingshot slowdown snapline snapshot snowcap snowslide solo southward soybean spaniel spearhead spellbind spheroid spigot spindle spyglass stagehand stagnate stairway standard stapler steamship sterling stockman stopwatch stormy sugar surmount suspense sweatband swelter tactics talon tapeworm tempest tiger tissue tonic topmost tracker transit trauma treadmill Trojan trouble tumor tunnel tycoon uncut unearth unwind uproot upset upshot vapor village virus Vulcan waffle wallet watchword wayside willow woodlark Zulu/;
214 my @pgp_odd = qw/adroitness adviser aftermath aggregate alkali almighty amulet amusement antenna applicant Apollo armistice article asteroid Atlantic atmosphere autopsy Babylon backwater barbecue belowground bifocals bodyguard bookseller borderline bottomless Bradbury bravado Brazilian breakaway Burlington businessman butterfat Camelot candidate cannonball Capricorn caravan caretaker celebrate cellulose certify chambermaid Cherokee Chicago clergyman coherence combustion commando company component concurrent confidence conformist congregate consensus consulting corporate corrosion councilman crossover crucifix cumbersome customer Dakota decadence December decimal designing detector detergent determine dictator dinosaur direction disable disbelief disruptive distortion document embezzle enchanting enrollment enterprise equation equipment escapade Eskimo everyday examine existence exodus fascinate filament finicky forever fortitude frequency gadgetry Galveston getaway glossary gossamer graduate gravity guitarist hamburger Hamilton handiwork hazardous headwaters hemisphere hesitate hideaway holiness hurricane hydraulic impartial impetus inception indigo inertia infancy inferno informant insincere insurgent integrate intention inventive Istanbul Jamaica Jupiter leprosy letterhead liberty maritime matchmaker maverick Medusa megaton microscope microwave midsummer millionaire miracle misnomer molasses molecule Montana monument mosquito narrative nebula newsletter Norwegian October Ohio onlooker opulent Orlando outfielder Pacific pandemic Pandora paperweight paragon paragraph paramount passenger pedigree Pegasus penetrate perceptive performance pharmacy phonetic photograph pioneer pocketful politeness positive potato processor provincial proximate puberty publisher pyramid quantity racketeer rebellion recipe recover repellent replica reproduce resistor responsive retraction retrieval retrospect revenue revival revolver sandalwood sardonic Saturday savagery scavenger sensation sociable souvenir specialist speculate stethoscope stupendous supportive surrender suspicious sympathy tambourine telephone therapist tobacco tolerance tomorrow torpedo tradition travesty trombonist truncated typewriter ultimate undaunted underfoot unicorn unify universe unravel upcoming vacancy vagabond vertigo Virginia visitor vocalist voyager warranty Waterloo whimsical Wichita Wilmington Wyoming yesteryear Yucatan/;
215 my %formats = (
216 'a' => sub { pick_random(@alpha) },
217 'n' => sub { pick_random(@numeric) },
218 'c' => sub { pick_random(@alpha,@numeric) },
219 'h' => sub { pick_random(@hex) },
220 'U' => sub { time },
221 'X' => sub { pick_random(@pgp_even) },
222 'Y' => sub { pick_random(@pgp_odd) },
223 );
224 if( scalar(@plugins) ) {
225 # scan the plugin commands for use of tokens to count how many we need
226 my $token_count = 0;
227 foreach my $p (@plugins) {
228 my @matches = sort ($p =~ m/%TOKEN(\d+)%/g);
229 my $max = pop @matches;
230 $token_count = $max if defined($max) && $max > $token_count;
231 }
232 # create the tokens
233 my @tokens = ();
234 foreach my $t (1..$token_count) {
235 my $format = shift @token_formats;
236 $format = "U-X-Y" unless $format;
237 my @format_characters = split(//, $format);
238 my $token = "";
239 foreach my $c (@format_characters) {
240 if( defined $formats{$c} ) {
241 $token .= &{$formats{$c}};
242 }
243 else {
244 $token .= $c;
245 }
246 }
247 push @tokens, $token;
248 }
249 # substitute the tokens into each plugin command
250 foreach my $p (@plugins) {
251 foreach my $t (1..$token_count) {
252 my $token = $tokens[$t-1];
253 $p =~ s/%TOKEN$t%/$token/g;
254 }
255 }
256 # mark plugins that are allowed to generate alerts. default behavior is to alert for all plugins.
257 my %alert_plugins = ();
258 if( scalar(@alert_plugins) > 0 ) {
259 %alert_plugins = map { $_ => 1 } @alert_plugins;
260 }
261 else {
262 %alert_plugins = map { $_ => 1 } (1..scalar(@plugins));
263 }
264 # run each plugin and store its output in a report
265 $time_start = time;
266 my $i = 0;
267 foreach my $p( @plugins ) {
268 $i++;
269 my $plugin_timeout = shift(@alarm_times) || $default_timeout;
270 # run the plugin
271 eval {
272 local $SIG{ALRM} = sub { die "exceeded timeout $plugin_timeout seconds\n" }; # NB: \n required, see `perldoc -f alarm`
273 alarm $plugin_timeout;
274 my $output = `$p`;
275 chomp $output;
276 if( $output !~ m/OK|WARNING|CRITICAL/ ) {
277 print "EMAIL DELIVERY UNKNOWN - plugin $i error: $output\n";
278 print "Plugin $i: $p\n" if $verbose;
279 # record tokens in a file if option is enabled
280 record_tokens($tokenfile,\@tokens,$time_start,undef,'UNKNOWN',$i,$output) if $tokenfile;
281 exit $status{UNKNOWN};
282 }
283 if( $output =~ m/CRITICAL/ && $alert_plugins{$i} ) {
284 print "EMAIL DELIVERY CRITICAL - plugin $i failed: $output\n";
285 print "Plugin $i: $p" if $verbose;
286 # record tokens in a file if option is enabled
287 record_tokens($tokenfile,\@tokens,$time_start,undef,'CRITICAL',$i,$output) if $tokenfile;
288 exit $status{CRITICAL};
289 }
290 if( $output =~ m/WARNING/ && $alert_plugins{$i} ) {
291 print "EMAIL DELIVERY WARNING - plugin $i warning: $output\n";
292 print "Plugin $i: $p\n" if $verbose;
293 # record tokens in a file if option is enabled
294 record_tokens($tokenfile,\@tokens,$time_start,undef,'WARNING',$i,$output) if $tokenfile;
295 exit $status{WARNING};
296 }
297 $report->{"plugin".$i} = $output;
298 alarm 0;
299 };
300 if( $@ && $alert_plugins{$i} ) {
301 print "EMAIL DELIVERY CRITICAL - Could not run plugin $i: $@\n";
302 print "Plugin $i: $p\n" if $verbose;
303 exit $status{CRITICAL};
304 }
305 # if this wasn't the last plugin, wait before continuing
306 if( $i < scalar(@plugins) ) {
307 my $wait = shift(@wait_times) || $default_wait;
308 sleep $wait;
309 }
310 # compatibility with the "not using plugins" method... pretend to calculate the total round trip time (the delay) using data from the plugins ...
311 $report->{max} = 0;
312 $report->{delay} = 0;
313 }
314 # register the list of reports
315 foreach my $r ( 1..scalar(@plugins)) {
316 push @report_plugins, "plugin".$r;
317 }
318 # record tokens in a file if option is enabled
319 my $tmp_long_report = join(", ", map { "$_: $report->{$_}" } @report_plugins ) if $tokenfile;
320 record_tokens($tokenfile,\@tokens,$time_start,time,'OK',scalar(@plugins),$tmp_long_report) if $tokenfile;
321 }
322 else {
323 # not using plugins.
324 $time_start = time;
325
326 # send email via SMTP
327 my $id = $time_start; # XXX should include localhost name maybe or some random number in case the same mailbox is used for multiple delivery tests
328
329 my $smtp_plugin = "$libexec/check_smtp_send";
330 $smtp_plugin = "$libexec/check_smtp_send.pl" unless -e $smtp_plugin;
331 my $smtp_timeout = shift(@alarm_times) || $default_timeout;
332 eval {
333 local $SIG{ALRM} = sub { die "exceeded timeout $smtp_timeout seconds\n" }; # NB: \n required, see `perldoc -f alarm`
334 alarm $smtp_timeout;
335 my $smtp = `$smtp_plugin $smtp_options --header 'Subject: Nagios Message SMTP $smtp_server ID $id.' --body 'Nagios Email Delivery Plugin\n$body' $smtp_thresholds`;
336 if( $smtp !~ m/OK|WARNING|CRITICAL/ ) {
337 print "EMAIL DELIVERY UNKNOWN - smtp unknown: $smtp\n";
338 exit $status{UNKNOWN};
339 }
340 if( $smtp =~ m/CRITICAL/ ) {
341 print "EMAIL DELIVERY CRITICAL - smtp failed: $smtp\n";
342 exit $status{CRITICAL};
343 }
344 chomp $smtp;
345 $report->{smtp} = $smtp;
346 alarm 0;
347 };
348 if( $@ ) {
349 print "EMAIL DELIVERY CRITICAL - Could not connect to SMTP server $smtp_server: $@\n";
350 exit $status{CRITICAL};
351 }
352
353 # wait before checking the delivery
354 $wait = shift(@wait_times) || $default_wait;
355 sleep $wait;
356
357 # check email via IMAP
358 my $imap_plugin = "$libexec/check_imap_receive";
359 $imap_plugin = "$libexec/check_imap_receive.pl" unless -e $imap_plugin;
360 my $imap_timeout = shift(@alarm_times) || $default_timeout;
361 eval {
362 local $SIG{ALRM} = sub { die "exceeded timeout $imap_timeout seconds\n" }; # NB: \n required, see `perldoc -f alarm`
363 alarm $imap_timeout;
364 my $imap = `$imap_plugin $imap_options -s SUBJECT -s 'Nagios Message SMTP $smtp_server ID' --capture-max 'Nagios Message SMTP $smtp_server ID (\\d+)' --nodelete-captured $imap_thresholds`;
365 if( $imap !~ m/OK|WARNING|CRITICAL/ ) {
366 print "EMAIL DELIVERY UNKNOWN - imap unknown: $imap\n";
367 exit $status{UNKNOWN};
368 }
369 if( $imap =~ m/CRITICAL/ ) {
370 print "EMAIL DELIVERY CRITICAL - imap failed: $imap\n";
371 exit $status{CRITICAL};
372 }
373 if( $imap =~ m/ (\d+) max/ ) {
374 my $last_received = $1;
375 $report->{max} = $1;
376 my $delay = time - $last_received;
377 $report->{delay} = $delay;
378 }
379 chomp $imap;
380 $report->{imap} = $imap;
381 alarm 0;
382 };
383 if( $@ ) {
384 print "EMAIL DELIVERY CRITICAL - Could not connect to IMAP server $imap_server: $@\n";
385 exit $status{CRITICAL};
386 }
387 # register the list of reports
388 push @report_plugins, ("smtp","imap");
389 }
390
391
392 # calculate elapsed time and issue warnings
393 my $time_end = time;
394 my $elapsedtime = $time_end - $time_start;
395 $report->{seconds} = $elapsedtime;
396
397 my @warning = ();
398 my @critical = ();
399
400 push @warning, "most recent received $report->{delay} seconds ago" if( defined($report->{delay}) && $report->{delay} > $delay_warn );
401 push @critical, "most recent received $report->{delay} seconds ago" if( defined($report->{delay}) && $report->{delay} > $delay_crit );
402 push @warning, "no emails found" if( !defined($report->{delay}) );
403
404 # print report and exit with known status
405 my $perf_data = "delay=".$report->{delay}."s;$delay_warn;$delay_crit;0 elapsed=".$report->{seconds}."s"; # TODO: need a component for safely generating valid perf data format. for notes on the format, see http://www.perfparse.de/tiki-view_faq.php?faqId=6
406 my $short_report = $report->text(qw/seconds delay/) . " | $perf_data";
407 my $long_report = join("", map { "$_: $report->{$_}\n" } @report_plugins );
408 if( scalar @critical ) {
409 my $alerts = join(", ", @critical);
410 print "EMAIL DELIVERY CRITICAL - $alerts; $short_report\n";
411 print $long_report if $verbose;
412 exit $status{CRITICAL};
413 }
414 if( scalar @warning ) {
415 my $alerts = join(", ", @warning);
416 print "EMAIL DELIVERY WARNING - $alerts; $short_report\n";
417 print $long_report if $verbose;
418 exit $status{WARNING};
419 }
420 print "EMAIL DELIVERY OK - $short_report\n";
421 print $long_report if $verbose;
422 exit $status{OK};
423
424 # utility to load required modules. exits if unable to load one or more of the modules.
425 sub load_modules {
426 my @missing_modules = ();
427 foreach( @_ ) {
428 eval "require $_";
429 push @missing_modules, $_ if $@;
430 }
431 if( @missing_modules ) {
432 print "Missing perl modules: @missing_modules\n";
433 return 0;
434 }
435 return 1;
436 }
437
438 # returns one random character from a set of characters
439 sub pick_random {
440 my @set = @_;
441 my $size = scalar @set;
442 my $string = $set[int(rand($size))];
443 return $string;
444 }
445
446 # appens tokens and times to a tab-separated value file
447 sub record_tokens {
448 my ($tokenfile,$tokens,$time_start,$time_end,$status,$plugin_num,$output) = @_;
449 if( $tokenfile ) {
450 my @tokens = @$tokens;
451 $time_end = "" unless defined $time_end;
452 $status = "" unless defined $status;
453 $plugin_num = "" unless defined $plugin_num;
454 $output = "" unless defined $output;
455 print "saving ".scalar(@tokens)." tokens into $tokenfile\n" if $verbose;
456 open(TOKENFILE,">>$tokenfile");
457 foreach(@tokens) {
458 print TOKENFILE "$_\t$time_start\t$time_end\t$status\t$plugin_num\t$output\n";
459 }
460 close(TOKENFILE);
461 }
462 }
463
464 # wraps argument in single-quotes and escapes any single-quotes in the argument
465 sub shellquote {
466 my $str = shift || "";
467 $str =~ s/\'/\'\\\'\'/g;
468 return "'$str'";
469 }
470
471
472 # NAME
473 # PluginReport
474 # SYNOPSIS
475 # $report = new PluginReport;
476 # $report->{label1} = "value1";
477 # $report->{label2} = "value2";
478 # print $report->text(qw/label1 label2/);
479 package PluginReport;
480
481 sub new {
482 my ($proto,%p) = @_;
483 my $class = ref($proto) || $proto;
484 my $self = bless {}, $class;
485 $self->{$_} = $p{$_} foreach keys %p;
486 return $self;
487 }
488
489 sub text {
490 my ($self,@labels) = @_;
491 my @report = map { "$self->{$_} $_" } grep { defined $self->{$_} } @labels;
492 my $text = join(", ", @report);
493 return $text;
494 }
495
496 package main;
497 1;
498