contrib/collection3: Set @INC at runtime, too.
[collectd.git] / contrib / collection3 / bin / index.cgi
1 #!/usr/bin/perl
2
3 # Copyright (C) 2008-2011  Florian Forster
4 # Copyright (C) 2011       noris network AG
5 #
6 # This program is free software; you can redistribute it and/or modify it under
7 # the terms of the GNU General Public License as published by the Free Software
8 # Foundation; only version 2 of the License is applicable.
9 #
10 # This program is distributed in the hope that it will be useful, but WITHOUT
11 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
12 # FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
13 # details.
14 #
15 # You should have received a copy of the GNU General Public License along with
16 # this program; if not, write to the Free Software Foundation, Inc.,
17 # 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18 #
19 # Authors:
20 #   Florian "octo" Forster <octo at collectd.org>
21
22 use strict;
23 use warnings;
24 use utf8;
25 use vars (qw($BASE_DIR));
26
27 BEGIN
28 {
29   if (defined $ENV{'SCRIPT_FILENAME'})
30   {
31     if ($ENV{'SCRIPT_FILENAME'} =~ m{^(/.+)/bin/[^/]+$})
32     {
33       $::BASE_DIR = $1;
34       unshift (@::INC, "$::BASE_DIR/lib");
35     }
36   }
37 }
38
39 use Carp (qw(cluck confess));
40 use CGI (':cgi');
41 use CGI::Carp ('fatalsToBrowser');
42 use HTML::Entities ('encode_entities');
43
44 use Data::Dumper;
45
46 use Collectd::Graph::Config (qw(gc_read_config gc_get_scalar));
47 use Collectd::Graph::TypeLoader (qw(tl_load_type));
48 use Collectd::Graph::Common (qw(get_files_from_directory get_all_hosts
49       get_timespan_selection get_selected_files get_host_selection
50       get_plugin_selection flush_files));
51 use Collectd::Graph::Type ();
52
53 our $TimeSpans =
54 {
55   Hour  =>        3600,
56   Day   =>       86400,
57   Week  =>   7 * 86400,
58   Month =>  31 * 86400,
59   Year  => 366 * 86400
60 };
61
62 my %Actions =
63 (
64   list_hosts => \&action_list_hosts,
65   show_selection => \&action_show_selection
66 );
67
68 sub base_dir
69 {
70   if (defined $::BASE_DIR)
71   {
72     return ($::BASE_DIR);
73   }
74
75   if (!defined ($ENV{'SCRIPT_FILENAME'}))
76   {
77     return;
78   }
79
80   if ($ENV{'SCRIPT_FILENAME'} =~ m{^(/.+)/bin/[^/]+$})
81   {
82     $::BASE_DIR = $1;
83     return ($::BASE_DIR);
84   }
85
86   return;
87 }
88
89 sub lib_dir
90 {
91   my $base = base_dir ();
92
93   if ($base)
94   {
95     return "$base/lib";
96   }
97   else
98   {
99     return "../lib";
100   }
101 }
102
103 sub sysconf_dir
104 {
105   my $base = base_dir ();
106
107   if ($base)
108   {
109     return "$base/etc";
110   }
111   else
112   {
113     return "../etc";
114   }
115 }
116
117 sub init
118 {
119   my $lib_dir = lib_dir ();
120   my $sysconf_dir = sysconf_dir ();
121
122   if (!grep { $lib_dir eq $_ } (@::INC))
123   {
124     unshift (@::INC, $lib_dir);
125   }
126
127   gc_read_config ("$sysconf_dir/collection.conf");
128 }
129
130 sub main
131 {
132   my $Debug = param ('debug') ? 1 : 0;
133   my $action = param ('action') || 'list_hosts';
134
135   if (!exists ($Actions{$action}))
136   {
137     print STDERR "No such action: $action\n";
138     return (1);
139   }
140
141   init ();
142
143   $Actions{$action}->();
144   return (1);
145 } # sub main
146
147 sub can_handle_xhtml
148 {
149   my %types = ();
150
151   if (!defined $ENV{'HTTP_ACCEPT'})
152   {
153     return;
154   }
155
156   for (split (',', $ENV{'HTTP_ACCEPT'}))
157   {
158     my $type = lc ($_);
159     my $q = 1.0;
160
161     if ($type =~ m#^([^;]+);q=([0-9\.]+)$#)
162     {
163       $type = $1;
164       $q = 0.0 + $2;
165     }
166     $types{$type} = $q;
167   }
168
169   if (!defined ($types{'application/xhtml+xml'}))
170   {
171     return;
172   }
173   elsif (!defined ($types{'text/html'}))
174   {
175     return (1);
176   }
177   elsif ($types{'application/xhtml+xml'} < $types{'text/html'})
178   {
179     return;
180   }
181   else
182   {
183     return (1);
184   }
185 } # can_handle_xhtml
186
187 my $html_started;
188 sub start_html
189 {
190   return if ($html_started);
191
192   my $end;
193   my $begin;
194   my $timespan;
195
196   $end = time ();
197   $timespan = get_timespan_selection ();
198   $begin = $end - $timespan;
199
200   if (can_handle_xhtml ())
201   {
202     print header (-Content_Type => 'application/xhtml+xml; charset=UTF-8');
203     print <<HTML;
204 <?xml version="1.0" encoding="UTF-8"?>
205 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
206     "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
207 <html xmlns="http://www.w3.org/1999/xhtml"
208     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
209     xsi:schemaLocation="http://www.w3.org/MarkUp/SCHEMA/xhtml11.xsd"
210     xml:lang="en">
211 HTML
212   }
213   else
214   {
215     print header (-Content_Type => 'text/html; charset=UTF-8');
216     print <<HTML;
217 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
218     "http://www.w3.org/TR/html4/strict.dtd">
219 <html>
220 HTML
221   }
222   print <<HTML;
223   <head>
224     <title>collection.cgi, Version 3</title>
225     <link rel="icon" href="../share/shortcut-icon.png" type="image/png" />
226     <link rel="stylesheet" href="../share/style.css" type="text/css" />
227     <script type="text/javascript" src="../share/navigate.js"></script>
228   </head>
229   <body onload="nav_init ($begin, $end);">
230 HTML
231   $html_started = 1;
232 }
233
234 sub end_html
235 {
236   print <<HTML;
237   </body>
238 </html>
239 HTML
240   $html_started = 0;
241 }
242
243 sub show_selector
244 {
245   my $timespan_selection = get_timespan_selection ();
246   my $host_selection = get_host_selection ();
247   my $plugin_selection = get_plugin_selection ();
248
249   print <<HTML;
250     <form action="${\script_name ()}" method="get">
251       <fieldset>
252         <legend>Data selection</legend>
253         <select name="hostname" multiple="multiple" size="15">
254 HTML
255   for (sort (keys %$host_selection))
256   {
257     my $host = encode_entities ($_);
258     my $selected = $host_selection->{$_}
259     ? ' selected="selected"'
260     : '';
261     print qq#          <option value="$host"$selected>$host</option>\n#;
262   }
263   print <<HTML;
264         </select>
265         <select name="plugin" multiple="multiple" size="15">
266 HTML
267   for (sort (keys %$plugin_selection))
268   {
269     my $plugin = encode_entities ($_);
270     my $selected = $plugin_selection->{$_}
271     ? ' selected="selected"'
272     : '';
273     print qq#          <option value="$plugin"$selected>$plugin</option>\n#;
274   }
275   print <<HTML;
276         </select>
277         <select name="timespan">
278 HTML
279   for (sort { $TimeSpans->{$a} <=> $TimeSpans->{$b} } (keys (%$TimeSpans)))
280   {
281     my $name = encode_entities ($_);
282     my $value = $TimeSpans->{$_};
283     my $selected = ($value == $timespan_selection)
284     ? ' selected="selected"'
285     : '';
286     print qq#          <option value="$value"$selected>$name</option>\n#;
287   }
288   print <<HTML;
289         </select>
290         <input type="hidden" name="action" value="show_selection" />
291         <input type="submit" name="ok_button" value="OK" />
292       </fieldset>
293     </form>
294 HTML
295 } # show_selector
296
297 sub action_list_hosts
298 {
299   start_html ();
300   show_selector ();
301
302   my @hosts = get_all_hosts ();
303   print "    <ul>\n";
304   for (sort @hosts)
305   {
306     my $url = encode_entities (script_name () . "?action=show_selection;hostname=$_");
307     my $name = encode_entities ($_);
308     print qq#      <li><a href="$url">$name</a></li>\n#;
309   }
310   print "    </ul>\n";
311
312   end_html ();
313 } # action_list_hosts
314
315 =head1 MODULE LOADING
316
317 This script makes use of the various B<Collectd::Graph::Type::*> modules. If a
318 file like C<foo.rrd> is encountered it tries to load the
319 B<Collectd::Graph::Type::Foo> module and, if that fails, falls back to the
320 B<Collectd::Graph::Type> base class.
321
322 If you want to create a specialized graph for a certain type, you have to
323 create a new module which inherits from the B<Collectd::Graph::Type> base
324 class. A description of provided (and used) methods can be found in the inline
325 documentation of the B<Collectd::Graph::Type> module.
326
327 There are other, more specialized, "abstract" classes that possibly better fit
328 your need. Unfortunately they are not yet documented.
329
330 =over 4
331
332 =item B<Collectd::Graph::Type::GenericStacked>
333
334 Specialized class that groups files by their plugin instance and stacks them on
335 top of each other. Example types that inherit from this class are
336 B<Collectd::Graph::Type::Cpu> and B<Collectd::Graph::Type::Memory>.
337
338 =item B<Collectd::Graph::Type::GenericIO>
339
340 Specialized class for input/output graphs. This class can only handle files
341 with exactly two data sources, input and output. Example types that inherit
342 from this class are B<Collectd::Graph::Type::DiskOctets> and
343 B<Collectd::Graph::Type::IfOctets>.
344
345 =back
346
347 =cut
348
349 sub action_show_selection
350 {
351   start_html ();
352   show_selector ();
353
354   my $all_files;
355   my $timespan;
356
357   my $types = {};
358
359   my $id_counter = 0;
360
361   $all_files = get_selected_files ();
362   $timespan = get_timespan_selection ();
363
364   if (param ('debug'))
365   {
366     print "<pre>", Data::Dumper->Dump ([$all_files], ['all_files']), "</pre>\n";
367   }
368
369   # Send FLUSH command to the daemon if necessary and possible.
370   flush_files ($all_files,
371       begin => time () - $timespan,
372       end => time (),
373       addr => gc_get_scalar ('UnixSockAddr', undef),
374       interval => gc_get_scalar ('Interval', 10));
375
376   for (@$all_files)
377   {
378     my $file = $_;
379     my $type = ucfirst (lc ($file->{'type'}));
380
381     $type =~ s/[^A-Za-z0-9_]//g;
382     $type =~ s/_([A-Za-z0-9])/\U$1\E/g;
383
384     if (!defined ($types->{$type}))
385     {
386       $types->{$type} = tl_load_type ($file->{'type'});
387       if (!$types->{$type})
388       {
389         warn ("tl_load_type (" . $file->{'type'} . ") failed");
390         next;
391       }
392     }
393
394     $types->{$type}->addFiles ($file);
395   }
396 #print STDOUT Data::Dumper->Dump ([$types], ['types']);
397
398   print qq#    <table>\n#;
399   for (sort (keys %$types))
400   {
401     my $type = $_;
402
403     if (!defined ($types->{$type}))
404     {
405       next;
406     }
407
408     my $graphs_num = $types->{$type}->getGraphsNum ();
409
410     for (my $i = 0; $i < $graphs_num; $i++)
411     {
412       my $args = $types->{$type}->getGraphArgs ($i);
413       my $url = encode_entities ("graph.cgi?$args;begin=-$timespan");
414       my $id = sprintf ("graph%04i", $id_counter++);
415
416       print "      <tr>\n";
417       print "        <td rowspan=\"$graphs_num\">$type</td>\n" if ($i == 0);
418       print <<EOF;
419         <td>
420           <div class="graph_canvas">
421             <div class="graph_float">
422               <img id="${id}" class="graph_image"
423                 alt="A graph"
424                 src="$url" />
425               <div class="controls zoom">
426                 <div title="Earlier"
427                   onclick="nav_move_earlier ('${id}');">&#x2190;</div>
428                 <div title="Zoom out"
429                   onclick="nav_zoom_out ('${id}');">-</div>
430                 <div title="Zoom in"
431                   onclick="nav_zoom_in ('${id}');">+</div>
432                 <div title="Later"
433                   onclick="nav_move_later ('${id}');">&#x2192;</div>
434               </div>
435               <div class="controls preset">
436                 <div title="Show current hour"
437                   onclick="nav_time_reset ('${id}', 3600);">H</div>
438                 <div title="Show current day"
439                   onclick="nav_time_reset ('${id}', 86400);">D</div>
440                 <div title="Show current week"
441                   onclick="nav_time_reset ('${id}', 7 * 86400);">W</div>
442                 <div title="Show current month"
443                   onclick="nav_time_reset ('${id}', 31 * 86400);">M</div>
444                 <div title="Show current year"
445                   onclick="nav_time_reset ('${id}', 366 * 86400);">Y</div>
446                 <div title="Set all images to this timespan"
447                   onclick="nav_set_reference ('${id}');">!</div>
448               </div>
449             </div>
450           </div>
451         </td>
452 EOF
453       # print qq#        <td><img src="$url" /></td>\n#;
454       print "      </tr>\n";
455     }
456   }
457
458   print "    </table>\n";
459   end_html ();
460 }
461
462 main ();
463
464 =head1 SEE ALSO
465
466 L<Collectd::Graph::Type>
467
468 =head1 AUTHOR AND LICENSE
469
470 Copyright (c) 2008 by Florian Forster
471 E<lt>octoE<nbsp>atE<nbsp>verplant.orgE<gt>. Licensed under the terms of the GNU
472 General Public License, VersionE<nbsp>2 (GPLv2).
473
474 =cut
475
476 # vim: set shiftwidth=2 softtabstop=2 tabstop=8 :