-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrrd.pl
executable file
·1804 lines (1606 loc) · 57.2 KB
/
rrd.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/perl -w
#
# rrd.cgi: The script for generating graphs for rrdtool statistics.
#
# Author: Haroon Rafique <[email protected]>
#
# Closely modelled after the script by Jan "Yenya" Kasprzak <[email protected]>
# mrtg-rrd.cgi available at: http://www.fi.muni.cz/~kas/mrtg-rrd/
# I did not like its limitations and tight coupling with MRTG
#
use strict;
use POSIX qw(strftime);
use Time::Local;
use Text::ParseWords;
use Date::Manip;
use CGI;
use LWP::UserAgent;
use HTTP::Request::Common qw(GET);
use File::Basename;
use File::Path;
use Image::Size qw(imgsize);
use List::Util qw(first);
use RRDs;
use vars qw(@config_files @all_config_files %targets $config_time
%directories $imagetype $percent_h);
use constant HTML_PREAMBLE => <<EOT;
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
EOT
use constant SCRIPT_VERSION => '<!-- $Id$ -->';
# EDIT THIS to reflect all your RRD config files
# Since this is in a BEGIN block, changes here require a restart in
# mod_perl to take effect
BEGIN { @config_files = qw(
/etc/rrd/rrd.cfg
/etc/rrd/rrd-mysql.cfg
/etc/rrd/rrd-tomcat.cfg
/etc/rrd/rrd-network.cfg
/etc/rrd/rrd-weather.cfg
/etc/rrd/rrd-sar.cfg
/etc/rrd/rrd-home.cfg
); }
# This depends on what image format your libgd (and rrdtool) uses
$imagetype = 'png'; # or make this 'gif';
# strftime(3) compatability test
$percent_h = '%-H';
$percent_h = '%H' if (strftime('%-H', gmtime(0)) !~ /^\d+$/);
sub main ($)
{
my ($q) = @_;
try_read_config($q->url());
my $mode = $q->param('mode');
defined $mode && do {
do_archive($q, $mode);
return;
};
my $path = $q->path_info();
$path =~ s/^\///;
$path =~ s/\/$//;
if (defined $directories{$path}) {
if ($q->path_info() =~ /\/$/) {
print_dir($path, $q);
} else {
print "Location: ", $q->url(-path_info=>1), "/\n\n";
}
return;
}
my ($dir, $stat, $ext) = ($q->path_info() =~
/^(.*)\/([^\/]+)(\.html|-(preview|hour|day|week|month|year)\.($imagetype|src))$/);
$dir && $dir =~ s/^\///;
$dir .= '/' if $dir;
print_error('Undefined statistic: ' . $q->path_info())
unless defined $stat and defined $targets{$dir . $stat};
print_error('Incorrect directory: ' . $q->path_info())
unless defined $targets{$dir . $stat}{directory} ||
$targets{$dir . $stat}{directory} eq $dir;
my $tgt = $targets{$dir . $stat};
common_args($dir . $stat, $tgt, $q);
my $start = $q->param('start');
my $end = $q->param('end');
if( defined $start || defined $end ) {
do_custom_image($tgt, $start, $end);
return;
}
if ($ext eq '.html') {
do_html($tgt, $q);
} elsif ($ext eq '-preview.' . $imagetype) {
do_image($tgt, 'preview', 0, 1);
} elsif ($ext eq '-hour.' . $imagetype) {
do_image($tgt, 'hour', 0, 1);
} elsif ($ext eq '-day.' . $imagetype) {
do_image($tgt, 'day', 0, 1);
} elsif ($ext eq '-week.' . $imagetype) {
do_image($tgt, 'week', 0, 1);
} elsif ($ext eq '-month.' . $imagetype) {
do_image($tgt, 'month', 0, 1);
} elsif ($ext eq '-year.' . $imagetype) {
do_image($tgt, 'year', 0, 1);
} elsif ($ext eq '-preview.src') {
do_image($tgt, 'preview', 1, 0);
} elsif ($ext eq '-hour.src') {
do_image($tgt, 'hour', 1, 0);
} elsif ($ext eq '-day.src') {
do_image($tgt, 'day', 1, 0);
} elsif ($ext eq '-week.src') {
do_image($tgt, 'week', 1, 0);
} elsif ($ext eq '-month.src') {
do_image($tgt, 'month', 1, 0);
} elsif ($ext eq '-year.src') {
do_image($tgt, 'year', 1, 0);
} else {
print_error('Unknown extension: ' . $ext);
}
}
sub do_html($$)
{
my ($tgt, $q) = @_;
my( undef, $xh, $yh ) = do_image($tgt, 'hour', 0, 0)
unless $tgt->{suppress} =~ /h/ or
$tgt->{config}{interval} ne '1';
my( undef, $xd, $yd ) = do_image($tgt, 'day', 0, 0);
my( undef, $xw, $yw ) = do_image($tgt, 'week', 0, 0);
my( undef, $xm, $ym ) = do_image($tgt, 'month', 0, 0);
my( undef, $xy, $yy ) = do_image($tgt, 'year', 0, 0);
http_headers('text/html', $tgt->{config});
print <<EOT;
@{[HTML_PREAMBLE]}
<head>
<link type="text/css" rel="stylesheet" href="$tgt->{config}{resourcedir}/style.css"/>
<title>
EOT
print $tgt->{title} if defined $tgt->{title};
print <<EOT;
</title>
</head>
<body>
<table border="0">
<tr align="left" valign="top">
<td>
EOT
my $mtime = undef;
if( !$tgt->{ignoretimestamps} ) {
$mtime = (stat $tgt->{rrd})[9];
print STDERR
'Could not get status info for ', $tgt->{rrd}, '. ',
'Missing symbolic link or incorrect permissions!', "\n"
unless defined $mtime;
$mtime ||= 0;
}
my $is_set_no_auto_refresh =
($q->param('autorefresh') and $q->param('autorefresh') eq 'no')
? 1 : 0;
my $is_set_no_preview =
($q->param('preview') and $q->param('preview') eq 'no')
? 1 : 0;
my $modified_href;
if( $is_set_no_auto_refresh or $is_set_no_preview ) {
if( $is_set_no_auto_refresh and $is_set_no_preview ) {
$modified_href = '?autorefresh=no&preview=no';
} elsif( $is_set_no_auto_refresh ) {
$modified_href = '?autorefresh=no';
} else {
$modified_href = '?preview=no';
}
} else {
$modified_href = '';
}
my $link_toggle_auto_refresh;
if( $is_set_no_auto_refresh and $is_set_no_preview ) {
# both autorefresh and preview say "no"
$link_toggle_auto_refresh =
'<a class="navlink" href="' .
$q->url(-absolute=>1,-path=>1) .
'?preview=no">Θ Enable Autorefresh</a>';
} elsif( $is_set_no_auto_refresh and !$is_set_no_preview ) {
# autorefresh says "no"
$link_toggle_auto_refresh =
'<a class="navlink" href="' .
$q->url(-absolute=>1,-path=>1) .
'">Θ Enable Autorefresh</a>';
} elsif( !$is_set_no_auto_refresh and $is_set_no_preview ) {
# preview says "no"
$link_toggle_auto_refresh =
'<a class="navlink" href="?autorefresh=no&preview=no">Φ Disable Autorefresh</a>';
} else {
# none of them say "no"
$link_toggle_auto_refresh =
'<a class="navlink" href="?autorefresh=no">Φ Disable Autorefresh</a>';
}
print <<EOT;
<div id="menu">
<h1 class="firstheading">Navigation</h1>
<a class="navlink"
href="./$modified_href">↑ Up to parent level (..)</a>
$link_toggle_auto_refresh
<div class="menuitem">
@{[ ($tgt->{suppress} =~ /h/ or $tgt->{config}{interval} ne '1') ? '' : '<a href="#Hourly">Hourly</a>|' ]}
@{[ $tgt->{suppress} =~ /d/ ? '' : '<a href="#Daily">Daily</a>|' ]}
@{[ $tgt->{suppress} =~ /w/ ? '' : '<a href="#Weekly">Weekly</a>|' ]}
@{[ $tgt->{suppress} =~ /m/ ? '' : '<a href="#Monthly">Monthly</a>|' ]}
@{[ $tgt->{suppress} =~ /y/ ? '' : '<a href="#Yearly">Yearly</a>|' ]}
<a href="#Historical">Historical</a>|
<a href="#Archived">Archived</a> Graphs
</div>
EOT
print <<EOT if defined $tgt->{pagetop};
<h1 class="subheading">Title</h1>
<div class="menuitem">$tgt->{pagetop}</div>
EOT
print <<EOT unless defined $tgt->{ignoretimestamps};
<h1 class="subheading">Timestamp</h1>
<div class="menuitem">
@{[ strftime("%A, %d %B, %H:%M:%S %Z", localtime($mtime)) ]}
EOT
print <<EOT;
</div>
</div>
</td>
<td style="padding-top: 50px;">
EOT
# total number of graphs (either 4 or 5)
my $total_graphs = $tgt->{config}{interval} ne '1' ? 4 : 5;
# How many are suppressed?
my( $suppressed_graphs ) =
$tgt->{config}{interval} ne '1' ?
$tgt->{suppress} =~ /([dwmy]+)/ :
$tgt->{suppress} =~ /([hdwmy]+)/;
$suppressed_graphs ||= "";
print '<div id="summary">';
print '<h1>Graphs: ', $total_graphs-length($suppressed_graphs), '</h1>';
$suppressed_graphs
and print '<p>Suppressed: ', length($suppressed_graphs), '</p>';
print '</div>';
my $dayavg = $tgt->{config}->{interval};
# print '<!--';
# use Data::Dumper;
# print Dumper(%targets);
# print '-->', "\n";
html_graph($tgt, 'hour', 'Hourly', $dayavg . ' Minute', $xh, $yh);
html_graph($tgt, 'day', 'Daily', '5 Minute', $xd, $yd);
html_graph($tgt, 'week', 'Weekly', '30 Minute', $xw, $yw);
html_graph($tgt, 'month', 'Monthly', '2 Hour', $xm, $ym);
html_graph($tgt, 'year', 'Yearly', '1 Day', $xy, $yy);
print <<EOT;
</td>
</tr>
</table>
<div>
<b><a name="Historical">Run-time Historical Graphs</a></b>
<small>(on-line generated and not cached - causes performance hit)</small>
EOT
if( $tgt->{suppress} !~ /h/ and $tgt->{config}{interval} eq '1' ) {
print '<br/>', "\nHours back: ";
foreach my $i (1..6) {
print '<a href="?start=', -$i, 'h">', $i, '</a>', "\n";
}
}
print ' | ', "\nDays back: ";
foreach my $i (1..7) {
print '<a href="?start=', -$i, 'd">', $i, '</a>', "\n";
}
print ' | ', "\nWeeks back: ";
foreach my $i (1..4) {
print '<a href="?start=', -$i, 'w">', $i, '</a>', "\n";
}
print ' | ', "\nMonths back: ";
foreach my $i (1..6) {
print '<a href="?start=', -$i, 'm">', $i, '</a>', "\n";
}
print <<EOT;
<form method="post" action="@{[ $q->url(-absolute=>1,-path=>1) ]}">
<div>
Arbitrary start and end dates:<br/>
Start Date: <input type="text" name="start" size="6" maxlength="40"/>
End Date: <input type="text" name="end" size="6" maxlength="40"/>
<input type="submit"/>
</div>
</form>
<div style="font-size: 80%"><dl>
<dt>Some examples of date specification for the above 2 inputs are:</dt>
<dd>today</dd>
<dd>1st thursday in June 1992</dd>
<dd>05/10/93</dd>
<dd>April 1, 2003</dd>
<dd>2 days ago</dd>
<dd>15 weeks ago</dd>
<dd>..., etc.</dd>
</dl>
</div>
EOT
print <<EOT;
<div id="footer">
<b><a name="Archived">Archived Graphs</a></b>
<small><i>(filesystem snapshots - no performance hit)</i></small>
<br/>
Modes:
<a href="?mode=daily">daily</a>,
<a href="?mode=monthly">monthly</a>,
<a href="?mode=yearly">yearly</a>.
<br/>
EOT
print <<EOT;
<a href="http://www.rrdtool.org/"><img
src="$tgt->{config}{resourcedir}/rrdtool-logo-light.png" width="121"
height="48" alt="RRDTool"/></a>
</div>
</div>
EOT
print <<EOT;
@{[ SCRIPT_VERSION ]}
</body>
</html>
EOT
}
sub html_graph($$$$$$)
{
my ($tgt, $ext, $freq, $period, $xsize, $ysize) = @_;
return unless defined $tgt->{$ext};
print <<EOT;
<br/><a name="$freq"><b>"$freq" Graph ($period Average)</b></a><br/>
<img src="$tgt->{url}-$ext.$imagetype"
width="$xsize" height="$ysize"
alt="$freq Graph"/><br/>
EOT
print <<EOT;
<div style="font-size: 85%;"><a href="$tgt->{url}-$ext.src">[source]</a></div>
EOT
}
sub fp_equal {
my ($X, $Y, $POINTS) = @_;
my ($tX, $tY);
$tX = sprintf("%.${POINTS}g", $X);
$tY = sprintf("%.${POINTS}g", $Y);
return $tX eq $tY;
}
sub http_headers($$)
{
my ($content_type, $cfg) = @_;
my $interval = $cfg->{interval};
$interval ||= 5;
my $refresh = $cfg->{refresh};
$refresh ||= 300;
print 'Content-Type: ', $content_type,
($content_type eq 'text/html' ? '; charset=utf-8' : ''),
"\n";
if( %$cfg ) {
# $cfg contains a reference to a non-empty hash
# pragma header
print 'Pragma: no-cache', "\n";
# Don't print refresh headers for graphics and
# when asked not to
my $autorefresh = defined $cfg->{autorefresh}
? $cfg->{autorefresh} : '';
print 'Refresh: ', $refresh, "\n"
if $content_type ne "image/$imagetype" and
$autorefresh ne 'no';
# Expires header calculation stolen from CGI.pm
print strftime("Expires: %a, %d %b %Y %H:%M:%S GMT\n",
gmtime(time+60*$interval));
}
print "\n";
}
sub do_image($$$$)
{
my ($target, $freq, $wantsrc, $wantimage) = @_;
my $file = $target->{$freq};
do {
print_error("Target '$freq' suppressed for this target") if $wantimage;
return;
} unless defined $file;
# Now the vertical rule at the end of the day
my @t = localtime(time);
# set seconds, minutes, hours to zero
$t[0] = $t[1] = $t[2] = 0 unless $freq eq 'hour';
my $seconds;
my $oldsec;
my $back;
my $xgrid = '';
if ($freq eq 'preview') {
$seconds = timelocal(@t);
$back = 10*3600; # 10 hours
$oldsec = $seconds - 1*864000;
} elsif ($freq eq 'hour') {
$seconds = timelocal(@t);
$back = 3*3600; # 3 hours
$oldsec = $seconds - $t[2]*3600 - $t[1]*60 - $t[0]; # FIXME: where to set the VRULE
$seconds = 0;
} elsif ($freq eq 'day') {
$seconds = timelocal(@t);
$back = 30*3600; # 30 hours
$oldsec = $seconds - 86400;
# We need this only for day graph. The other ones
# are magically correct.
$xgrid = 'HOUR:1:HOUR:6:HOUR:2:0:' . $percent_h;
} elsif ($freq eq 'week') {
$seconds = timelocal(@t);
$t[6] = ($t[6]+6) % 7;
$seconds -= $t[6]*86400;
$back = 8*86400; # 8 days
$oldsec = $seconds - 7*86400;
} elsif ($freq eq 'month') {
$t[3] = 1;
$seconds = timelocal(@t);
$back = 36*86400; # 36 days
$oldsec = $seconds - 30*86400; # FIXME (the right # of days!!)
} elsif ($freq eq 'year') {
$t[3] = 1;
$t[4] = 0;
$seconds = timelocal(@t);
$back = 396*86400; # 365 + 31 days
$oldsec = $seconds - 365*86400; # FIXME (the right # of days!!)
} else {
print_error("Unknown frequency: $freq");
}
my @local_args = ();
if ($xgrid) {
push @local_args, '-x', $xgrid;
}
my @graph_args = get_graph_args($target);
my @common_graph_args = @{$target->{args}};
if( $freq eq 'preview' ) {
use constant PREVIEW_TITLE_LENGTH => 47;
# shorten the title to first PREVIEW_TITLE_LENGTH characters
my $preview_title = substr $target->{title}, 0, PREVIEW_TITLE_LENGTH;
# replace last 3 characters with ellipses (only if getting cut off)
if (length $target->{title} > PREVIEW_TITLE_LENGTH) {
substr $preview_title, PREVIEW_TITLE_LENGTH-3, 3, '...';
}
# find index of first array element which is equal to -W (watermark)
my $watermark_index = first { $common_graph_args[$_] eq '-W' } 0..$#common_graph_args;
# weed out -W (watermark) and it's argument
if (defined $watermark_index) {
splice(@common_graph_args, $watermark_index, 2);
}
# overwrite values for -h, -w, -W and introduce step size with -S
push @graph_args,
'-h', 80,
'-w', 250,
'-t', $preview_title,
# make title, axis, unit and legend fonts smaller
'-n', 'TITLE:8',
'-n', 'AXIS:7',
'-n', 'UNIT:7',
'-n', 'LEGEND:7',
'-S', 300;
# weed out legend related printing
@graph_args = grep {!/^(GPRINT|COMMENT|PRINT)/i} @graph_args;
# args with LINE1 or AREA should have multiple spaces stripped
for( @graph_args ) {
if( m/^(LINE1|AREA)/ ) {
s/\s{2,}//g;
}
}
}
make_def_paths_absolute($target, \@graph_args);
do {
http_headers("text/html", $target->{config});
print <<EOT;
@{[HTML_PREAMBLE]}
<head><title>Source</title></head>
<body>
EOT
print '<pre>RRDs::graph(',
join(",\n",
$file, '-s', "-$back", @local_args,
@common_graph_args, @graph_args, "VRULE:$oldsec#ff0000",
"VRULE:$seconds#ff0000"),
')</pre></body></html>';
return;
} if $wantsrc;
my $dir_name = dirname($file);
if( !-d $dir_name ) {
eval { mkpath $dir_name };
if( $@ ) {
print_error("Could not create $dir_name: $@");
}
}
my( undef, $xsize, $ysize ) =
RRDs::graph($file, '-s', "-$back", @local_args,
@common_graph_args, @graph_args, "VRULE:$oldsec#ff0000",
"VRULE:$seconds#ff0000");
my $rrd_error = RRDs::error;
print_error("RRDs::graph failed, $rrd_error") if defined $rrd_error;
# on FreeBSD, RRDs::graph may return hugely wrong image size
( $xsize, $ysize ) = imgsize($file) if $xsize > 100000;
# Do not proceed unless image is wanted
return( undef, $xsize, $ysize ) unless $wantimage;
# Return the exact image straight from the file
open PNG, "<$file" or print_error("Can't open $file: $!");
binmode PNG;
http_headers("image/$imagetype", $target->{config});
my $buf;
# could be sendfile in Linux ;-)
while(sysread PNG, $buf, 8192) {
print $buf;
}
close PNG;
}
sub make_def_paths_absolute($$) {
my $target = shift; # target
my $array_ref = shift; # array reference to the graph arguments
# make relative paths into absolute paths for DEFs
for( @$array_ref ) {
if( m/^DEF/i ) {
# processing a line with DEF directive
# check to see if rrd path is absolute
my( $rrd_path ) = m#DEF:.*?=(/.*?):#g;
if( !defined $rrd_path ) {
# rrd path is relative
# replace relative path with absolute by prepending
# $target->{config}{logdir}/$target->{directory} to it
s#
(DEF:.*?=)(.*?):
#$1$target->{config}{logdir}/$target->{directory}/$2:#ix;
}
}
}
}
sub get_graph_args($) {
my $target = shift;
# Use space as a delimeter to break up {graph} into a list
# of words ignoring spaces inside quotes.
my @graph_args = ();
@graph_args =
# eliminate all quotes and replace backslash-space with space
map { s/"//og; s/\\ / /og; $_ }
# The 2nd parameter is true which signifies that quotes,
# backslashes, etc are kept in the return array
quotewords('\s+', 1, $target->{graph})
if defined $target->{graph};
return @graph_args;
}
# prints a custom image for a historical/non-standard time interval
sub do_custom_image($$$) {
my $target = shift;
my $start = shift;
my $end = shift;
my( $start_time, $end_time ) = ( undef, undef );
if( defined $start && defined $end ) {
my( $start_date ) = ParseDate($start);
my( $end_date ) = ParseDate($end);
print_error("start date \"$start\" is not a parseable date")
if $start_date eq '';
print_error("end date \"$end\" is not a parseable date")
if $end_date eq '';
$start_time = UnixDate($start_date, "%s");
$end_time = UnixDate($end_date, "%s");
print_error("start \"$start\" should be less than end \"$end\"")
if $start_time >= $end_time;
# have to fix the x-axis for day interval
push @{$target->{args}}, '-x', 'HOUR:1:HOUR:6:HOUR:2:0:' . $percent_h
if ($end_time-$start_time) <= 86400;
} elsif( defined $start ) {
my( $interval, $type ) = ($start =~ m/(\-\d+)([hdwm])/);
# regular -1d, -1m, -2w style start interval with no end
if( defined $interval && defined $type ) {
# work around a bug in time parsing code within rrdtool
# interprets -6m as -6 minutes instead of -6 months
$type = 'mon' if $type eq 'm';
# start time is just interval-1
$start_time = $interval-1 . $type;
# for hourly interval type just go back three hours
$start_time = $interval-3 . 'h' if $type eq 'h';
# end time is equal to interval
$end_time = $interval . $type;
# have to fix the x-axis for day interval
push @{$target->{args}}, '-x', 'HOUR:1:HOUR:6:HOUR:2:0:' . $percent_h
if $type eq 'd';
}
}
do {
print_error('Undefined start or end time');
return;
} unless defined $start_time && defined $end_time;
my @graph_args = get_graph_args($target);
make_def_paths_absolute($target, \@graph_args);
my( $fh, $filename );
if( $ENV{MOD_PERL} or defined $CGI::SpeedyCGI::i_am_speedy ) {
use File::Temp qw/ tempfile /;
( $fh, $filename )= tempfile( );
} else {
# unbuffered output
$| = 1;
$filename = '-';
}
http_headers("image/$imagetype", $target->{config});
RRDs::graph($filename,
'-s', $start_time,
'-e', $end_time,
@{$target->{args}}, @graph_args);
if( $ENV{MOD_PERL} or defined $CGI::SpeedyCGI::i_am_speedy ) {
binmode $fh;
my $buf;
while(sysread $fh, $buf, 8192) {
print $buf;
}
close $fh;
unlink $filename;
}
my $rrd_error = RRDs::error;
print_error("RRDs::graph failed, $rrd_error") if defined $rrd_error;
}
sub common_args($$$)
{
my ($name, $target, $q) = @_;
my $cfg = $target->{config};
my $autorefresh = $q->param('autorefresh') || '';
if( $autorefresh eq 'no' ) {
$cfg->{autorefresh} = 'no';
} else {
delete $cfg->{autorefresh};
}
return @{$target->{args}} if defined $target->{args} and @{$target->{args}};
$target->{name} = $name;
$target->{directory} = ''
unless defined $target->{directory};
$target->{url} = $q->url . '/' . $name;
my $dir = $cfg->{workdir};
$dir = $cfg->{logdir}
if defined $cfg->{logdir};
$target->{rrd} = $dir . '/' . $name . '.rrd';
$dir = $cfg->{workdir};
$dir = $cfg->{imagedir}
if defined $cfg->{imagedir};
$target->{suppress} ||= '';
$target->{preview} = $dir . '/' . $name
. '-preview.' . $imagetype unless $target->{suppress} =~ /p/;
$target->{hour} = $dir . '/' . $name
. '-hour.' . $imagetype unless
$target->{suppress} =~ /h/ or $cfg->{interval} ne '1';
$target->{day} = $dir . '/' . $name
. '-day.' . $imagetype unless $target->{suppress} =~ /d/;
$target->{week} = $dir . '/' . $name
. '-week.' . $imagetype unless $target->{suppress} =~ /w/;
$target->{month} = $dir . '/' . $name
. '-month.' . $imagetype unless $target->{suppress} =~ /m/;
$target->{year} = $dir . '/' . $name
. '-year.' . $imagetype unless $target->{suppress} =~ /y/;
if( $target->{config}{interval} eq '1' and $target->{suppress} !~ /h/ ) {
# change the refresh interval only if hourly is enabled
$target->{config}{refresh} = 60;
} elsif( $target->{config}{interval} ne '5' ) {
# custom interval
$target->{config}{refresh} = 60 * $target->{config}{interval};
}
my @args = ();
my $year = strftime "%Y", localtime;
push @args, '--lazy',
'-a', uc $imagetype,
'-h', '120',
'-w', '500',
'-W', '© Haroon Rafique 2003-' . $year . '. All rights reserved. Unauthorised use prohibited.';
@{$target->{args}} = @args;
@args;
}
# store/display images from/to archive
sub do_archive($$)
{
my $q = shift;
my $mode = shift;
do {
print_error(<<EOT);
<h3>Invalid mode '$mode'</h3>
Only
<a href="?mode=archive">archive</a>,
<a href="?mode=daily">daily</a>,
<a href="?mode=monthly">monthly</a>,
<a href="?mode=yearly">yearly</a> modes are supported.
EOT
} if $mode !~ m/^(archive|daily|monthly|yearly)$/o;
# check to see if archive mode being requested via the web
if( $mode eq 'archive' and $ENV{GATEWAY_INTERFACE} ) {
print_error(<<EOT);
<h2>Should be used offline only</h2>
Invoke from command line as:
<pre>rrd.cgi mode=archive</pre>
EOT
} elsif( $mode eq 'archive' ) {
archive_directory(undef, undef);
return;
}
my $date;
my( $m, $d, $y );
if( $q->param('date') ) {
$date = $q->param('date');
( $m, $d, $y ) = split /-/, $date;
unless( defined $m and defined $d and defined $y ) {
# initialize missing date parameters
if( $mode eq 'monthly' ) {
$y = $d;
# plug in 01 as the day
$d = '01';
}
if( $mode eq 'yearly' ) {
$y = $m;
# plug in 01 as the day, 01 as the month
$d = $m = '01';
}
}
unless( defined $m and defined $d and defined $y
and $m =~ /\d{2}/
and $d =~ /\d{2}/
and $y =~ /\d{4}/ ) {
print_error(<<EOT)
<h3>Invalid date >>>$date<<<<</h3>
<b>Date parameter must be in mm-dd-yyyy format</b>
EOT
}
} else {
# no date provided
if( $mode eq 'daily' ) {
# default to yesterday
( $m, $d, $y ) = UnixDate('yesterday', '%m', '%d', '%Y');
} elsif( $mode eq 'monthly' ) {
# default to 1 month ago
( $m, $d, $y ) = UnixDate('1 month ago', '%m', '%d', '%Y');
} elsif( $mode eq 'yearly' ) {
# default to 1 year ago
( $m, $d, $y ) = UnixDate('1 year ago', '%m', '%d', '%Y');
}
}
my $parse_date = ParseDate($m.'/'.$d.'/'.$y);
my $parse_time = UnixDate($parse_date, "%s");
unless( defined $parse_time and
$parse_time < UnixDate(ParseDate('today 12:00am'), "%s") ) {
print_error(<<EOT)
<h3>We're sorry. Archived snapshots for $m-$d-$y are not available</h3>
We only carry Archived snapshots uptil yesterday.
EOT
}
display_archived_images($q, $m, $d, $y);
}
sub display_archived_images($$$$) {
my $q = shift;
my $m = shift;
my $d = shift;
my $y = shift;
my $mode = $q->param('mode');
my ($dir, undef, $stat, $ext) = ($q->path_info() =~
m#^(.*)/(([^/]+)(\.html))?$#);
if( !defined $dir ) {
print_error('Undefined statistic ', $q->path_info(),
' for archive mode: ', $mode);
}
# now that $dir is verified immediately strip the leading slash
$dir =~ s/^\///;
unless( defined $directories{$dir}{config}{archiveurl} ) {
print_error('Missing Archiveurl for ', $dir,
' for archive mode: ', $mode);
}
my $archive_url = $directories{$dir}{config}{archiveurl};
my @targets = ();
my $title;
# if only $dir is defined it means user is requesting archived
# images for the whole directory. Otherwise, if all of $dir, $stat
# and $ext are defined, then the user is requesting a single
# archived image
if( !defined $stat or !defined $ext ) {
# multiple archived images
for my $target ( @{$directories{$dir}{target}} ) {
push @targets, $target;
}
$title = 'Images for ' . $dir;
} else {
# single archived image
push @targets, $dir . '/' . $stat;
$title = 'Image for ' . $dir . '/' . $stat;
}
for( $mode ) {
/daily/ && do { $title .= " daily mode for $m-$d-$y"; last; };
/monthly/ && do { $title .= " monthly mode for $m-$y"; last; };
/yearly/ && do { $title .= " yearly mode for $y"; last; };
}
my $resource_dir = $directories{$dir}{config}{resourcedir};
$resource_dir = find_resource_dir($dir) unless defined $resource_dir;
http_headers('text/html', undef);
print <<EOT;
@{[HTML_PREAMBLE]}
<head>
<link type="text/css" rel="stylesheet" href="$resource_dir/style.css"/>
<title>RRD: Archived $title</title>
<script type="text/javascript" src="$resource_dir/CalendarPopup.js">
</script>
</head><body>
<div>
EOT
generate_calendar($q, $mode, $m, $d, $y, $resource_dir);
print 'Switch mode to:';
for my $m ('daily', 'monthly', 'yearly') {
print $mode eq $m
?
' ' . $m
:
' [<a href="?mode=' . $m . '">' . $m . '</a>]';
}
print '<br/>';
for my $target ( @targets ) {
if(
exists $targets{$target}{suppress} and
($targets{$target}{suppress} =~ /d/ and $mode eq 'daily'
or
$targets{$target}{suppress} =~ /m/ and $mode eq 'monthly'
or
$targets{$target}{suppress} =~ /y/ and $mode eq 'yearly')
) {
# target is suppressed for this mode
print '<b>', $targets{$target}{title},
'</b> <br/> <span style="margin-left: 20px;">',
'<b>', $mode, '</b> archive mode is suppressed',
' (try another mode above)</span><br/>';
next;
}
my $image_file;
my $image_dir = $directories{$dir}{config}{archivedir} . '/' . $dir;
for( $mode ) {
/daily/ && do { $image_file = "$y/$m/$target-$y-$m-$d"; last; };
/monthly/ && do { $image_file = "$y/$target-$y-$m"; last; };
/yearly/ && do { $image_file = "$target-$y"; last; };
print_error('Undefined mode, ', $mode);
}
# strip directory name from the file
$image_file =~ s/$dir\/?//;
$image_file .= '.' . $imagetype;
unless( -f "$image_dir/$image_file" ) {
my $current_month_year = strftime "%m-%Y", localtime;
my( $cur_m, $cur_y ) = split /-/, $current_month_year;
my $error_date = $mode eq 'daily' ?
"$m-$d-$y" : $mode eq 'monthly' ?
"$m-$y" : $y;
# archived image does not exist for this mode
# perhaps archival of images was started after that date
print '<b>', $targets{$target}{title},
'</b> does not have a <b>', $mode,
'</b> archived image for <b>',
$error_date, '</b>.<br/>';
if( $mode eq 'monthly' and $cur_y <= $y and $cur_m <= $m ) {
my $avail_month = sprintf("%02d", $m+1);
my $avail_year = $y;
# be careful when incrementing months beyond 12
if( $m eq '12' ) {
$avail_month = '01';
$avail_year = $y+1;
}
print 'It will become available on <b>',
$avail_month, '-01-', $avail_year,
'</b>.<br/>', "\n";
}
if( $mode eq 'yearly' and $cur_y <= $y ) {
print 'It will become available on <b>',
'01-01-', $y+1,
'</b>.<br/>', "\n";
}
next;
}
print <<EOT;
<b>$targets{$target}{title}</b>
<br/>
<img src="$archive_url/$dir/$image_file"/>
<br/>
EOT
}
print <<EOT;
</div>
@{[ SCRIPT_VERSION ]}
</body>
</html>
EOT
}
# generate code for JavaScript calendar
# remember that, in JavaScript, the 2nd argument to
# Date($y,@{[$m-1]},$d) needs to have 1 subtracted from it as the
# JavaScript months go from 0 to 11
sub generate_calendar($$$$$$) {
my $q = shift;
my $mode = shift;
my $m = shift;
my $d = shift;
my $y = shift;
my $resource_dir = shift;