VBTK/DBI.pm untested

filter: Statementstmt 0.0% 0 / 119 Branchbran 0.0% 0 / 34 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 / 194 CC 18 SCAR 33.1
CC
18
Cov
0%
run
72.0
lookupPassword
30.0
connect
20.0
CRAP 27.3
1 #! /bin/perl
2 #############################################################################
3 #
4 # NOTE: This file under revision control using RCS
5 # Any changes made without RCS will be lost
6 #
7 # $Source: /usr/local/cvsroot/vbtk/VBTK/DBI.pm,v $
8 # $Revision: 1.8 $
9 # $Date: 2002/03/04 20:53:06 $
10 # $Author: bhenry $
11 # $Locker: $
12 # $State: Exp $
13 #
14 # Purpose: A common perl library used to execute select statements
15 # against a database and monitor the results
16 #
17 # Description: This library allows for the definition of select
18 # statements which are run against a database at
19 # specified intervals. The results sets are parsed and
20 # evaluated using a specified set of rules and the
21 # status of corresponding VBServer objects are set
22 # accordingly.
23 #
24 # Depends on: VBTK::Common.pm, VBTK::Parser.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: DBI.pm,v $
44 # Revision 1.8 2002/03/04 20:53:06 bhenry
45 # *** empty log message ***
46 #
47 # Revision 1.7 2002/03/04 16:49:09 bhenry
48 # Changed requirement back to perl 5.6.0
49 #
50 # Revision 1.6 2002/03/02 00:53:54 bhenry
51 # Documentation updates
52 #
53 # Revision 1.5 2002/02/13 07:38:52 bhenry
54 # Disabled RrdLogRecovery and removed use of @log
55 #
56 # Revision 1.4 2002/01/28 19:35:14 bhenry
57 # Bug Fixes
58 #
59 # Revision 1.3 2002/01/25 07:17:35 bhenry
60 # Changed to inherit from Parser
61 #
62 #
63  
64 package VBTK::DBI;
65  
66 use 5.6.0;
67 use strict;
68 use warnings;
69 # I like using undef as a value so I'm turning off the uninitialized warnings
70 no warnings qw(uninitialized);
71  
72 use VBTK;
73 use VBTK::Common;
74 use VBTK::Parser;
75 use Storable qw(dclone);
76 use DBI;
77  
78 # Inherit methods from Parser class
79 our @ISA = qw(VBTK::Parser);
80  
81 our $VERBOSE = $ENV{VERBOSE};
82 our %POOL_CACHE;
83  
84 #-------------------------------------------------------------------------------
85 # Function: new
86 # Description: Object constructor. Allocates memory for all class members,
87 # opens a connection to the database, and validates passed values.
88 # Input Parms: VBTK::Oracle name pairs hash
89 # Output Parms: Pointer to class
90 #-------------------------------------------------------------------------------
91 sub new
92 {
93 my ($type,$self);
94
95 # If we're passed a hash as the first element, then it's probably from an
96 # inheriting class, so just use it as is.
97 if((defined $_[0])&&(UNIVERSAL::isa($_[0], 'HASH')))
98 {
99 $self = shift;
100 }
101 # Otherwise, allocate a new hash, bless it and handle any passed parms
102 else
103 {
104 $type = shift;
105 $self = {};
106 bless $self, $type;
107  
108 # Store all passed input name pairs in the object
109 $self->set(@_);
110 }
111  
112 my $defaultParms = {
113 Interval => 60,
114 DSN => $::REQUIRED,
115 User => undef,
116 Auth => undef,
117 Attr => undef,
118 VBHeader => undef,
119 VBDetail => [ '$data' ],
120 PreProcessor => undef,
121 VBServerURI => $::VBURI,
122 LogFile => undef,
123 LogHeader => undef,
124 LogDetail => undef,
125 RotateLogAt => '12:00am',
126 ErrorStatus => $::FAILED,
127 SqlClause => $::REQUIRED,
128 };
129  
130 # Validate the passed parameters
131 $self->validateParms($defaultParms) || &fatal("Exiting");
132  
133 # Try to lookup the password from a file in the VBHOME directory if
134 # it wasn't specified.
135 $self->lookupPassword;
136  
137 # Create a parser object, passing along all the input name/value pairs.
138 # Unused name/value pairs will be ignored
139 # Create a parser object, passing along all the corresponding name/value
140 # pairs.
141 $self->SUPER::new();
142  
143 &VBTK::register($self);
144 return $self;
145 }
146  
147 #-------------------------------------------------------------------------------
148 # Function: connect
149 # Description: Establish a connection to the specified database, closing any
150 # existing connection;
151 # Input Parms: Parser Name Pairs Hash
152 # Output Parms: None
153 #-------------------------------------------------------------------------------
154 sub connect
155 {
156 my $self = shift;
157 my $DSN = $self->{DSN};
158 my $User = $self->{User};
159 my $Auth = $self->{Auth};
160 my $Attr = $self->{Attr};
161 my $dbh = $self->{dbh};
162  
163 # If the dbh is already set in this object, then there was some kind of
164 # error and we need to drop and re-open the connection. We also need to
165 # remove the corresponding entry from the pool_cache.
166 if($dbh)
167 {
168 $dbh->disconnect();
169 $POOL_CACHE{$DSN,$User,$Auth,$Attr} = undef;
170 }
171  
172 $dbh = $POOL_CACHE{$DSN,$User,$Auth,$Attr};
173  
174 if ($dbh)
175 {
176 &log("Using existing DB connection to '$DSN' as '$User'");
177 }
178 else
179 {
180 &log("Connecting to '$DSN' as '$User' with Attr='$Attr'");
181  
182 $dbh = DBI->connect($DSN,$User,$Auth,undef,$Attr);
183  
184 # If the connect was successful, then add it into the pool.
185 if($dbh) { $POOL_CACHE{$DSN,$User,$Auth,$Attr} = $dbh; }
186 else { &error("Cannot connect"); }
187 }
188  
189 $self->{dbh} = $dbh;
190 $self->{sth} = undef;
191 }
192  
193 #-------------------------------------------------------------------------------
194 # Function: run
195 # Description: Execute the pre-defined SQL statement, retrieve the results,
196 # and pass them to the corresponding VBTK::Parser object. Also,
197 # calculate how long until the next execution needs to take
198 # place
199 # Input Parms: None
200 # Output Parms: None
201 #-------------------------------------------------------------------------------
202 sub run
203 {
204 my $self = shift;
205 my $Interval = $self->{Interval};
206 my $lastTime = $self->{lastTime};
207 my $ErrorStatus = $self->{ErrorStatus};
208 my $sth = $self->{sth};
209 my $dbh = $self->{dbh};
210 my $now = time;
211
212 my (@data,$msg,@result_array,$errstr,$sleepTime);
213  
214 $self->connect unless ($dbh);
215  
216 # If it's not time to run yet, then return
217 if(($sleepTime = $self->calcSleepTime()) > 0)
218 {
219 &log("Not time to run SQL, wait $sleepTime seconds")
220 if ($VERBOSE > 1);
221 return ($sleepTime,$::NOT_FINISHED);
222 }
223  
224 # If not already defined, parse and prepare the sql statement
225 $sth = $self->initialize_sql() if ($sth eq '');
226  
227 # Execute the SQL
228 if(($sth ne '') && ($sth->execute))
229 {
230 &log("Processing sql query results") if ($VERBOSE);
231 while(@data = $sth->fetchrow_array)
232 {
233 push(@result_array, [ @data ]);
234 }
235  
236 $self->parseData(\@result_array);
237 }
238 # Handle errors
239 else
240 {
241 $errstr = $dbh->{errstr} if ($dbh ne '');
242 $msg = "Cannot execute SQL - $errstr";
243 $self->parseData(undef,$ErrorStatus,$msg);
244 &error($msg);
245  
246 # Re-open the connection
247 $self->connect;
248 }
249  
250 $sleepTime = $self->calcSleepTime(1);
251  
252 ($sleepTime,$::NOT_FINISHED);
253 }
254  
255 #-------------------------------------------------------------------------------
256 # Function: initialize_sql
257 # Description: Prepare the specified SQL.
258 # Input Parms: None
259 # Output Parms: DBI prepared sql pointer
260 #-------------------------------------------------------------------------------
261 sub initialize_sql
262 {
263 my $self = shift;
264 my $SqlClause = $self->{SqlClause};
265 my $dbh = $self->{dbh};
266
267 return undef unless ($dbh);
268  
269 my $sql = $SqlClause;
270  
271 &log("Preparing SQL:\n$sql") if ($VERBOSE);
272 my $sth = $dbh->prepare($sql) ||
273 &error("Cannot prepare sql '$sql' - " . $dbh->errstr);
274  
275 $self->{sth} = $sth;
276  
277 ($sth);
278 }
279  
280 #-------------------------------------------------------------------------------
281 # Function: lookupPassword
282 # Description: Try to lookup the password for the specified user. If no user
283 # was specified, then just use the first entry in the password file.
284 # Input Parms: None
285 # Output Parms: None
286 #-------------------------------------------------------------------------------
287 sub lookupPassword
288 {
289 my $self = shift;
290 my $User = $self->{User};
291 my $DSN = $self->{DSN};
292 my ($user,$pswd);
293  
294 return unless (-f $::VBPSWD);
295  
296 &log("Looking up the password in '$::VBPSWD'") if ($VERBOSE);
297  
298 # Read the password file
299 my $fh = new FileHandle "< $::VBPSWD";
300 my @list = <$fh>;
301 chomp(@list);
302 $fh->close;
303  
304 # If no user was specified, then just use the first entry
305 if(! defined $User)
306 {
307 ($user,$pswd) = split(/[:\s]+/,$list[0]);
308 $self->{User} = $user;
309 }
310 # Otherwise, try to find an entry which matches the specified user
311 else
312 {
313 ($pswd) = grep(s/^$DSN[:\s]+$User[:\s]+//,@list);
314 }
315  
316 $self->{Auth} = $pswd if (! defined $self->{Auth});
317  
318 (1);
319 }
320  
321 # Put in a stub for handleSignal
322 sub handleSignal { (0); }
323  
324 1;
325 __END__