VBTK/Objects/Rrd.pm untested

filter: Statementstmt 0.0% 0 / 210 Branchbran 0.0% 0 / 82 Conditioncond 0.0% 0 / 24 MC/DCmcdc 0.0% 0 / 13 Subroutinesub 0.0% 0 / 17 Podpod 0.0% 0 / 10 totaltotal 0.0% 0 / 356 CC 42 SCAR 45.3
CC
42
Cov
0%
generateGraph
210.0
createRrdDb
110.0
writeRrdDb
110.0
CRAP 92.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/Objects/Rrd.pm,v $
7 # $Revision: 1.7 $
8 # $Date: 2002/03/04 20:53:07 $
9 # $Author: bhenry $
10 # $Locker: $
11 # $State: Exp $
12 #
13 # Purpose: A common library to simplify the interface between
14 # VB and Rrd
15 #
16 # Directions:
17 #
18 # Invoked by: VBTK::Parser
19 #
20 # Depends on: VBTK::Common, rrd
21 #
22 # Copyright (C) 1996 - 2002 Brent Henry
23 #
24 # This program is free software; you can redistribute it and/or
25 # modify it under the terms of version 2 of the GNU General Public
26 # License as published by the Free Software Foundation available at:
27 # http://http://www.gnu.org/copyleft/gpl.html
28 #
29 # This program is distributed in the hope that it will be useful,
30 # but WITHOUT ANY WARRANTY; without even the implied warranty of
31 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
32 # GNU General Public License for more details.
33 #
34 #############################################################################
35 #
36 #
37 # REVISION HISTORY:
38 #
39 # $Log: Rrd.pm,v $
40 # Revision 1.7 2002/03/04 20:53:07 bhenry
41 # *** empty log message ***
42 #
43 # Revision 1.6 2002/03/04 16:49:10 bhenry
44 # Changed requirement back to perl 5.6.0
45 #
46 # Revision 1.5 2002/03/02 00:53:55 bhenry
47 # Documentation updates
48 #
49 # Revision 1.4 2002/02/08 02:14:21 bhenry
50 # *** empty log message ***
51 #
52 # Revision 1.3 2002/01/25 16:41:33 bhenry
53 # Changed to use 'serPut' instead of serialize
54 #
55 # Revision 1.2 2002/01/21 17:07:50 bhenry
56 # Disabled 'uninitialized' warnings
57 #
58 # Revision 1.1.1.1 2002/01/17 18:05:57 bhenry
59 # VBTK Project
60 #
61 #
62  
63 package VBTK::Rrd;
64  
65 use 5.6.0;
66 use strict;
67 use warnings;
68 # I like using undef as a value so I'm turning off the uninitialized warnings
69 no warnings qw(uninitialized);
70  
71 use VBTK::Common;
72 use VBTK::File;
73 use Date::Manip;
74  
75 # Import global variables from package main.
76 our $VERBOSE=$ENV{'VERBOSE'};
77  
78 #-------------------------------------------------------------------------------
79 # Function: new
80 # Description: Object constructor. Allocates memory for all class members
81 # Input Parms: Parameter hash
82 # Output Parms: Pointer to class
83 #-------------------------------------------------------------------------------
84 sub new
85 {
86 my $type = shift;
87 my $self = {};
88 bless $self, $type;
89  
90 # Load in all passed parms
91 $self->set(@_);
92  
93 # Setup a hash of default parameters
94 my $defaultParms = {
95 RrdDbPath => $::REQUIRED,
96 RrdDbFile => "$self->{RrdDbPath}/RRD.db",
97 RrdDbMetaFile => "$self->{RrdDbPath}/RRD.ser",
98 Interval => undef,
99 Min => 0,
100 Max => undef,
101 CF => "AVERAGE",
102 XFF => 0.5,
103 DST => "GAUGE",
104 ForkRrdUpdate => 0,
105 };
106  
107 # Run the validation, setting defaults if values are not already set
108 $self->validateParms($defaultParms) || return -1;
109  
110 &log("Creating Rrd object '$self->{RrdDbFile}'") if ($VERBOSE > 1);
111
112 $self->{metaFileObj} = new VBTK::File($self->{RrdDbMetaFile});
113  
114 # Load in settings from prior transmissions - Not used right now
115 # $self->loadMetaData;
116  
117 # Set default member values
118 $self->{dataQueue} = [];
119  
120 return $self;
121 }
122  
123 #-------------------------------------------------------------------------------
124 # Function: addGraphDbData
125 # Description: Add data to the Rrd database
126 # Input Parms: Graph parms
127 # Output Parms: None
128 #-------------------------------------------------------------------------------
129 sub addGraphDbData
130 {
131 my $self = shift;
132 my %args = @_;
133  
134 my ($key);
135  
136 my $defaultParms = {
137 Min => undef,
138 Max => undef,
139 XFF => undef,
140 CF => undef,
141 DST => undef,
142 DataQueue => $::REQUIRED,
143 Interval => undef
144 };
145  
146 # Run the validation, setting defaults if values are not already set
147 &validateParms(\%args,$defaultParms) || return undef;
148  
149 # Now step through each value passed and use it to override the existing
150 # parameters.
151 foreach $key (%args)
152 {
153 $self->{$key} = $args{$key} if ($args{$key} ne undef);
154 }
155  
156 $self->writeRrdDb || return undef;
157  
158 # Not doing anything right now, so we'll just comment it out
159 #$self->saveMetaData;
160  
161 (1);
162 }
163  
164 #-------------------------------------------------------------------------------
165 # Function: createRrdDb
166 # Description: Create an RrdDb
167 # Input Parms: None
168 # Output Parms: None
169 #-------------------------------------------------------------------------------
170 sub createRrdDb
171 {
172 my $self = shift;
173 my $RrdDbFile = $self->{RrdDbFile};
174  
175 # Just return if the filename hasn't been defined
176 return undef if (-f $RrdDbFile);
177  
178 my $Interval = $self->{Interval};
179 my $DST = $self->{DST};
180 my $Min = $self->{Min};
181 my $Max = $self->{Max};
182 my $CF = $self->{CF};
183 my $XFF = $self->{XFF};
184 my $DataQueue = $self->{DataQueue};
185  
186 # Look at the first data element to determine some variables
187 my @firstRow = split(/:/,$DataQueue->[0]);
188 my $colCount = @firstRow - 1;
189  
190 if ($colCount < 1)
191 {
192 &log("Not enough data passed to create RRD database, waiting till next round")
193 if ($VERBOSE);
194 return undef;
195 }
196  
197 my $startTime = $firstRow[0] - 1;
198  
199 # Setup a default structure to provide standard graph ranges
200 my %RRA = ( 1 => 60, # $steps => $rows for RRA
201 1 => 1440, # assumes max 1200 pixel graph
202 7 => 1440, # "1440 7($Interval) samples" weekly RRA
203 14 => 3131, # "3131 14($Inverval) samples" monthly RRA
204 180 => 2922 # "2922 180($Interval) samples" yearly RRA
205 );
206  
207 my $step = $Interval;
208 my $heartbeat = $Interval * 2;
209 my ($steps,$rows,$cmd,$pos);
210  
211 # Default Min and Max to unlimited if not specified
212 $Min = "U" if ($Min eq undef);
213 $Max = "U" if ($Max eq undef);
214  
215 &log("Creating new RrdDbFile - $RrdDbFile with step $step") if ($VERBOSE);
216  
217 # Start forming the command
218 $cmd = "$::RRDBIN create $RrdDbFile --start $startTime --step $step";
219  
220 # Formulate the string for the DS names - DS:ds-name:DST:heartbeat:min:max
221 for($pos=0; $pos < $colCount; $pos++)
222 {
223 $cmd .= " DS:ds$pos:$DST:$heartbeat:$Min:$Max";
224  
225 # create 5 RRAs with hard-coded values per data Column
226 while (($steps,$rows) = each %RRA)
227 {
228 $cmd .= " RRA:$CF:$XFF:$steps:$rows";
229 }
230 }
231  
232 # execute the whole command
233 &log("Executing '$cmd'") if ($VERBOSE > 1);
234 system("$cmd");
235  
236 if($? != 0)
237 {
238 &error("Non-zero exit code $? while executing '$cmd' - $!");
239 return undef;
240 }
241  
242 # Check to make sure the db file was created
243 unless (-f $RrdDbFile)
244 {
245 &error("RrdDb was not created");
246 return undef;
247 }
248  
249 (1);
250 }
251  
252 #-------------------------------------------------------------------------------
253 # Function: writeRrdDb
254 # Description: Write out the passed RRD Db Data
255 # Input Parms: None
256 # Output Parms: None
257 #-------------------------------------------------------------------------------
258 sub writeRrdDb
259 {
260 my $self = shift;
261 my $RrdDbFile = $self->{RrdDbFile};
262 my $DataQueue = $self->{DataQueue};
263 my $ForkRrdUpdate = $self->{ForkRrdUpdate};
264 my ($timestamp,$pid);
265  
266 # If the db file doesn't exist then create it an return if there are
267 # any errors
268 if (! -f $RrdDbFile)
269 {
270 $self->createRrdDb || return undef;
271 }
272  
273 # Retrieve the last timestamp in the database
274 my $lastTimestamp = $self->{lastTimestamp} || $self->getLastTimestamp;
275  
276 # Clear out any entries in the dataqueue which are <= the last timestamp
277 while(@{$DataQueue} > 0)
278 {
279 ($timestamp) = split(/:/,$DataQueue->[0]);
280 last if($timestamp > $lastTimestamp);
281  
282 &log("Warning: Ignoring graph data entry - $DataQueue->[0]");
283 shift(@{$DataQueue});
284 }
285  
286 # Don't save if nothing has changed
287 return 1 if (@{$DataQueue} == 0);
288  
289 # Start the rrd update command string
290 my @cmd = ($::RRDBIN,'update',$RrdDbFile);
291  
292 # Add on all the data
293 push(@cmd,@{$DataQueue});
294  
295 # Fork?
296 if($ForkRrdUpdate)
297 {
298 # Parent process
299 if($pid = fork)
300 {
301 &log("Forked '@cmd' - pid $pid") if ($VERBOSE > 1);
302 }
303 # Child process
304 elsif(defined $pid)
305 {
306 # Insulate this process from the vbc controller process
307 setpgrp(0,$$);
308
309 exec @cmd || &fatal("Could not start cmd '@cmd' - $!");
310 }
311 else
312 {
313 &error("Can't fork!");
314 }
315 }
316 else
317 {
318 &log("Running '@cmd'") if ($VERBOSE > 1);
319 system @cmd;
320 my $exitVal = $? >> 8;
321 &error("Call to $::RRDBIN failed with exit code $exitVal") if ($exitVal);
322 }
323  
324 # Clear the data queue and store the last timestamp.
325 my $lastEntry = pop(@{$DataQueue});
326 ($self->{lastTimestamp}) = split(/:/,$lastEntry);
327  
328 @{$DataQueue} = ();
329  
330 (1);
331 }
332  
333 #-------------------------------------------------------------------------------
334 # Function: saveMetaData
335 # Description: Save the meta data about this object which is not stored in the RRD
336 # database into a file in the vbobj directory, so that if the
337 # VB server is re-started, we don't lose the important graph settings
338 # like 'labels', 'title', etc.
339 # Input Parms: None
340 # Output Parms: None
341 #-------------------------------------------------------------------------------
342 sub saveMetaData
343 {
344 my $self = shift;
345 my $metaFileObj = $self->{metaFileObj};
346 my $RrdDbMetaFile = $self->{RrdDbMetaFile};
347  
348 # Commented out all elements but decided to leave this in place in case
349 # we need it later on.
350 my $saveStruct = { };
351  
352 &log("Writing serialized metadata to '$RrdDbMetaFile'") if ($VERBOSE > 1);
353  
354 unless($metaFileObj->serPut($saveStruct))
355 {
356 &error("Can't save RRD meta data to $RrdDbMetaFile");
357 return undef;
358 }
359  
360 (1);
361 }
362  
363 #-------------------------------------------------------------------------------
364 # Function: loadMetaData
365 # Description: Load the meta data for this object
366 # Input Parms: None
367 # Output Parms: None
368 #-------------------------------------------------------------------------------
369 sub loadMetaData
370 {
371 my $self = shift;
372 my $metaFileObj = $self->{metaFileObj};
373 my $RrdDbMetaFile = $self->{RrdDbMetaFile};
374  
375 &log("Loading RRD metadata from '$RrdDbMetaFile'") if ($VERBOSE > 1);
376  
377 my $metaStruct = $metaFileObj->serGet() || return undef;
378  
379 # Load all the values into the object
380 $self->set(%{$metaStruct});
381  
382 (1);
383 }
384  
385 #-------------------------------------------------------------------------------
386 # Function: generateGraph
387 # Description: Generate the gif or png for the current object
388 # Input Parms: None
389 # Output Parms: GraphData
390 #-------------------------------------------------------------------------------
391 sub generateGraph
392 {
393 my $self = shift;
394 my %args = @_;
395  
396 # Setup some defaults
397 my $defaultParms = {
398 DataSourceList => [],
399 Labels => $::REQUIRED,
400 LineWidth => 1,
401 Colors => '#0000FF,#00FF00,#FF0000,#CC00FF,#000000,#CC0000,' .
402 '#00FFFF,#990000,#996600,#999999',
403 CF => 'AVERAGE',
404 VLabel => undef,
405 Title => undef,
406 TimeWindow => '1day',
407 XSize => 600,
408 YSize => 60
409 };
410  
411 # Apply the defaults and verify the inputs
412 &validateParms(\%args,$defaultParms) || return undef;
413  
414 # Define scope of local variables
415 my ($pos,$vName,$dsName,$color,$label,$vCmd,$GPrint,$cmd,$lCmd,$source);
416 my ($sourceObj,$sourceObjName,$sourceRrdObj,$sourceRrdDbFile,$dsNum,$vnNum);
417  
418 # Calculate starting and ending times in unix time format.
419 my $end = time;
420 my $startTimestamp = &DateCalc("today","- $args{TimeWindow}");
421 my $start = &unixdate($startTimestamp);
422  
423 # Escape out any " characters in the Title or VLabel parms
424 $args{Title} =~ s/"/\\"/;
425 $args{VLabel} =~ s/"/\\"/;
426  
427 # begin cmd string for rrdtool
428 $cmd = "$::RRDBIN graph - -s $start -e $end -c BACK#CCCCFF ";
429 $cmd .= "-t \"$args{Title}\" " if ($args{YSize} >= 100);
430 $cmd .= "-w $args{XSize} -h $args{YSize} -a PNG ";
431 $cmd .= "-v \"$args{VLabel}\" " if ($args{VLabel} ne undef);
432 $cmd .= "\"COMMENT:$args{Title}\:\" " if ($args{YSize} < 100);
433  
434 # Check to see if the Labels, Colors, and DataSourceList parms are array references.
435 # If not then turn them it one by splitting them.
436 my $Labels = (ref($args{Labels}) eq 'ARRAY') ?
437 $args{Labels} : [ split(/[,]/,$args{Labels}) ];
438 my $Colors = (ref($args{Colors}) eq 'ARRAY') ?
439 $args{Colors} : [ split(/[,]/,$args{Colors}) ];
440 my $DataSourceList = (ref($args{DataSourceList}) eq 'ARRAY') ?
441 $args{DataSourceList} : [ split(/[,]/,$args{DataSourceList}) ];
442  
443 my $colCount = @{$Labels};
444  
445 # Now setup DEF and LINE attrib for each column in the database to be
446 # graphed
447 foreach $pos (0..$#{$Labels})
448 {
449 $color = $Colors->[$pos];
450 $label = $Labels->[$pos];
451 $source = $DataSourceList->[$pos];
452 $dsNum = $pos;
453 $vnNum = $pos;
454  
455 # Escape out any ' characters in the label
456 $label =~ s/"/\\"/;
457  
458 if($source =~ /^(.*):(\d+)$/)
459 {
460 ($sourceObjName,$dsNum) = ($1,$2);
461 }
462 elsif($source ne undef)
463 {
464 &error("Invalid data source '$source' specified");
465 return undef;
466 }
467  
468 if($sourceObjName ne undef)
469 {
470 $sourceObj = &VBTK::Objects::FindObjByName($sourceObjName) || return undef;
471 $sourceRrdObj = $sourceObj->getRrdObj || return undef;
472 $sourceRrdDbFile = $sourceRrdObj->getRrdDbFile || return undef;
473 }
474 else
475 {
476 $sourceRrdDbFile = $self->{RrdDbFile};
477 }
478  
479 if (! -f $sourceRrdDbFile)
480 {
481 &error("Reference to non-existant Rrd DB file '$sourceRrdDbFile'");
482 return undef;
483 }
484  
485 $vName = "vn$vnNum";
486 $dsName = "ds$dsNum";
487  
488 $vCmd = "DEF:$vName=$sourceRrdDbFile:$dsName:$args{CF} ";
489  
490 # If there's only one label, then do a line graph, otherwise, do an
491 # area graph.
492 $lCmd = ($colCount > 1) ?
493 "\"LINE$args{LineWidth}:$vName$color:$label\" " :
494 "\"AREA:$vName$color:$label\" ";
495  
496 $GPrint = "\"GPRINT:$vName:LAST:%3.2lf%s\" ";
497 $cmd .= " $vCmd $lCmd $GPrint";
498 }
499  
500 # Execute the command
501 &log("Executing '$cmd'") if ($VERBOSE > 1);
502 my $pngData = `$cmd`;
503  
504 if($? != 0)
505 {
506 &error("Non-zero exit code $? while executing '$cmd' - $!");
507 return undef;
508 }
509  
510 ($pngData);
511 }
512  
513 #-------------------------------------------------------------------------------
514 # Function: canGraph
515 # Description: Return true or false indicating if this object can generate
516 # graphs, meaning that the RrdDbFile exists.
517 # Input Parms: None
518 # Output Parms: GraphData
519 #-------------------------------------------------------------------------------
520 sub canGraph
521 {
522 my $self = shift;
523 my $RrdDbFile = $self->{RrdDbFile};
524  
525 # Just return if the filename hasn't been defined
526 return undef if (! -f $RrdDbFile);
527  
528 (1);
529 }
530  
531 #-------------------------------------------------------------------------------
532 # Function: getLastTimestamp
533 # Description: Retrieve the last RrdDb timestamp
534 # Input Parms: None
535 # Output Parms: Timestamp
536 #-------------------------------------------------------------------------------
537 sub getLastTimestamp
538 {
539 my $self = shift;
540 my $RrdDbFile = $self->{RrdDbFile};
541  
542 return 1 if (! -f $RrdDbFile);
543  
544 # Use 'rrdtool last' to get time stamp of most recent rrddb entry
545 &log("Retrieving last timestamp from '$RrdDbFile'") if ($VERBOSE > 1);
546  
547 my $cmd = "$::RRDBIN last $RrdDbFile";
548 my $lastTimestamp = `$cmd`;
549  
550 if($? != 0)
551 {
552 &error("Non-zero exit code $? while executing '$cmd' - $!");
553 return undef;
554 }
555  
556 chomp($lastTimestamp);
557  
558 &log("lastTimestamp is $lastTimestamp") if ($VERBOSE > 1);
559 $self->{lastTimestamp} = $lastTimestamp;
560  
561 ($lastTimestamp);
562 }
563  
564 # Simple Get Methods
565 sub getRrdDbFile { $_[0]->{RrdDbFile}; }
566  
567 1;
568 __END__