VBTK/Wrapper.pm untested

filter: Statementstmt 0.0% 0 / 233 Branchbran 0.0% 0 / 94 Conditioncond 0.0% 0 / 57 MC/DCmcdc 0.0% 0 / 36 Subroutinesub 0.0% 0 / 15 Podpod 0.0% 0 / 6 totaltotal 0.0% 0 / 441 CC 48 SCAR 50.0
CC
48
Cov
0%
run
380.0
openCmd
90.0
readRows
56.0
CRAP 148.9
1 #############################################################################
2 #
3 # NOTE: This file under revision control using RCS
4 # Any changes made without RCS will be lost
5 #
6 # $Source: /usr/local/cvsroot/vbtk/VBTK/Wrapper.pm,v $
7 # $Revision: 1.9 $
8 # $Date: 2002/03/04 20:53:07 $
9 # $Author: bhenry $
10 # $Locker: $
11 # $State: Exp $
12 #
13 # Purpose: A common perl library to simplify the encapsulation of the
14 # execution of other programs.
15 #
16 # Description: This perl library provides the ability to encapsulate the
17 # execution of another program, capturing STDOUT and searching
18 # it for text patterns indicating success or failure. It then
19 # can set the status of a vbserver object based on the
20 # results.
21 #
22 # Directions:
23 #
24 # Depends on: VBTK::Common.pm
25 #
26 # Copyright (C) 1996 - 2002 Brent Henry
27 #
28 # This program is free software; you can redistribute it and/or
29 # modify it under the terms of version 2 of the GNU General Public
30 # License as published by the Free Software Foundation available at:
31 # http://www.gnu.org/copyleft/gpl.html
32 #
33 # This program is distributed in the hope that it will be useful,
34 # but WITHOUT ANY WARRANTY; without even the implied warranty of
35 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
36 # GNU General Public License for more details.
37 #
38 #############################################################################
39 #
40 #
41 # REVISION HISTORY:
42 #
43 # $Log: Wrapper.pm,v $
44 # Revision 1.9 2002/03/04 20:53:07 bhenry
45 # *** empty log message ***
46 #
47 # Revision 1.8 2002/03/04 16:49:09 bhenry
48 # Changed requirement back to perl 5.6.0
49 #
50 # Revision 1.7 2002/03/02 00:53:55 bhenry
51 # Documentation updates
52 #
53 # Revision 1.6 2002/02/19 19:12:06 bhenry
54 # Changed to use unix time internally, to avoid DST problems
55 #
56 # Revision 1.5 2002/02/13 07:38:51 bhenry
57 # Disabled RrdLogRecovery and removed use of @log
58 #
59 # Revision 1.4 2002/01/25 07:14:12 bhenry
60 # Changed to make use of calcSleepTime
61 #
62 # Revision 1.3 2002/01/23 20:27:52 bhenry
63 # Changed to inherit from Parser and support inheritance
64 #
65 # Revision 1.2 2002/01/21 17:07:40 bhenry
66 # Disabled 'uninitialized' warnings
67 #
68  
69 package VBTK::Wrapper;
70  
71 use 5.6.0;
72 use strict;
73 use warnings;
74 # I like using undef as a value so I'm turning off the uninitialized warnings
75 no warnings qw(uninitialized);
76  
77 use VBTK;
78 use VBTK::Common;
79 use VBTK::Parser;
80 use VBTK::InputStream;
81 use Storable qw(dclone);
82  
83 # Inherit methods from Parser class
84 our @ISA = qw(VBTK::Parser);
85  
86 # Setup package constants
87 our $FILE_HANDLE_COUNT = 1;
88  
89 # Setup global package variables.
90 our $VERBOSE=$ENV{VERBOSE};
91  
92 #-------------------------------------------------------------------------------
93 # Function: new
94 # Description: Object constructor. Allocates memory for all class members
95 # Input Parms:
96 # Output Parms: Pointer to class
97 #-------------------------------------------------------------------------------
98 sub new
99 {
100 my ($type,$self);
101
102 # If we're passed a hash as the first element, then it's probably from an
103 # inheriting class
104 if((defined $_[0])&&(UNIVERSAL::isa($_[0], 'HASH')))
105 {
106 $self = shift;
107 }
108 # Otherwise, allocate a new hash, bless it and handle any passed parms
109 else
110 {
111 $type = shift;
112 $self = {};
113 bless $self, $type;
114  
115 # Store all passed input name pairs in the object
116 $self->set(@_);
117 }
118  
119 # For backward compatibility
120 $self->{SourceList} = $self->{Execute} . " |"
121 if (($self->{SourceList} eq '')&&($self->{Execute} ne ''));
122  
123 # Setup a hash of default parameters
124 my $defaultParms = {
125 Interval => undef,
126 Execute => undef,
127 SourceList => $::REQUIRED,
128 VBServerURI => $::VBURI,
129 VBHeader => undef,
130 VBDetail => [ '$data' ],
131 LogFile => undef,
132 LogHeader => undef,
133 LogDetail => undef,
134 RotateLogAt => '12:00am',
135 RotateLogOnEOF => undef,
136 PreProcessor => undef,
137 Split => undef,
138 Filter => undef,
139 Ignore => undef,
140 SkipLines => undef,
141 Timeout => undef,
142 TimeoutStatus => $::TIMEOUT,
143 Follow => undef,
144 FollowTimeout => ((2 * $self->{Interval}) + 10),
145 FollowHeartbeat => undef,
146 SetRunStatus => undef,
147 NonZeroExitStatus => $::FAILED,
148 SuppressStdout => 1,
149 SuppressMessages => 1,
150 DebugHeader => undef
151 };
152  
153 # Run the validation, setting defaults if values are not already set
154 $self->validateParms($defaultParms) || &fatal("Exiting");
155  
156 # Make sure the program specified is executable
157 my $lastSource = $self->{SourceList};
158  
159 # If sourcelist is an array, then just look at the last entry
160 $lastSource = pop(@{[@{$self->{SourceList}}]})
161 if (ref($self->{SourceList}) eq 'ARRAY');
162  
163 # Call the super-class Parser to initialize it.
164 $self->SUPER::new;
165  
166 # Setup additional object attributes
167 $self->{out} = []; # Will store all output, used for vbobj message.
168 $self->{cmd_out} = []; # Will store output since the last retrieval
169 $self->{cmd_open} = 0; # Indicates whether the cmd is currently running.
170 $self->{run_count} = 0; # Counts number of times command has been run.
171  
172 # Create a file handle
173 $self->{fhLabel} = "CMD" . $FILE_HANDLE_COUNT++;
174  
175 $self->{TimeoutStatus} = map_status($self->{TimeoutStatus});
176 &fatal("Invalid Timeout Status specified") if ($self->{TimeoutStatus} eq '');
177  
178 $self->{NonZeroExitStatus} = map_status($self->{NonZeroExitStatus});
179 &fatal("Invalid NonZeroExit Status specified") if ($self->{NonZeroExitStatus} eq '');
180  
181 &VBTK::register($self);
182 ($self);
183 }
184  
185 #-------------------------------------------------------------------------------
186 # Function: run
187 # Description: Execute the command associated with the object.
188 # Input Parms: None
189 # Output Parms: Retvals: $::NOT_FINISHED (-1), $::FINISHED (0), $::ERROR (1), or retval
190 # from process executed (0 - 255);
191 #-------------------------------------------------------------------------------
192 sub run
193 {
194 my $self = shift;
195  
196 my $fhLabel = $self->{fhLabel};
197 my $cmd_open = $self->{cmd_open};
198 my $SetRunStatus = $self->{SetRunStatus};
199 my $Timeout = $self->{Timeout};
200 my $FollowTimeout = $self->{FollowTimeout};
201 my $FollowHeartbeat = $self->{FollowHeartbeat};
202 my $TimeoutStatus = $self->{TimeoutStatus};
203 my $Interval = $self->{Interval};
204 my $Follow = $self->{Follow};
205 my $RotateLogOnEOF = $self->{RotateLogOnEOF};
206 my $header = $self->{DebugHeader};
207 my $out = $self->{out};
208 my $pid = $self->{pid};
209  
210 my($retval,$tmp_status,$cmd_out,$msg,$ret_code,$sleepTime);
211  
212 $self->{DebugHeader} = $header = $fhLabel if ($header eq '');
213  
214 # Run the command if not already running.
215 if(! $cmd_open)
216 {
217 ($sleepTime,$retval) = $self->openCmd;
218 return ($sleepTime,$retval) if (($retval != $::NOT_FINISHED)||($sleepTime > 0));
219 }
220  
221 $retval = $self->readRows;
222 $cmd_out = $self->{cmd_out};
223  
224 # Dump rows retrieved into the $out array
225 push(@{$out},@{$cmd_out});
226  
227 if($self->{ShowStdout})
228 {
229 foreach (@{$cmd_out})
230 {
231 print STDOUT "$header: " if($FILE_HANDLE_COUNT > 2);
232 print STDOUT $_;
233 }
234 }
235  
236 $self->{rows_pending} = 1 if (@{$cmd_out} > 0);
237  
238 # Did the command complete yet?
239 if($retval == $::FINISHED)
240 {
241 $self->{cmd_open} = 0;
242  
243 $ret_code = $self->{fh}->getRetVal();
244  
245 $msg = ($ret_code) ? "Command exited with return code '$ret_code'." : undef;
246  
247 # Convert any return codes > 255 or < 0 to 255 (Ksh only supports 0-255).
248 $ret_code = 255 if (($ret_code > 255)||($ret_code < 0));
249  
250 $retval = $self->handleExit($ret_code,undef,$msg);
251  
252 # If the RotateLogOnEOF parm was specified, then rotate the log here.
253 $self->rotate_log if ($RotateLogOnEOF);
254  
255 # If no interval was specified, then just return the exit code.
256 return(0,$retval) if ($Interval eq '');
257 }
258 # Check to see if the command has passed the timeout value
259 elsif(($Timeout > 0) && (($Timeout + $self->{startTime}) < time))
260 {
261 $self->{cmd_open} = 0;
262  
263 $msg = "Timed out waiting for '$header' to complete";
264 $retval = $self->handleExit($ret_code,$TimeoutStatus,$msg);
265 return(0,$retval) if ($Interval eq '');
266 }
267 # If Follow option wasn't specified, and SetRunStatus was specified, then
268 # set status to Running once with no message
269 elsif(($Follow eq '')&&($SetRunStatus)&&($self->{last_status_set}==0))
270 {
271 $self->parseData(undef,$::RUNNING);
272 $self->{last_status_set} = time;
273 }
274 # If Follow option was specified, then if there is new output to be processed
275 # and the status wasn't set in the last $Interval seconds, or the
276 # FollowHeartbeat option was specified and no data has come through in the
277 # last $Interval seconds, then pass the output to the Parser object to be
278 # analyzed and transmitted to the vbserver process.
279 elsif(($Follow)&&
280 ((($self->{rows_pending} > 0)&&
281 (($self->{last_status_set} + $Interval) <= time)) ||
282 (($FollowHeartbeat)&&(($self->{last_data_read} + $Interval) < time))))
283 {
284 # Send updated message to vbserver with status of Running if 'SetRunStatus'
285 # is true. Otherwise, send the message with a status of Success and clear
286 # the output.
287 if ($SetRunStatus eq '')
288 {
289 $self->parseData($out,$::SUCCESS);
290 @{$self->{out}} = ();
291 }
292 else
293 {
294 $self->parseData($out,$::RUNNING);
295 }
296  
297 # Reset the counters
298 $self->{last_status_set} += $Interval;
299 $self->{last_data_read} = time;
300 $self->{rows_pending} = 0;
301 }
302 # Check to see if the command has been inactive longer than the follow
303 # timeout value. If so then close the command and process a timeout
304 # status.
305 elsif(($Follow)&&($FollowTimeout > 0)&&
306 (($FollowTimeout + $self->{last_data_read}) < time))
307 {
308 $self->{cmd_open} = 0;
309  
310 $msg = "Timed out on '$header' waiting for data to arrive";
311 $retval = $self->handleExit($ret_code,$TimeoutStatus,$msg);
312 return(0,$retval) if ($Interval eq '');
313 }
314  
315 (0,$::NOT_FINISHED);
316 }
317  
318  
319 #-------------------------------------------------------------------------------
320 # Function: openCmd
321 # Description: Check to see if it's time to run the command, and if it's already
322 # been run. If everything is ready, then run the command and link
323 # the output to the corresponding file handle.
324 # Input Parms: None
325 # Output Parms: retval ($::FINISHED,$::ERROR,$::NOT_FINISHED)
326 #-------------------------------------------------------------------------------
327 sub openCmd
328 {
329 my $self = shift;
330  
331 my $fhLabel = $self->{fhLabel};
332 my $SourceList = $self->{SourceList};
333 my $Interval = $self->{Interval};
334 my $cmd_open = $self->{cmd_open};
335 my $run_count = $self->{run_count};
336 my $Follow = $self->{Follow};
337 my $header = $self->{DebugHeader};
338 my $out = $self->{out};
339 my $now = time;
340 my ($sleepTime);
341  
342 return (0,$::NOT_FINISHED) if ($cmd_open);
343  
344 $header = $self->{DebugHeader} = $fhLabel if ($header eq '');
345  
346 # If no interval was specified, then only allow the command to be
347 # run once.
348 if($Interval eq '')
349 {
350 return (0,$::FINISHED) if ($run_count > 0);
351 }
352 # If interval was specified, check to see if enough time has elapsed.
353 elsif(($sleepTime = $self->calcSleepTime()) > 0)
354 {
355 &log("Not time to run '$header' yet, wait $sleepTime seconds") if ($VERBOSE > 1);
356 return ($sleepTime,$::NOT_FINISHED);
357 }
358 @{$self->{out}} = ();
359  
360 &log("Starting $header: $SourceList",$out,$self->{SuppressStdout},
361 $self->{SuppressMessages});
362 $self->{run_count}++;
363 $self->{last_status_set} = 0;
364 $self->{last_data_read} = time;
365 $self->{rows_pending} = 0;
366 $self->{startTime} = time;
367  
368 # Increment 'lastTime'
369 $self->calcSleepTime(1);
370  
371 # Try to open the input stream
372 my $fh = new VBTK::InputStream(SourceList => $SourceList,
373 Follow => $Follow);
374 unless($fh)
375 {
376 $self->{fh} = undef;
377
378 # If we failed the first exec, and an interval is specified, then just
379 # unregister the object now, so that we don't try to run it again.
380 if(($self->{run_count} == 1)&&($Interval))
381 {
382 &log("Disabling '$header' test");
383 &VBTK::unRegister($self);
384 }
385
386 return (0,$::ERROR);
387 }
388  
389 $self->{cmd_open} = 1;
390 $self->{fh} = $fh;
391  
392 (0,$::NOT_FINISHED);
393 }
394  
395 #-------------------------------------------------------------------------------
396 # Function: readRows
397 # Description: Read as many rows as are available to the file handle. Timeout
398 # and return after $timeout seconds have passed with no rows arriving
399 # Input Parms: None
400 # Output Parms: Data
401 #-------------------------------------------------------------------------------
402 sub readRows
403 {
404 my $self = shift;
405 my $fh = $self->{fh};
406 my $fhLabel = $self->{fhLabel};
407 my $header = $self->{DebugHeader} || $fhLabel;
408 my ($buf,$line,$rows,$eof,$num_rows,$timeleft,$found_eof,$leaveRows);
409 my $start_time = time;
410  
411 &log("Reading data from '$header'") if ($VERBOSE > 1);
412  
413 # Read rows from the InputStream
414 ($rows,$eof) = $fh->read;
415  
416 $self->{cmd_out} = $rows;
417  
418 if(@{$rows} > 0)
419 {
420 &log(scalar(@{$rows}) . " rows read from '$header'") if ($VERBOSE);
421  
422 # If the SkipLines parm starts with '-' then strip the rows off the front
423 # until there are only abs(SkipLines) rows left.
424 if(($self->{SkipLines} < 0)||($self->{SkipLines} =~ /^-/))
425 {
426 $leaveRows = abs($self->{SkipLines});
427 while(@{$rows} > $leaveRows) { shift(@{$rows}) };
428 $self->{SkipLines} = 0;
429 }
430 elsif($self->{SkipLines} > 0)
431 {
432 # Skip the number of rows specified by the SkipLines parm
433 while(($self->{SkipLines}-- > 0)&&(@{$rows} > 0)) { shift(@{$rows}) };
434 }
435 }
436  
437 if ($eof)
438 {
439 ($::FINISHED);
440 }
441 else
442 {
443 ($::NOT_FINISHED);
444 }
445 }
446  
447 #-------------------------------------------------------------------------------
448 # Function: handleSignal
449 # Description: If the main program catches a signal, it will call this method
450 # for each object. If the object is currently running a process,
451 # that process will be killed and marked as failed.
452 # Input Parms: Message
453 # Output Parms: None
454 #-------------------------------------------------------------------------------
455 sub handleSignal
456 {
457 my $self = shift;
458 my $signal = shift;
459 my $cmd_open = $self->{cmd_open};
460 my $fh = $self->{fh};
461 my $pid = $fh->getPid() if (defined $fh);
462 my $Follow = $self->{Follow};
463 my $SetRunStatus = $self->{SetRunStatus};
464 my $error_msg;
465  
466 if ($cmd_open)
467 {
468 $error_msg = "Program caught signal SIG$signal";
469  
470 # If we're using the running status, then send a status of warning to
471 # the object to indicate that it was killed.
472 if($SetRunStatus)
473 {
474 &obj->handleExit(1,$::WARNING,$error_msg);
475 }
476 # Otherwise, just log an error and kill all sub-processes.
477 else
478 {
479 &error("$error_msg");
480  
481 # Make sure process and child processes are dead if this is an abnormal
482 # termination
483 if ($pid)
484 {
485 &log("Killing child process '$pid'");
486 kill 9, $pid;
487 }
488 }
489 }
490 (0);
491 }
492  
493 #-------------------------------------------------------------------------------
494 # Function: handleExit
495 # Description: Take care of parsing the output for required or error strings,
496 # reviewing the process exit code, setting the status of the vbobject
497 # and logging all important information
498 # Input Parms: None
499 # Output Parms: Data
500 #-------------------------------------------------------------------------------
501 sub handleExit
502 {
503 my $self = shift;
504 my ($ret_code,$status,$error_msg) = @_;
505  
506 my $pid = $self->{fh}->getPid();
507 my $header = $self->{DebugHeader};
508  
509 &error("$error_msg") if ($error_msg ne '');
510  
511 # If status isn't passed in, then set it based on the retcode passed in.
512 if($status eq '')
513 {
514 $status = ($ret_code == 0) ? $::SUCCESS : $self->{NonZeroExitStatus};
515 }
516  
517 # Make sure process and child processes are dead if this is an abnormal
518 # termination
519 if (($pid)&&($status ne $::SUCCESS))
520 {
521 &log("Killing child process '$pid'");
522 kill 9, $pid;
523 }
524  
525 &log("Finished $header",$self->{out},$self->{SuppressStdout},
526 $self->{SuppressMessages});
527  
528 # Check for patterns in the output which might change the status
529 $self->parseData($self->{out},$status,$error_msg);
530  
531 return ($ret_code) if ($ret_code > 0);
532 return (0) if ($status eq $::SUCCESS);
533 return (1);
534 }
535  
536 1;
537 __END__