VBTK/Http.pm untested

filter: Statementstmt 0.0% 0 / 126 Branchbran 0.0% 0 / 26 Conditioncond 0.0% 0 / 12 MC/DCmcdc 0.0% 0 / 8 Subroutinesub 0.0% 0 / 15 Podpod 0.0% 0 / 6 totaltotal 0.0% 0 / 193 CC 14 SCAR 33.3
CC
14
Cov
0%
run
72.0
addVBObj
30.0
new
12.0
CRAP 28.1
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/Http.pm,v $
7 # $Revision: 1.7 $
8 # $Date: 2002/03/04 20:53:06 $
9 # $Author: bhenry $
10 # $Locker: $
11 # $State: Exp $
12 #
13 # Purpose: A common perl library to test web URL's
14 #
15 # Description: This perl library provides the ability to monitor a
16 # series of URL's for content.
17 #
18 # Copyright (C) 1996 - 2002 Brent Henry
19 #
20 # This program is free software; you can redistribute it and/or
21 # modify it under the terms of version 2 of the GNU General Public
22 # License as published by the Free Software Foundation available at:
23 # http://www.gnu.org/copyleft/gpl.html
24 #
25 # This program is distributed in the hope that it will be useful,
26 # but WITHOUT ANY WARRANTY; without even the implied warranty of
27 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28 # GNU General Public License for more details.
29 #
30 #############################################################################
31 #
32 #
33 # REVISION HISTORY:
34 #
35 # $Log: Http.pm,v $
36 # Revision 1.7 2002/03/04 20:53:06 bhenry
37 # *** empty log message ***
38 #
39 # Revision 1.6 2002/03/04 16:49:09 bhenry
40 # Changed requirement back to perl 5.6.0
41 #
42 # Revision 1.5 2002/03/02 00:53:54 bhenry
43 # Documentation updates
44 #
45 # Revision 1.4 2002/02/13 07:38:52 bhenry
46 # Disabled RrdLogRecovery and removed use of @log
47 #
48 # Revision 1.3 2002/01/25 07:15:11 bhenry
49 # Changed to inherit from Parser
50 #
51 #
52  
53 package VBTK::Http;
54  
55 use 5.6.0;
56 use strict;
57 use warnings;
58 # I like using undef as a value so I'm turning off the uninitialized warnings
59 no warnings qw(uninitialized);
60  
61 use VBTK;
62 use VBTK::Common;
63 use VBTK::Parser;
64 use LWP::UserAgent;
65 use HTTP::Cookies;
66  
67 # Inherit methods from Parser class
68 our @ISA = qw(VBTK::Parser);
69  
70 # Setup global package variables.
71 our $VERBOSE=$ENV{VERBOSE};
72 our $DEFAULT_TIMEOUT = 15;
73  
74 #-------------------------------------------------------------------------------
75 # Function: new
76 # Description: Object constructor. Allocates memory for all class members
77 # Input Parms:
78 # Output Parms: Pointer to class
79 #-------------------------------------------------------------------------------
80 sub new
81 {
82 my ($type,$self);
83
84 # If we're passed a hash as the first element, then it's probably from an
85 # inheriting class
86 if((defined $_[0])&&(UNIVERSAL::isa($_[0], 'HASH')))
87 {
88 $self = shift;
89 }
90 # Otherwise, allocate a new hash, bless it and handle any passed parms
91 else
92 {
93 $type = shift;
94 $self = {};
95 bless $self, $type;
96  
97 # Store all passed input name pairs in the object
98 $self->set(@_);
99 }
100  
101 # Setup the header and detail formats for the pmobjects and log
102 my $stdHeader = [ 'Time Resp Time (sec) Errors',
103 '----------------- --------------- ------' ];
104 my $stdDetail = [ '@<<<<<<<<<<<<<<<< @>>>>>>>>>>>>>> @>>>>>',
105 '$time, $data[0], $data[1]' ];
106  
107 # Setup a hash of default parameters
108 my $defaultParms = {
109 Interval => 60,
110 URL => $::REQUIRED,
111 CheckImages => undef,
112 VBServerURI => $::VBURI,
113 VBHeader => $stdHeader,
114 VBDetail => $stdDetail,
115 LogFile => undef,
116 LogHeader => $stdHeader,
117 LogDetail => $stdDetail,
118 RotateLogAt => '12:00am',
119 PreProcessor => undef,
120 Split => undef,
121 Filter => undef,
122 Ignore => undef,
123 Timeout => $DEFAULT_TIMEOUT,
124 ErrorStatus => $::WARNING,
125 DebugHeader => 'URL $self->{URL}',
126 AllowCookies => 1,
127 };
128  
129 # Run the validation, setting defaults if values are not already set
130 $self->validateParms($defaultParms) || &fatal("Exiting");
131  
132 # Create a parser object to handle the response times.
133 $self->{Parser} = new VBTK::Parser(
134 Interval => $self->{Interval},
135 VBServerURI => $self->{VBServerURI},
136 VBHeader => $self->{VBHeader},
137 VBDetail => $self->{VBDetail},
138 LogFile => $self->{LogFile},
139 LogHeader => $self->{LogHeader},
140 LogDetail => $self->{LogDetail},
141 RotateLogAt => $self->{RotateLogAt},
142 RotateLogOnEOF => $self->{RotateLogOnEOF},
143 Split => undef,
144 Filter => undef,
145 Ignore => undef,
146 );
147  
148 # Create a second parser object to handle the comparison to a baseline.
149 # This one will not get all the parms passed in.
150 $self->{BaselineParser} = new VBTK::Parser(
151 Interval => $self->{Interval},
152 VBServerURI => $self->{VBServerURI},
153 VBHeader => undef,
154 VBDetail => [ '$data' ],
155 LogFile => undef,
156 LogHeader => undef,
157 LogDetail => undef,
158 RotateLogAt => undef,
159 RotateLogOnEOF => undef,
160 PreProcessor => $self->{PreProcessor},
161 Split => $self->{Split},
162 Filter => $self->{Filter},
163 Ignore => $self->{Ignore}
164 );
165  
166 # Setup a useragent object
167 my $ua = new LWP::UserAgent;
168 $ua->agent("VBTK::Http" . $ua->agent);
169 $ua->timeout($self->{Timeout});
170 $self->{ua} = $ua;
171  
172 # Setup a request object, but don't submit it yet
173 my $req = new HTTP::Request GET => "$self->{URL}";
174 $self->{req} = $req;
175  
176 $self->{ErrorStatus} = map_status($self->{ErrorStatus});
177 &fatal("Invalid Error Status specified") if ($self->{ErrorStatus} eq '');
178  
179 # Setup a cookie jar
180 $self->{cookieJar} = HTTP::Cookies->new();
181  
182 &VBTK::register($self);
183 ($self);
184 }
185  
186 #-------------------------------------------------------------------------------
187 # Function: addVBObj
188 # Description: Calls the VBTK::Parser add_rules method for the current object.
189 # Input Parms: Parser Name Pairs Hash
190 # Output Parms: None
191 #-------------------------------------------------------------------------------
192 sub addVBObj
193 {
194 my $self = shift;
195 my $Parser = $self->{Parser};
196 my $BaselineParser = $self->{BaselineParser};
197 my $Interval = $self->{Interval};
198 my $URL = $self->{URL};
199 my %args = @_;
200  
201 # Setup some reasonable thresholds
202 my $expireAfterSec = int($Interval * 3);
203 my $description = qq(
204 This object monitors the URL '$URL'. It will set the status to 'Warning'
205 if it is unable to retrieve the URL or if response times become unacceptable.
206 );
207  
208 # Setup default parms
209 my $defaultRules = {
210 VBObjName => $::REQUIRED,
211 TextHistoryLimit => 30,
212 ReverseText => 1,
213 Rules => undef,
214 Requirements => undef,
215 StatusHistoryLimit => 30,
216 StatusChangeActions => undef,
217 StatusUpgradeRules => [
218 "Upgrade to Failed if Warning occurs 2 times in $expireAfterSec sec" ],
219 ExpireAfter => "$expireAfterSec seconds",
220 Description => $description,
221 RrdTimeCol => '$time',
222 RrdColumns => [ '$data[0]' ],
223 RrdFilter => undef,
224 RrdMin => 0,
225 RrdMax => undef,
226 RrdXFF => undef,
227 RrdCF => undef,
228 RrdDST => undef,
229  
230 # These parms will be used with the BaselineParser object
231 BaselineVBObjName => undef,
232 BaselineDiffStatus => 'Warn',
233 BaselineRules => undef,
234 BaselineRequirements => undef
235 };
236  
237 # Run the validation
238 &validateParms(\%args,$defaultRules) || &fatal("Exiting");
239  
240 # Setup the VB object for response time parser.
241 my $vbObj = $Parser->addVBObj(
242 VBObjName => $args{VBObjName},
243 TextHistoryLimit => $args{TextHistoryLimit},
244 ReverseText => $args{ReverseText},
245 Rules => $args{Rules},
246 Requirements => $args{Requirements},
247 StatusHistoryLimit => $args{StatusHistoryLimit},
248 StatusChangeActions => $args{StatusChangeActions},
249 StatusUpgradeRules => $args{StatusUpgradeRules},
250 ExpireAfter => $args{ExpireAfter},
251 Description => $args{Description},
252 BaselineDiffStatus => undef,
253 RrdTimeCol => $args{RrdTimeCol},
254 RrdColumns => $args{RrdColumns},
255 RrdFilter => $args{RrdFilter},
256 RrdMin => $args{RrdMin},
257 RrdMax => $args{RrdMax},
258 RrdXFF => $args{RrdXFF},
259 RrdCF => $args{RrdCF},
260 RrdDST => $args{RrdDST},
261 );
262  
263 return undef if (! defined $vbObj);
264  
265 # Now define what graphs to show on this object's page, but only if
266 # a value was specified for 'RrdColumns'
267 if($args{RrdColumns})
268 {
269 $vbObj->addGraphGroup (
270 GroupNumber => 1,
271 DataSourceList => undef,
272 Labels => 'resp time (sec)',
273 Title => "URL $URL",
274 CF => undef,
275 );
276 }
277  
278 # If a BaselineVBObjName parm was specified, then setup the VB object
279 # for the baseline parser
280 my $baselineVbObj;
281 if (defined $args{BaselineVBObjName})
282 {
283 $baselineVbObj = $BaselineParser->addVBObj(
284 VBObjName => $args{BaselineVBObjName},
285 Rules => $args{BaselineRules},
286 Requirements => $args{BaselineRequirements},
287 StatusHistoryLimit => $args{StatusHistoryLimit},
288 StatusChangeActions => $args{StatusChangeActions},
289 StatusUpgradeRules => $args{StatusUpgradeRules},
290 ExpireAfter => $args{ExpireAfter},
291 Description => $args{Description},
292 BaselineDiffStatus => $args{BaselineDiffStatus}
293 );
294  
295 return undef if (! defined $baselineVbObj);
296 }
297  
298 ($vbObj,$baselineVbObj);
299 }
300  
301 #-------------------------------------------------------------------------------
302 # Function: run
303 # Description: Execute the command associated with the object.
304 # Input Parms: None
305 # Output Parms: Retvals: $::NOT_FINISHED (-1), $::FINISHED (0), $::ERROR (1)
306 #-------------------------------------------------------------------------------
307 sub run
308 {
309 my $self = shift;
310  
311 my $ErrorStatus = $self->{ErrorStatus};
312 my $Interval = $self->{Interval};
313 my $Parser = $self->{Parser};
314 my $BaselineParser = $self->{BaselineParser};
315 my $header = $self->{DebugHeader};
316 my $ua = $self->{ua};
317 my $req = $self->{req};
318 my $URL = $self->{URL};
319 my $lastTime = $self->{lastTime};
320 my $AllowCookies = $self->{AllowCookies};
321 my $cookieJar = $self->{cookieJar};
322  
323 my $now = time;
324 my ($sleepTime);
325  
326 # If it's not time to run yet, then return
327 if(($sleepTime = $self->calcSleepTime()) > 0)
328 {
329 &log("Not time to check '$URL', wait $sleepTime seconds")
330 if ($VERBOSE > 1);
331 return ($sleepTime,$::NOT_FINISHED);
332 }
333  
334 # Make the HTTP request
335 &log("Requesting HTML from '$URL'") if ($VERBOSE > 1);
336  
337 # Add in any cookies if we're allowing cookies
338 $cookieJar->add_cookie_header($req) if ($AllowCookies);
339  
340 my $res = $ua->request($req);
341 my $code = $res->code;
342 my $content = $res->content;
343 my $elapsedTime = time - $now;
344  
345 # Check the reply
346 if($res->is_success)
347 {
348 # Call the response time parser, with the elapsed time
349 $Parser->parseData([[$elapsedTime,0]],$::SUCCESS);
350  
351 # Split the content into separate lines
352 my @lines = split(/\n/,$content);
353 # Add CR back onto the end
354 grep(s/$/\n/,@lines);
355  
356 # Escape out HTML control characters
357 grep(s/</\&lt;/g && s/>/\&gt;/g, @lines);
358  
359 # Call the baseline parser with the actual HTML text
360 $BaselineParser->parseData(\@lines,$::SUCCESS);
361  
362 # Store any returned cookies
363 $cookieJar->extract_cookies($res) if ($AllowCookies);
364  
365 &log($cookieJar->as_string) if ($VERBOSE > 2);
366 }
367 else
368 {
369 my $msg = "Error retrieving URL: '$URL' - Code $code";
370 $Parser->parseData([[0,1]],$ErrorStatus,$msg);
371 $BaselineParser->parseData(undef,$ErrorStatus,$msg);
372 }
373  
374 $sleepTime = $self->calcSleepTime(1);
375  
376 ($sleepTime,$::NOT_FINISHED);
377 }
378  
379 # Simple calls to pass on to the parser
380 sub getLastRows { shift->{Parser}->getLastRows; }
381 sub addGraphGroup { shift->{Parser}->addGraphGroup(@_); }
382  
383 # Put in a stub for handleSignal
384 sub handleSignal { (0); }
385  
386 1;
387 __END__