Graph.pm untested

filter: Statementstmt 0.0% 0 / 323 Branchbran 0.0% 0 / 110 Conditioncond 0.0% 0 / 79 MC/DCmcdc 0.0% 0 / 49 Subroutinesub 0.0% 0 / 29 Podpod 0.0% 0 / 23 totaltotal 0.0% 0 / 613 CC 56 SCAR 39.2
CC
56
Cov
0%
_2d_plot
110.0
define
110.0
_save_csv
90.0
CRAP 50.3
1 use strict;
2 use IO::File;
3 use IO::Dir;
4 use File::Basename;
5 use POSIX qw(strftime);
6  
7 package StatsView::Graph;
8 use vars qw($VERSION @Constructors);
9 $VERSION="1.15";
10  
11 ################################################################################
12 # Terminology:
13 # sample - All data collected at a given point in tstamp
14 # column - A time-series of data, eg percentage busy
15 # instance - An entity for which data is collected,
16 # eg disk drive, network interface, user, Oracle tablespace
17 # data point - An individual numeric statistic value
18 #
19 # Data of 2 types can be held - 2-d or 3-d. 2-d data does not have any
20 # instance information, eg for CPU usage, total idle,usr,sys,wio. 3-d data has
21 # instance information, eg for CPU usage, idle,usr,sys by CPU.
22 #
23 # 2-d data is held as
24 # $self->{data}[0]{tstamp}
25 # $self->{data}[0]{value}[0]
26 # :
27 # $self->{data}[0]{value}[n]
28 # :
29 # $self->{data}[m]{tstamp}
30 # $self->{data}[m]{value}[0]
31 # :
32 # $self->{data}[m]{value}[n]
33 #
34 # 3-d data is held as
35 # $self->{data}{$i}[0]{tstamp}
36 # $self->{data}{$i}[0]{value}[0]
37 # :
38 # $self->{data}{$i}[0]{value}[n]
39 # :
40 # $self->{data}{$i}[m]{tstamp}
41 # $self->{data}{$i}[m]{value}[0]
42 # :
43 # $self->{data}{$i}[m]{value}[n]
44 #
45 # where
46 # $i = instance
47 # m = number of samples
48 # n = number of data points per sample
49  
50 ################################################################################
51 # PRIVATE
52  
53 sub BEGIN
54 {
55 # Initialise the tmpfile index
56 $StatsView::Graph::tmpfile = 1;
57  
58 # Search for and load in parser subclasses at run-time
59 foreach my $dir (@INC)
60 {
61 my $gd = "$dir/StatsView/Graph";
62 next if (! -d $gd);
63 next if (! defined(my $dh = IO::Dir->new($gd)));
64 foreach my $g (grep(/\.pm$/, $dh->read()))
65 {
66 $g =~ s/\.pm//;
67 $g = "StatsView::Graph::$g";
68 my $ctor;
69 eval "require $g; \$ctor = sub { ${g}->new(\@_); };" || die($@);
70 push(@Constructors, $ctor);
71 }
72 $dh->close();
73 }
74 }
75  
76 ################################################################################
77 # PRIVATE
78  
79 sub reinit($;$)
80 {
81 my ($self, $cat) = @_;
82  
83 # Set via define_cols method, called by child read method
84 $self->{colindex} = undef; # Hash of col name => data index
85 $self->{coltype} = undef; # Hash of col name => col type
86 # D=date, T=text, N=number, %=percentage, 0-100
87  
88 # Set by define_inst method, called by child read method
89 $self->{instance} = undef; # For 3-d data - hash of instance => gnuplot index
90 $self->{index_3d} = 0; # A counter used to number 3d datasets
91  
92 # Set by child read method
93 $self->{data} = undef; # 2-d or 3-d array of data (see above for format)
94 $self->{start} = 0; # Start time of samples
95 $self->{interval} = 0; # Interval between samples
96 $self->{finish} = 0; # Finish time of samples
97 $self->{title} = ""; # Title of graph
98  
99 # Set by define method
100 $self->{plot_cat} = $cat ? $cat : "none"; # Category of data to plot
101 $self->{plot_cols} = undef; # Column(s) to plot (2d=arrayref, 3d=scalar)
102 $self->{plot_insts} = undef; # Instance(s) to plot (2d=undef, 3d=arrayref)
103 $self->{plot_scale} = undef; # Log/Normal scale to be used for plot
104 $self->{plot_start} = undef; # Start time of plot
105 $self->{plot_finish} = undef; # Finish time of plot
106 }
107  
108 ################################################################################
109 # PRIVATE
110  
111 sub _2d_plot($)
112 {
113 my ($self) = @_;
114 my ($cat, $cols) = @$self{qw(plot_cat plot_cols)};
115  
116 # Output the data into a file, of this is the first time through
117 if (! $self->{tmpfile}{$cat})
118 {
119 my $fname = "/tmp/svtmp$$.$StatsView::Graph::tmpfile";
120 $StatsView::Graph::tmpfile++;
121 $self->{tmpfile}{$cat} = $fname;
122 my $out = IO::File->new($fname, "w") || die("Can't open $fname: $!\n");
123 my $last_was_blank = 1;
124 foreach my $sample (@{$self->{data}})
125 {
126 my $val = $sample->{value};
127 if (@$val > 0)
128 {
129 $out->print(POSIX::strftime("%d/%m/%Y %T",
130 localtime($sample->{tstamp})), "\t",
131 join("\t", @$val), "\n");
132 $last_was_blank = 0;
133 }
134 elsif (! $last_was_blank)
135 {
136 $out->print("\n");
137 $last_was_blank = 1;
138 }
139 }
140 $out->close();
141 }
142  
143 # Clear the plot if no cols are selected
144 if (! @$cols)
145 {
146 $self->{gnuplot}->print("clear\n");
147 return;
148 }
149  
150 # Set up the headers and scale
151 my $scale = $self->{plot_scale} eq "log" ? "logscale" : "nologscale";
152 $self->{gnuplot}->print("reset\nset title '", $self->get_title(), "'\n",
153 "set data style lines\nset $scale y\n",
154 "set xdata time\nset timefmt '%d/%m/%Y %H:%M:%S'\n",
155 "set xlabel 'Time'\nset format x '%H:%M:%S'\n");
156  
157 # Figure out how many types of data we have
158 my %t;
159 @t{@{$self->{coltype}}{@$cols}} = @$cols;
160 my $plot_type = join('', sort(keys(%t)));
161 undef(%t);
162  
163 if ($plot_type eq '%N')
164 {
165 $self->{gnuplot}->print("set y2range [0:100]\nset y2tics\n",
166 "set ytics nomirror\nset y2label '%'\n");
167 }
168 else
169 {
170 $self->{gnuplot}->print("set rmargin 3\n");
171 }
172 if ($plot_type eq '%')
173 {
174 $self->{gnuplot}->print("set yrange [0:100]\n");
175 }
176  
177 # Generate the plot command
178 $self->{gnuplot}->print("plot ['",
179 POSIX::strftime("%d/%m/%Y %T", localtime($self->{plot_start})),
180 "':'",
181 POSIX::strftime("%d/%m/%Y %T", localtime($self->{plot_finish})),
182 "'] ");
183 my $not_first = 0;
184 foreach my $col (@$cols)
185 {
186 my $index = $self->{colindex}{$col} + 3;
187 $self->{gnuplot}->print(", ") if ($not_first);
188 $self->{gnuplot}->print("'$self->{tmpfile}{$cat}' using 1:$index ");
189 $self->{gnuplot}->print("axes x1y2 ")
190 if ($plot_type ne '%' && $self->{coltype}{$col} eq '%');
191 $self->{gnuplot}->print("title '$col'");
192 $not_first = 1;
193 }
194 $self->{gnuplot}->print("\n");
195 }
196  
197 ################################################################################
198 # PRIVATE
199  
200 sub _3d_plot($)
201 {
202 my ($self) = @_;
203 my ($cat, $col, $insts) = @$self{qw(plot_cat plot_cols plot_insts)};
204  
205 # Output the data into a file, of this is the first time through
206 if (! $self->{tmpfile}{$cat})
207 {
208 my $fname = "/tmp/svtmp$$.$StatsView::Graph::tmpfile";
209 $StatsView::Graph::tmpfile++;
210 $self->{tmpfile}{$cat} = $fname;
211 my $out = IO::File->new($fname, "w") || die("Can't open $fname: $!\n");
212 my @inst_order = sort({ $self->{instance}{$a} <=> $self->{instance}{$b} }
213 keys(%{$self->{instance}}));
214 foreach my $inst_name (@inst_order)
215 {
216 my $last_was_blank = 1;
217 foreach my $sample (@{$self->{data}{$inst_name}})
218 {
219 my $val = $sample->{value};
220 if (@$val > 0)
221 {
222 $out->print(POSIX::strftime("%d/%m/%Y %T",
223 localtime($sample->{tstamp})),
224 "\t", join("\t", @$val), "\n");
225 $last_was_blank = 0;
226 }
227 elsif (! $last_was_blank)
228 {
229 $out->print("\n");
230 $last_was_blank = 1;
231 }
232 }
233 $out->print("\n\n");
234 }
235 $out->close();
236 }
237  
238 # Clear the plot if no instances are selected
239 if (! @$insts)
240 {
241 $self->{gnuplot}->print("clear\n");
242 return;
243 }
244  
245 # Set up the headers and scale
246 my $scale = $self->{plot_scale} eq "log" ? "logscale" : "nologscale";
247 $self->{gnuplot}->print("reset\nset title '", $self->get_title(), "'\n",
248 "set data style lines\nset ylabel '$col'\n",
249 "set xdata time\nset timefmt '%d/%m/%Y %H:%M:%S'\n",
250 "set $scale y\nset rmargin 3\n",
251 "set xlabel 'Time'\nset format x '%H:%M:%S'\n");
252  
253 if ($self->{coltype}{$col} eq '%')
254 {
255 $self->{gnuplot}->print("set yrange [0:100]\n");
256 }
257  
258 # Generate the plot command
259 $self->{gnuplot}->print("plot ['",
260 POSIX::strftime("%d/%m/%Y %T", localtime($self->{plot_start})),
261 "':'",
262 POSIX::strftime("%d/%m/%Y %T", localtime($self->{plot_finish})),
263 "'] ");
264 my $not_first = 0;
265 foreach my $inst (@$insts)
266 {
267 my $index = $self->{colindex}{$col} + 3;
268 $self->{gnuplot}->print(", ") if ($not_first);
269 $self->{gnuplot}->print("'$self->{tmpfile}{$cat}' ",
270 "index $self->{instance}{$inst} ",
271 "using 1:$index title '$inst'");
272 $not_first = 1;
273 }
274 $self->{gnuplot}->print("\n");
275 }
276  
277 ################################################################################
278 # PRIVATE
279  
280 sub _save_gnuplot($$$$)
281 {
282 my ($self, $file, $format, $orientation, $color) = @_;
283  
284 my $cmd = "set terminal ";
285 CASE:
286 {
287 $format eq "postscript" and do
288 {
289 $cmd .= "postscript eps enhanced $color 10";
290 last CASE;
291 };
292 $format eq "cgm" and do
293 {
294 $cmd .= "cgm $orientation $color 10";
295 last CASE;
296 };
297 $format eq "mif" and do
298 {
299 $color = $color eq "color" ? "colour" : "monochrome";
300 $cmd .= "mif $color polyline";
301 last CASE;
302 };
303 $format eq "gif" and do
304 {
305 $cmd .= "gif medium";
306 last CASE;
307 };
308 # default
309 die("Unknown file format $format\n");
310 last CASE;
311 }
312  
313 $self->{gnuplot}->print("$cmd\nset output '$file'\n");
314 $self->plot();
315 $self->{gnuplot}->print("set output\nset terminal x11\n");
316 }
317  
318 ################################################################################
319 # PRIVATE
320  
321 sub _save_csv($$)
322 {
323 my ($self, $file) = @_;
324  
325 my $csv = IO::File->new($file, "w") || die("Can't open $file: $!\n");
326 my ($cols, $start, $finish) = @$self{qw(plot_cols plot_start plot_finish)};
327  
328 # 2-d data
329 if (! defined($self->{instance}))
330 {
331 $csv->print($self->get_title(), "\n\n");
332 $csv->print("Time,", join(",", @$cols), "\n");
333 my $fmt = join(',', @{$self->{coltype}}{@$cols});
334 $fmt =~ s/%/%s%%/g;
335 $fmt =~ s/[DTN]/%s/g;
336 my @indices = @{$self->{colindex}}{@$cols};
337 foreach my $sample (@{$self->{data}})
338 {
339 next if ($sample->{tstamp} < $start);
340 last if ($sample->{tstamp} > $finish);
341 $csv->printf("%s,$fmt\n",
342 POSIX::strftime("%d/%m/%Y %T", localtime($sample->{tstamp})),
343 @{$sample->{value}}[@indices]) if (@{$sample->{value}});
344 }
345 }
346 # 3-d data
347 else
348 {
349 my $insts = $self->{plot_insts};
350 my $fmt = join(',', ($self->{coltype}{$cols}) x @$insts);
351 $fmt =~ s/%/%s%%/g;
352 $fmt =~ s/[DTN]/%s/g;
353  
354 # Invert the data so that all data for a given time is accessible
355 my $first = 1;
356 my %data;
357 my $index = @{$self->{colindex}}{$cols};
358 foreach my $inst_name (@{$self->{plot_insts}})
359 {
360 foreach my $sample (@{$self->{data}{$inst_name}})
361 {
362 my $tstamp = $sample->{tstamp};
363 next if ($tstamp < $start);
364 last if ($tstamp > $finish);
365 $data{$tstamp}{$inst_name} = $sample->{value}[$index]
366 if (@{$sample->{value}});
367 }
368 $first = 0;
369 }
370  
371 # Print out the data
372 $csv->print($self->get_title(), " - $cols\n\n");
373 $csv->print("Time,", join(",", @$insts), "\n");
374 foreach my $tstamp (sort(keys(%data)))
375 {
376 $csv->print(POSIX::strftime("%d/%m/%Y %T", localtime($tstamp)));
377 foreach my $inst_name (@$insts)
378 {
379 my $value = $data{$tstamp}{$inst_name};
380 $csv->print(",", $value ? $value : "0");
381 }
382 $csv->print("\n");
383 }
384 }
385 $csv->close();
386 }
387  
388 ################################################################################
389 # PRIVATE
390  
391 sub DESTROY($)
392 {
393 my ($self) = @_;
394 if ($self->{gnuplot})
395 {
396 $self->{gnuplot}->print("quit\n");
397 $self->{gnuplot}->close();
398 }
399 foreach my $file (values(%{$self->{tmpfile}})) { unlink($file); }
400 $self->{tmpfile} = undef;
401 }
402  
403 ################################################################################
404 # PROTECTED
405  
406 sub init($)
407 {
408 my ($class, $file) = @_;
409 $class = ref($class) || $class;
410 my $self =
411 {
412 # Set by base class
413 file => $file, # Filename the data is stored in
414 gnuplot => undef, # Filehandle of gnuplot session
415 tmpfile => undef, # Names of gnuplot data files
416  
417 # Set by child new method
418 category => undef, # List of data categories in file, undef = none
419 };
420 bless($self, $class);
421 $self->reinit();
422 return($self);
423 }
424  
425 ################################################################################
426 # PROTECTED
427  
428 sub read($;$)
429 {
430 my ($self, $cat) = @_;
431 my $class = ref($self) || $self;
432 $self->reinit($cat);
433 }
434  
435 ################################################################################
436 # PROTECTED
437  
438 sub define_cols($\@\@)
439 {
440 my ($self, $colname, $coltype) = @_;
441 die("Mismatching col name/type lists\n") if (@$colname != @$coltype);
442 $self->{colindex} = {};
443 $self->{coltype} = {};
444 my ($col, $index);
445 $index = 0;
446 foreach $col (@$colname) { $self->{colindex}{$col} = $index++; }
447 foreach $col (@$colname) { $self->{coltype}{$col} = shift(@$coltype); }
448 }
449  
450 ################################################################################
451 # PROTECTED
452  
453 sub define_inst($$)
454 {
455 my ($self, $inst) = @_;
456 $self->{instance}{$inst} = $self->{index_3d}++
457 if (! exists($self->{instance}->{$inst}));
458 }
459  
460 ################################################################################
461 # PUBLIC Static method
462  
463 sub new($)
464 {
465 my ($class, $file) = @_;
466 $class = ref($class) || $class;
467  
468 # Check for nonexistent or empty files
469 die("$file doesn't exist\n") if (! -e $file);
470 die("$file is empty\n") if (-z $file);
471 my $fh = IO::File->new($file, "r") || die("Can't open $file: $!\n");
472  
473 # Call each constructor in turn until one returns an object
474 my $self;
475 foreach my $ctor (@Constructors)
476 {
477 if ($self = &$ctor($file, $fh))
478 {
479 $fh->close();
480 return($self);
481 }
482 $fh->seek(0, 0);
483 }
484 $fh->close();
485 die("Unrecognised file $file\n");
486 }
487  
488 ################################################################################
489 # PUBLIC
490  
491 sub define($;)
492 {
493 my ($self, %arg) = @_;
494  
495 # Sort out the required scale
496 $self->{plot_scale} = $arg{scale} || "normal";
497 delete($arg{scale});
498  
499 # Sort out the range of the plot
500 $self->{plot_start} = $arg{start} || $self->{start};
501 $self->{plot_finish} = $arg{finish} || $self->{finish};
502 die("Plot start time later than or equal to start time\n")
503 if ($self->{plot_start} >= $self->{plot_finish});
504 delete(@arg{qw(start finish)});
505  
506 # Check we are plottable
507 die("No data to plot\n") if (! defined($self->{data}));
508 die("No columns defined\n")
509 if (! (defined($self->{colindex}) && defined($self->{coltype})));
510  
511 # 2d data - expect a set of columns
512 if (! $self->{instance})
513 {
514 die("No columns to plot\n") if (! defined($arg{columns}));
515 $self->{plot_cols} = $arg{columns};
516 delete($arg{columns});
517 $self->{plot_insts} = undef;
518 }
519 # 3d data - expect 1 column and a set of instances
520 else
521 {
522 die("No column to plot\n") if (! defined($arg{column}));
523 die("No instances to plot\n") if (! @{$arg{instances}});
524 $self->{plot_cols} = $arg{column};
525 $self->{plot_insts} = $arg{instances};
526 delete(@arg{qw(column instances)});
527 }
528  
529 # Check there are no invalid arguments left
530 die("Invalid arguments " . join(", ", keys(%arg)) . "\n") if (keys(%arg));
531  
532 # Start gnuplot, if required
533 if (! $self->{gnuplot})
534 {
535 $self->{gnuplot} = IO::File->new("| exec gnuplot -title '" .
536 $self->get_title() . "' >/dev/null 2>&1")
537 # $self->get_title() . "'")
538 || die("Can't run gnuplot: $!\n");
539 $self->{gnuplot}->autoflush(1);
540 }
541 }
542  
543 ################################################################################
544 # PUBLIC
545  
546 sub plot($)
547 {
548 my ($self) = @_;
549 $self->{instance} ? $self->_3d_plot() : $self->_2d_plot();
550 }
551  
552 ################################################################################
553 # PUBLIC
554  
555 sub print($;)
556 {
557 my ($self, %arg) = @_;
558  
559 # Default args
560 $arg{orientation} ||= "landscape";
561 $arg{color} ||= "color";
562  
563 # Validate args
564 die("Illegal orientation $arg{orientation}\n")
565 if ($arg{orientation} ne "landscape" && $arg{orientation} ne "portrait");
566 die("Illegal color $arg{color}\n")
567 if ($arg{color} ne "monochrome" && $arg{color} ne "color");
568 die("No printer specified\n") if (! $arg{printer});
569 die("No printer type specified\n") if (! $arg{type});
570  
571 my $cmd = "set terminal ";
572 my $type = $arg{type};
573 CASE:
574 {
575 $type eq "postscript" and do
576 {
577 $cmd .= "postscript $arg{orientation} enhanced $arg{color} 10";
578 last CASE;
579 };
580 $type eq "laserjet ii" and do
581 {
582 $cmd .= "hpljii 300";
583 last CASE;
584 };
585 $type eq "laserjet iii" and do
586 {
587 $cmd .= "pcl5 $arg{orientation} univers 10";
588 last CASE;
589 };
590 # default
591 die("Unknown printer type $type\n");
592 last CASE;
593 }
594  
595 $self->{gnuplot}->print("$cmd\nset output '|$arg{printer}'\n");
596 $self->plot();
597 $self->{gnuplot}->print("set output\nset terminal x11\n");
598 }
599  
600 ################################################################################
601 # PUBLIC
602  
603 sub save($;)
604 {
605 my ($self, %arg) = @_;
606  
607 # Default args
608 $arg{orientation} ||= "landscape";
609 $arg{color} ||= "color";
610  
611 # Validate args
612 die("Illegal orientation $arg{orientation}\n")
613 if ($arg{orientation} ne "landscape" && $arg{orientation} ne "portrait");
614 die("Illegal color $arg{color}\n")
615 if ($arg{color} ne "monochrome" && $arg{color} ne "color");
616 die("No file specified\n") if (! $arg{file});
617 die("No format type specified\n") if (! $arg{format});
618  
619 if ($arg{format} eq 'csv')
620 {
621 $self->_save_csv($arg{file});
622 }
623 else
624 {
625 $self->_save_gnuplot($arg{file}, $arg{format},
626 $arg{orientation}, $arg{color});
627 }
628 }
629  
630 ################################################################################
631 # PUBLIC
632  
633 sub get_data_type($;$)
634 {
635 my $self = shift;
636 my $class = ref($self) || $self;
637 die("No get_data_type method defined for class $class\n");
638 }
639  
640 ################################################################################
641 # PUBLIC
642  
643 sub get_columns($)
644 {
645 my ($self) = @_;
646 return(sort({ $self->{colindex}{$a} <=> $self->{colindex}{$b} }
647 keys(%{$self->{colindex}})));
648 }
649  
650 ################################################################################
651 # PUBLIC
652  
653 sub get_instances($)
654 {
655 my ($self) = @_;
656 return() if (! $self->{instance});
657 return(sort(keys(%{$self->{instance}})));
658 }
659  
660 ################################################################################
661 # PUBLIC
662  
663 sub get_times($)
664 {
665 my ($self) = @_;
666 return(@{$self}{qw(start interval finish)});
667 }
668  
669 ################################################################################
670 # PUBLIC
671  
672 sub get_title($)
673 {
674 my ($self) = @_;
675 return($self->{title} . " " .
676 File::Basename::basename($self->{file}) . " " .
677 POSIX::strftime("%d/%m/%Y", localtime($self->{start})));
678 }
679  
680 ################################################################################
681 # PUBLIC
682  
683 sub get_categories($)
684 {
685 my ($self) = @_;
686 if (! defined($self->{category})) { return(); }
687 else { return(@{$self->{category}}); }
688 }
689  
690 ################################################################################
691 # PUBLIC
692  
693 sub get_file($)
694 {
695 my ($self) = @_;
696 return($self->{file});
697 }
698  
699 ################################################################################
700 1;
701 __END__