palate 0.3.8

File type detection combining tft and hyperpolyglot
Documentation
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
#!/usr/bin/perl

# v1.0
# nagiostat, program to insert performance-data from Nagios into RRD-archives
# Copyright (C) 2004  Carl Bingel / Svensk IT konsult AB
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

use strict;

## Basic configuration options
my $BASE_DIR = "/usr/share/nagiostat";
my $CONFIG_FILE = "/etc/nagios/nagiostat.conf";  ## Config-file location
my $DEBUG_LOG_FILE = "/var/spool/nagiostat/debug.log";    ## Specify where to create log-file and what filename (must be writable by nagios-user!)
my $DEBUGLEVEL = 1;              ## 0=Nothing, 1=Errors, 2=Warnings, 3=Debug
my $DEBUGOUTPUT = 0;		 ## 0=file, 1=STDERR, 2=STDOUT (for cgi)

require 'shellwords.pl';

## Global vars
my $DEBUG_TIMESTAMP=0;

## Find out how program is run
if( $ARGV[0] eq "-t") {		## -t = test configuration-file
  print STDERR "nagiostat: Testing configuration-file..\n";
  $DEBUGLEVEL=3;
  $DEBUGOUTPUT=1;    ## output errors to console and not file
  my $c = &read_config();
  abort();
} elsif( $ARGV[0] eq "-p") {	## -p = parse performance-data (when started by nagios)
  &parse_perfdata();
} else {
  if( exists $ENV{'GATEWAY_INTERFACE'}) {	## we are run as a CGI-script!
    $DEBUGOUTPUT=2;  ## output errors to web-browser
    &run_as_cgi();
  } else {                                ## print some help-info
    print STDERR "nagiostat: usage:
        -t	Test configuration-file
        -p	Parse/import performance-data (used when called from nagios)
";
  }
}

abort();

sub abort {
   ## logfile: write blank if we wrote anything...
   if( $DEBUG_TIMESTAMP!=0) {
     debug( 1, "");	
   }
   exit;
}

##
##  Program is called as CGI
##
sub run_as_cgi {
   use CGI;
   my $cgi = new CGI;
   
   my $graph_name = $cgi->param( "graph_name");
   my $graph_iteration = $cgi->param( "graph_iteration");

   if( $graph_iteration eq "") {
      print "Content-type: text/html\nExpires: 0\n\n";
   } else {
      print "Content-type: image/gif\nExpires: 0\n\n";
   }

   my $config = read_config();

   if( $graph_name eq "") {      
      ##
      ## display index of graphs
      ##
      display_htmltemplate( $config->{'htmltemplatepath'}."/".$config->{'graphindextemplate'}, $graph_name, $config);
   } else {                      ## display graph
      if( ! exists $config->{'graphs'}->{$graph_name}) {
         debug( 1, "ERROR: Graph '$graph_name' does not exist!");
         exit;
      } elsif( $graph_iteration eq "") {
         ##
         ## Display HTML-page with all the graphs
         ##
         if( ! -r $config->{'htmltemplatepath'}."/".$config->{'graphs'}->{$graph_name}->{'htmltemplate'}) {
            debug( 1, "ERROR: HTML-template '".($config->{'htmltemplatepath'}."/".$config->{'graphs'}->{$graph_name}->{'htmltemplate'})."' is not readable by effective userid!");
            exit;
         }
         display_htmltemplate( $config->{'htmltemplatepath'}."/".$config->{'graphs'}->{$graph_name}->{'htmltemplate'}, $graph_name, $config);
      } else {                   
         ##
         ## generate graph (call 'rrdtool graph')
         ##
         my $rrdtool_cmdline = $config->{'rrdtoolpath'}." graph - ".join( " ", @{$config->{'plottemplates'}->{ $config->{'graphs'}->{$graph_name}->{'plottemplate'} } }); 
         
         ## expand variables
         my $rrdarchive = $config->{'rrdarchivepath'}."/".$config->{'graphs'}->{$graph_name}->{'rrdfilename'};
         $rrdtool_cmdline =~ s/\$f/$rrdarchive/g;
         my $t_start = $config->{'graphtimetemplates'}->{ $config->{'graphs'}->{$graph_name}->{'graphtimetemplate'} }->[$graph_iteration]->{'starttime'};
         $rrdtool_cmdline =~ s/\$s/$t_start/g;
         my $t_end = $config->{'graphtimetemplates'}->{ $config->{'graphs'}->{$graph_name}->{'graphtimetemplate'} }->[$graph_iteration]->{'endtime'};
         $rrdtool_cmdline =~ s/\$e/$t_end/g;
         my $t_descr = $config->{'graphtimetemplates'}->{ $config->{'graphs'}->{$graph_name}->{'graphtimetemplate'} }->[$graph_iteration]->{'description'};
         $rrdtool_cmdline =~ s/\$d/$t_descr/g;

         ## Call rrdtool (should probably be fixed to call it in a better way, like exec)
         print `$rrdtool_cmdline`;
      }

   }

}

## Display HTML template (and do variable-substitution and other stuff)
##
sub display_htmltemplate {
   my( $filename, $graph_name, $config) = @_;

   if( -r $filename) {
      open( HTML, $filename);
      while( <HTML>) {
         ## All is a big regex.. :-)
         s/\$(\w+)/my $t=sub {   
            my $varname = $_[0];
            if( $varname eq "GRAPHNAME") {                           ## return the name of the graph
               if( $config->{'graphs'}->{$graph_name}->{'title'} ne "") {
                  return( $config->{'graphs'}->{$graph_name}->{'title'});
               } else {
                  return( "Graph ".$graph_name);
               }
            } elsif( $varname eq "CURRENTTIME") {                    ## return current date-time
               return( localtime());
            } elsif( $varname eq "GRAPHINDEX" || $varname eq "GRAPHINDEX_ONEROW") {    ## return HTML-code for index of the different graphs
               my $return_html;
               foreach my $gn ( sort keys %{$config->{'graphs'}}) {           
                     $return_html.=(($varname eq "GRAPHINDEX")?"<LI>":"").
                     "<A HREF=\"?graph_name=$gn\">".($config->{'graphs'}->{$gn}->{'title'})."<\/A>".                  # must escape slash since were inside an regex!
                     (($varname eq "GRAPHINDEX_ONEROW")?"&nbsp;&nbsp;":"");
               }
               return( $return_html);
            } elsif( $varname eq "GRAPH_AUTOGENERATE") {             ## return HTML-code for displaying the actual graph-images
               my $iteration_id=0;
               my $return_html;
               foreach my $time ( @{ $config->{'graphtimetemplates'}->{ $config->{'graphs'}->{$graph_name}->{'graphtimetemplate'} } }) {
                 $return_html.="<P>".($time->{'description'})."<BR><IMG SRC=\"?graph_name=$graph_name&graph_iteration=$iteration_id\">"; 
                 $iteration_id++;
               }
               return( $return_html);
            } else {                                                 ## unknown variable
               return( "##UNKNOWN-VARIABLE##");
            }
         }; &$t($1)/eig;   ## i thought that regex would never end!
         print;
      }
      close( HTML);
   } else {
      print "ERROR: HTML-template '$filename' does not exist or is not readable by effective userid.";
   }

}

##
##  Process incoming performance-data (parse output from check-plugin and insert values into rrd-archives)
##
sub parse_perfdata {

  $DEBUG_TIMESTAMP=0;
  
  my $config = read_config();

  my $rrd_updates;

  ##  Provide more symbolic names (same names as the macros in nagios configuration-file)

  my( $LASTCHECK, $HOSTNAME, $SERVICEDESCR, $SERVICESTATE, $OUTPUT, $PERFDATA) = split( /\|!!\|/, $ARGV[1]);
  debug( 3, "**INCOMING PERFDATA:\n  LASTCHECK=$LASTCHECK\n  HOSTNAME=$HOSTNAME\n  SERVICEDESCR=\"$SERVICEDESCR\"\n  SERVICESTATE=\"$SERVICESTATE\"\n  OUTPUT=\"$OUTPUT\"\n  PERFDATA=\"$PERFDATA\"");
  
  my $host_and_descr_found;
  ## Loop through all host_regexes
  foreach my $host_regex ( keys %{$config->{'regexes'}}) {
    ## Loop through all service_description_regexes
    foreach my $service_regex ( keys %{$config->{'regexes'}->{$host_regex}}) {
      if( ($HOSTNAME =~ m/$host_regex/i) && ($SERVICEDESCR =~ m/$service_regex/i) ) {     ## match!
        $host_and_descr_found=1;
        ## Loop through all InsertValue-lines with same host and service_description match
        foreach my $insert_value ( @{$config->{'regexes'}->{$host_regex}->{$service_regex}} ) {
          ## Loop through all regexes that should match values in the output/perfdata
          foreach my $regex ( @{ $config->{'valueregextemplates'}->{$insert_value->{'regextemplate'}} }) {
             my $regex_string = $regex->{'regex'};
             if( $regex->{'regex_what'} eq "output") {         ## do regex on "output"
                if( $OUTPUT =~ m/$regex_string/) {
                   debug( 3, " +VALUE: ".$1);
                   push( @{$rrd_updates->{$insert_value->{'rrdarchive'}}->{'value'}}, $1);
                   push( @{$rrd_updates->{$insert_value->{'rrdarchive'}}->{'dsaname'}}, $regex->{'dsaname'});
                   $rrd_updates->{$insert_value->{'rrdarchive'}}->{'rrdcreatetemplate'} = $insert_value->{'rrdcreatetemplate'};  #$config->{'regexes'}->{$host_regex}->{$service_regex}->[0]->{'rrdcreatetemplate'};
                } else {
                   debug( 2, "**WARNING: No match for value with regex on output '$regex_string'.");
                }
             } else {                                          ## do regex on "perfdata"
                if( $PERFDATA =~ m/$regex_string/) {
                   debug( 3, " +VALUE: ".$1);
                   push( @{$rrd_updates->{$insert_value->{'rrdarchive'}}->{'value'}}, $1);
                   push( @{$rrd_updates->{$insert_value->{'rrdarchive'}}->{'dsaname'}}, $regex->{'dsaname'});
                   $rrd_updates->{$insert_value->{'rrdarchive'}}->{'rrdcreatetemplate'} = $insert_value->{'rrdcreatetemplate'};  #$config->{'regexes'}->{$host_regex}->{$service_regex}->[0]->{'rrdcreatetemplate'};
                } else {
                   debug( 2, "**WARNING: No match for value with regex on perfdata '$regex_string'.");
                }
             }
          }
        }
        
      }
    }
  }
  
  if( !$host_and_descr_found) {
    debug( 2, "**WARNING: Hostname and description didn't match any of the regexes in the config-file.");
  } else {
    ##
    ## Insert the value into the RRD by calling the rrdtool (may be several rrd-archives)
    ##
    foreach my $archive ( keys %{$rrd_updates}) {
      debug( 3, " =INSERT into '$archive': ".join( ",", @{$rrd_updates->{$archive}->{'value'}} )." DSA-names=".join( ",", @{$rrd_updates->{$archive}->{'dsaname'}}) );
      
      my $rrdarchive_filename = $config->{'rrdarchivepath'}."/".$archive;
      
      ## Create RRD-Archive (according to template) if it does not exist
      if( ! -e $rrdarchive_filename) {
         my $rrdtool_cmdline = $config->{'rrdtoolpath'}." create ".$rrdarchive_filename." ".(join( " ", @{$config->{'rrdcreatetemplates'}->{$rrd_updates->{$archive}->{'rrdcreatetemplate'}}}));
         debug( 2, "**CREATING: $rrdarchive_filename, cmdline='".$rrdtool_cmdline."'.");
         `$rrdtool_cmdline`;
      }

      ## Check if rrd-archive is writable
      if( ! -w $rrdarchive_filename) {					## check wheter RRD-archive exists
        debug( 1, "!!ERROR: RRD-archive '".$rrdarchive_filename."' does not exist or is not writable by effective UID."); abort();
      }

      ## Assemle command-line for rrdtool
      my $rrdtool_cmdline = $config->{'rrdtoolpath'}." update ".$rrdarchive_filename.
	                    " --template ".join( ":", @{$rrd_updates->{$archive}->{'dsaname'}}).
                            " $LASTCHECK:".join( ":", @{$rrd_updates->{$archive}->{'value'}});
      debug( 3, " !RRDCMDLINE: ".$rrdtool_cmdline);
      my $result = `$rrdtool_cmdline`;
      if( $result ne "") {
        debug( 1, "!!RESULT: $result");
      }
    }
  }

}




##
##  Read config-file and check for errors
##
sub read_config {
  my $config;
  open( CONFIG, $CONFIG_FILE);
  my( $line_counter);
  while( <CONFIG>) {
    $line_counter++;
    chomp;
    my( @args) = &shellwords( $_);
    my $orig_confline = $_;
    $args[0] = uc( $args[0]);
  
    if( $args[0] eq "INSERTVALUE") {	##  INSERTVALUE-command
      shift @args;
      my( $rrd_filename, $rrdcreatetemplate, $hostname_regex, $servicedescr_regex, $regex_template) = @args;

      if( ! exists $config->{'rrdcreatetemplates'}->{$rrdcreatetemplate}) {
         debug( 1, "!!ERROR: RRDCreateTemplate '$rrdcreatetemplate' is not defined but refered to in line $line_counter."); abort();
      }
      if( $hostname_regex !~ m/^\/(.*)\/$/) {			## verify hostname regex
        debug( 1, "!!ERROR: Hostname regex should be enclosed in slashes, i.e. /HOSTNAME/ and optionally enclosed in quotes if needed. Conf-line $line_counter."); abort();
      } else {
        $hostname_regex = $1;
      }
      if( $servicedescr_regex !~ m/^\/(.*)\/$/) {			## verify service description regex
        debug( 1, "!!ERROR: Service-description regex should be enclosed in slashes, i.e. /SERVICEDESCR/ and optionally enclosed in quotes if needed. Config-line $line_counter.");
        abort();
      } else {
        $servicedescr_regex = $1;
      }
      if( ! exists $config->{'valueregextemplates'}->{$regex_template}) {  ## verify value-regex-template exists
         debug( 1, "!!ERROR: VALUEREGEXTEMPLATE '$regex_template' is not defined on line $line_counter."); abort();
      }
      push( @{$config->{'regexes'}->{$hostname_regex}->{$servicedescr_regex}}, {
            'rrdarchive' => $rrd_filename,
            'rrdcreatetemplate' => $rrdcreatetemplate,
            'regextemplate' => $regex_template
            } );
    } elsif( $args[0] =~ m/^(\s*)#/ || $args[0] eq "") {	## comment or blank row
      ## do nuthin
    } elsif( $args[0] eq "RRDTOOLPATH") {               ## RRDToolPath args: path
      $config->{'rrdtoolpath'} = $args[1];
    } elsif( $args[0] eq "PLOTTEMPLATE") {		## PlotTemplate args: name,htmltemplate,parameters..
      shift @args;
      my( $name, @params) = @args;
      if( $name eq "") {
        debug( 1, "!!ERROR: PLOTTEMPLATE-name must be specified on line $line_counter."); abort();
      }
      if( exists $config->{'plottemplates'}->{$name}) {
        debug( 1, "!!ERROR: PLOTTTEMPLATE-names must be uniqe. Duplicate name found on line: $line_counter."); abort();
      }
      $config->{'plottemplates'}->{$name} = [ @params];
    } elsif( $args[0] eq "GRAPHTIMETEMPLATE") {         ## GraphTimeTemplate args: name,parameters..
      shift @args;
      my( $name, @params) = @args;
      if( $name eq "") {
        debug( 1, "!!ERROR: GRAPHTIMETEMPLATE-name must be specified on line $line_counter."); abort();
      }
      if( exists $config->{'graphtimetemplates'}->{$name}) {
        debug( 1, "!!ERROR: GRAPHTIMETEMPLATE-names must be uniqe. Duplicate name found on line: $line_counter."); abort();
      }
      foreach my $time_template (@params) {
         my( $t_start, $t_end, @t_descr) = split( /:/, $time_template);
         my $t_descr = join( ":", @t_descr);    # workaround if ':' is used in description-string
         if( $t_start eq "" || $t_end eq "") {
            debug( 1, "!!ERROR: GRAPHTIMETEMPLATE, each time-definition should be defined as '<starttime>:<endtime>:<description>' on line $line_counter.");
         }
         push( @{$config->{'graphtimetemplates'}->{$name}}, {
             'starttime' => $t_start,
             'endtime' => $t_end,
             'description' => $t_descr
         });
      }
    } elsif( $args[0] eq "RRDCREATETEMPLATE") {         ## RRDCreateTemplate
      shift @args;
      my( $name, @params) = @args;
      if( $name eq "") {
        debug( 1, "!!ERROR: RRDCREATETEMPLATE-name must be specified on line $line_counter."); abort();
      }
      if( exists $config->{'rrdcreatetemplates'}->{$name}) {
        debug( 1, "!!ERROR: RRDCREATETEMPLATE-names must be uniq. Duplicate name found on line: $line_counter."); abort();
      }
      $config->{'rrdcreatetemplates'}->{$name} = [ @params];
    } elsif( $args[0] eq "VALUEREGEXTEMPLATE") {        ## ValueRegexTemplate
      shift @args;
      my( $template_name, @regexes) = @args;
      if( $template_name eq "") {
         debug( 1, "!!ERROR: VALUEREGEXTEMPLATE-name must be specified on line $line_counter."); abort();
      }
      foreach my $r (@regexes) {
         if( $r !~ m/^(output|perfdata):(\w+):\/(.*)\/$/) {
           debug( 1, "!!ERROR: Value-regex should be formatted as 'output:dsaname:/regex/' or 'perfdata:dsaname:/regex/' depending on in which field to extract the data. The value should be within parantheses in the regex. Config-line $line_counter.");
           abort();
         } else {
           my( $regex_what, $dsa_name, $regex) = ( $1, $2, $3);
           push( @{$config->{'valueregextemplates'}->{$template_name}}, { 
                   'regex_what' => $regex_what, 
                   'regex' => $regex, 
                   'dsaname' => $dsa_name
                  } );
         }
      }
    } elsif( $args[0] eq "RRDARCHIVEPATH") {            ## RRDARCHIVEPATH
      $config->{'rrdarchivepath'} = $args[1];
    } elsif( $args[0] eq "HTMLTEMPLATEPATH") {          ## HTMLTemplatePath
      $config->{'htmltemplatepath'} = $args[1];
    } elsif( $args[0] eq "GRAPHINDEXTEMPLATE") {        ## GraphIndexTemplate
      $config->{'graphindextemplate'} = $args[1];
    } elsif( $args[0] eq "GRAPH") {			## GRAPH args: name,rrdfilename,rrdcreatetemplate,graphtimetemplate,plottemplate,htmltemplate
      if( $args[1] eq "") {
	debug( 1, "!!ERROR: GRAPH-name must be specified on line $line_counter."); abort();
      }
      if( ! exists $config->{'graphtimetemplates'}->{$args[3]}) {
        debug( 1, "!!ERROR: Unknown GRAPHTIMETEMPLATE on line $line_counter."); abort();
      }
      if( ! exists $config->{'plottemplates'}->{$args[4]}) {
        debug( 1, "!!ERROR: Unknown PLOTTEMPLATE on line $line_counter."); abort();
      }
      if( exists $config->{'graphs'}->{$args[1]}) {
        debug( 1, "!!ERROR: Graphnames must be uniqe. Duplicate name found on line: $line_counter.");
        abort();
      } else {
        $config->{'graphs'}->{$args[1]} = {
		'graphname' => $args[1],
		'rrdfilename' => $args[2],
                'graphtimetemplate' => $args[3],
                'plottemplate' => $args[4],
                'htmltemplate' => $args[5],
                'title' => $args[6]
        };
      }
    } else {
      debug( 1, "!!ERROR: Unknown config-file directive on line $line_counter: '".$args[0]."'");
    }
  }
  close( CONFIG);

  if( ! -x $config->{'rrdtoolpath'}) {
    debug( 1, "!!ERROR: RRDTOOLPATH does not point to executable rrdtool-binary.");
    abort();
  }
  if( ! -x $config->{'rrdarchivepath'}) {
     debug( 1, "!!ERROR: RRDARCHIVEPATH, '".($config->{'rrdarchivepath'})."' is not readable by effective userid."); abort();
  }
  if( ! -x $config->{'htmltemplatepath'}) {
     debug( 1, "!!ERROR: HTMLTEMPLATEPATH, '".($config->{'htmltemplatepath'})."' is not readable by effective userid."); abort();
  }

  return( $config);
}


## 
##  Write debug-output/logging
##
sub debug {
  my( $level, $msg) = @_;
  if( $DEBUGLEVEL >= $level) {

    ## write timestamp
    if( !$DEBUG_TIMESTAMP) {	
      $DEBUG_TIMESTAMP=1;
      debug( 1, scalar localtime());
    }

    ## write to file or STDERR
    if( $DEBUGOUTPUT == 0) {
      open( DEBUGOUTPUT, ">>".$DEBUG_LOG_FILE);
      print DEBUGOUTPUT $msg."\n";
      close( DEBUGOUTPUT);
    } elsif( $DEBUGOUTPUT == 2) {
      print "<BR><PRE>$msg</PRE>";
    } else {
      print STDERR $msg."\n";
    }

  }
}