Logo Search packages:      
Sourcecode: nagat version File versions  Download package

plugin_default.inc

<?php
# $Id: plugin_default.inc,v 1.12 2002/06/28 10:05:19 kemuri Exp $

/*
 * Copyright (c) 2002 Ypsilon.Net AG, Germany
 *
 * This file is part of Nagat.
 * 
 * Nagat 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.
 * 
 * Nagat 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 Nagat; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */

require_once("local.inc");

/*
 * Nagat default plugin
 *
 * Author   : Geert Vanderkelen <geert@kemuri.org>
 *
 * Description    : Default plugin for saving Nagat data and exporting it to and
 *            and importing from Nagios.
 *
 *            This plugin uses the 'serialize' functionallity from PHP to
 *            store some hashes in files. PHP doesn't need an special
 *            stuff compiled into it to let this work.
 *
 *            Nagat storage:
 *            NGT_CFGLOG in local.inc should be a directory. In most cases
 *            this will be the Nagios /etc directory. It must be writeable
 *            for the user running the webserver.
 *
 *            Importing form Nagios:
 *            This plugin reads template-based configurations files as
 *            found in Nagios. It those not support the old Netsaint
 *            style.
 *
 *            Exporting to Nagios:
 *            Nagios configuration is written in the new template-based
 *            form. Old Netsaint style is not supported.
 */

/*
 * 
 * Information for PluginCfg writers:
 * 
 * This file is the default Nagat method for reading, manipulating and saving 
 * nagios configuration. It contains information how to build other methods,
 * like saving to a database.
 * 
 * Functions starting with 'Plugin..' are required and used by Nagat. Those 
 * starting with 'Privat..' are only used within the plugin as helper
 * funtions. I suggest you stick to these to prefixes.
 *
 * NGT_CFGLOC is an important constant set in the local.inc file. It contains
 * the location where the information is stored (not Nagios files). It can be
 * a directory (like in this default plugin) or a string specifying some login
 * information for a database like MySQL, PostgreSQL, et al.
 *
 * (More docs comming)
 *
 */


function PrivatPluginGetSerialData($file) 
{
      if( file_exists($file) ) {
            $fp = fopen($file,"r");
            $serstr = fread($fp,filesize($file));
            fclose($fp);
            
            $data = @unserialize($serstr);
            
            if( is_array($data) ) {
                  return( $data );
            }
      } 

      return(NULL);
}

function PrivatPluginDumpObjects($filename,$objects)
{
      $result = FALSE;

      if( is_array($objects) ) {
            $fp = fopen($filename, "w");
            fwrite($fp, serialize($objects));
            fclose($fp);
            $result = TRUE;
      }
      sleep(1);

      return($result);
}

function PluginGetConfig($fileid = NULL)
{
      static $config = NULL;

      $filename = NGT_CFGLOC."nagatcfg.dat";

      if( $config == NULL ) {
            $config = PrivatPluginGetSerialData($filename);
      }

      if( is_array($config) ) {
            if( $fileid != NULL && is_array($config[$fileid]))
                  return( $config[$fileid] );
            else
                  return( $config );
      }

      return( NULL );
}

function PluginGetObjects($type = NULL) 
{

      $objects = PrivatPluginGetSerialData(NGT_CFGLOC."nagatobjs.dat");

      # Return asked objects
      if( is_array($objects) ) {
            if( $type != NULL && @is_array($objects[$type]))
                  return( $objects[$type] );
            else
                  return($objects);
      }
      
      return(NULL);
}

function PluginGetObjectsByField($field, $value, $type = NULL) 
{
      $selobjs = array();
      $objects = PrivatPluginGetSerialData(NGT_CFGLOC."nagatobjs.dat");

      # Get asked objects
      if( is_array($objects) ) {
            foreach( $objects as $key => $obj ) {
                  if( $obj[$field] == $value ) {
                        $selobjs[$key] = $obj;
                  }
            }
      }

      if( count($selobjs) > 0 ) {
            return( $selobjs );
      }

      return( NULL );
}

function PluginGetObject($key,$type) 
{

      $objects = PluginGetObjects($type);

      if( is_array($objects) && isset($objects[$key]) ) {
            return($objects[$key]);
      }
      
      return(NULL);
}

function PluginGetObjectByName($name,$type) 
{

      $objects = PluginGetObjects($type);

      if( is_array($objects) ) {

            foreach( $objects as $object) {
                  
                  # Template object
                  if( @$object['name'] == $name ) {
                        return($object);
                  } else if ( @$object[$type."_name"] == $name ) {
                        return($object);
                  }
            }
      }
      
      return(NULL);
}

function PluginSaveConfig($fileid, $data) 
{

      $filename = NGT_CFGLOC."nagatcfg.dat";

      if( !is_array($data) ) {
            return("No data, nothing to save.");
      }

      $fullcfg = PluginGetConfig();
      if( $fullcfg == NULL ) {
            $fullcfg = array();
      }

      # Don't save empty values
      foreach($data as $key => $value) {
            for($i = 0; $i < count($value); $i++) {
                  if( !empty($value[$i]) || "$value[$i]" == "0" ) {
                        $newcfg[$key][] = $value[$i];
                  }
            }
      }

      $fullcfg[$fileid] = $newcfg;

      if( PrivatPluginDumpObjects($filename,$fullcfg) ) {
            return(NULL);
      }

      return("Failed writing to $filename.");
}

function PluginSaveObject($objectid, $data, $objecttype)
{
      $currobjects = PluginGetObjects(); 
      $newobject = array();

      # Don't save empty values
      foreach($data as $key => $value) {
            if( !empty($value) || "$value" == "0" ) {
                  $newobject[$key] = $value;
            }
      }

      if( !isset($currobjects[$objecttype][$objectid]) || !$objectid ) {
            $keys = array_keys($currobjects[$objecttype]);
            rsort($keys);
            $objectid = $keys[0] + 1;
            $currobjects[$objecttype][$objectid] = $newobject;
      }

      $newobject['__objectid'] = $objectid;
      $newobject['__type'] = $objecttype;
      $currobjects[$objecttype][$objectid] = $newobject;

      PrivatPluginDumpObjects(NGT_CFGLOC."nagatobjs.dat",$currobjects);
            
      return($objectid);
}

function PluginDeleteObject($objectid, $objecttype)
{
      $currobjects = PluginGetObjects();

      unset($currobjects[$objecttype][$objectid]);
      PrivatPluginDumpObjects(NGT_CFGLOC."nagatobjs.dat",$currobjects);

      return($objectid);
}

function PluginCfgWriteObject($objects, $location)
{
      if( is_array($objects) ) {
            $fp = fopen($location, "w");
            fwrite($fp, serialize($objects));
            fclose($fp);
      }
}

# function PluginImportCfgFile($fileid)
#
# PlguinImprtCfgFile imports configuration entries found in the files like
# nagios.cfg and cgi.cfg. $fileid is must have a value as defined in 
# nagiosdata.inc, for example
#
#     PluginImportCfgFile('nagioscfg')
#
# will import the configuration found in NAGIOS_ETC.'nagios.cfg'
#
# Returns a message on failure, NULL when succesful.
#
function PluginImportCfgFile($fileid)
{
      global $NAGIOS_CFGFILES;

      $entries = array();

      $filename = NAGIOS_ETC.$NAGIOS_CFGFILES[$fileid];

      if( file_exists($filename) == TRUE ) {
            $configlines = file($filename);
      } else {
            return("File $filename couldn't be read. Does it exist?");
      }

      foreach($configlines as $line) {
            
            $line = trim($line);

            # comments and empty lines are not proccessed
            if( preg_match("/^\s*#/", $line) == FALSE &&
                  $line != "" ) {

                  list($entry,$value) = explode("=",$line,2);
                  
                  if( @is_array($entries[$entry]) == FALSE ) {
                        $entries[$entry][0] = $value;
                  } else {
                        $entries[$entry][] = $value;
                  }
            }
      }

      if( $result = PluginSaveConfig($fileid,$entries) ) {
            return($result);
      }

      return(NULL);

}


# function PluginImportObjects($filename)
#
# PlguinImprtCfgObjects imports objects found in files written in the new
# template-based style. $filename is a file found in 'nagios.cfg' entries
# under 'cfg_file'.
#
#     PluginImportCfgFile('/usr/local/nagios/etc/hosts.cfg')
#
# will import all objects from hosts.cfg. It's important to keep track of this
# filename and it's type (host,contact,timeperiod,..) in the object definition.
#
# Returns a message on failure, NULL when succesful.
#
function PluginImportObjects($filename) 
{
      $currobj = "";
      $count = -1;
      $loccount = -1;
      $objectsread = 0;
      $objects = array();

      # Read the serialized data
      if( file_exists(NGT_CFGLOC."nagatobjs.dat") ) {
            $fp = fopen(NGT_CFGLOC."nagatobjs.dat","r");
            $serstr = fread($fp,filesize(NGT_CFGLOC."nagatobjs.dat"));
            fclose($fp);
            $objects = @unserialize($serstr);
      }

      if( file_exists($filename) == TRUE ) {
            $configlines = file($filename);
      } else {
            return(-1);
      }

      foreach($configlines as $line) {
            
            $line = rtrim($line);

            # comments and emty lines are not processed
            if( preg_match("/^\s*#/", $line) == FALSE &&
                  $line != "" ) {

                  if(preg_match("/^\s*define\s*(\w+)\s*{/", $line, $m)) {
                        $currobj = $m[1];
                        $count = @count($objects[$currobj]);
                        $objects[$currobj][$count]['__cfgfile'] =
                              $filename;
                        $objects[$currobj][$count]['__type'] =
                              $currobj;
                        $objects[$currobj][$count]['__objectid'] =
                              $count;
                  } else if (preg_match("/^\s*(\w+)\s*(.*)$/",$line,$m)
                              && $currobj != "") {
                        $objects[$currobj][$count][$m[1]] = $m[2];
                  } else if( preg_match("/^\s*}/",$line) ) {
                        $currobj = "";
                        $objectsread++;
                  }
            }
      }

      # Write it back as serialized data
      if( is_array($objects) ) {
            $fp = fopen(NGT_CFGLOC."nagatobjs.dat", "w");
            fwrite($fp, serialize($objects));
            fclose($fp);
      }

      return($objectsread);
}

#
# void PluginNagiosWriteConfig(string filename, array config)
#
# Saves configuration to a file. It will overwrite existing files not
# preserving the original comments nor layout.
#
# Returns NULL on success, or a string when something went wrong.
#
function PluginNagiosWriteConfig($fileid) 
{
      global $NAGIOS_CFGFILES;

      $lines = array();
      $filename = $NAGIOS_CFGFILES[$fileid];

      $lines[0] = <<<TXT
#
# $filename - Config file for Nagios (www.nagios.org)
#
# Written by Nagat. Manually editing this file is a bad idea since Nagat will
# overwrite it. Delete the nagatobj.dat file in the nagios/etc directory to
# reread the Nagios configuration.
#
TXT;
      $config = PluginGetConfig($fileid);

      foreach(@$config as $key => $values) {
            foreach($values as $value) {
                  $value = trim($value);
                  if( $value != '' ) {
                        $lines[] = "$key=".$value;
                  } 
            }
      }
      
      # Save the array to the file
      if( $fp = fopen(NAGIOS_ETC."$filename","w") ) {
            fwrite($fp,implode("\n",$lines));
            fclose($fp);
            return(NULL);
      } else {
            return("Could not open $filename for writing");
      }

      return("Something went wrong writing the configuration");

}

function PluginNagiosWriteObjects()
{
      $foundone = FALSE;
      $index_start = 0;
      $index_stop = 0;
      $gotit = FALSE;
      $space = '';
      $ident = '';
      $fileobjs = array();

      $allobjects = PluginGetObjects();
      $basefilename = basename($filename);

      $excluded = array('__cfgfile','__objectid','__type');

      $header = <<<TXT
#
# $basefilename - Config file for Nagios (www.nagios.org)
#
# Written by Nagat. Manually editing this file is a bad idea since Nagat will
# overwrite it. 
#

TXT;

      # Group objects by filename usage
      foreach( $allobjects as $type => $objarr) 
            foreach( $objarr as $key => $object)
                  $fileobjs[$object['__cfgfile']][] = $object; 
      
      foreach($fileobjs as $filename => $objects) {
            if( $fp = fopen("$filename","w") ) {

                  fwrite($fp,$header."\n");
                  foreach($objects as $object) {
                        $type = $object['__type'];

                        fwrite($fp,"define $type {\n");
                        foreach($object as $key => $val) {
                              if( (!empty($val) || $val == 0) 
                                    && !in_array($key,$excluded) )
                                    fwrite($fp,sprintf("%-30s %s\n",
                                          $key,$val));
                        }
                        fwrite($fp,"}\n\n");
                  }
                  fclose($fp);
            } else {
                  return "Could not open file $filename for writing";
            }
      }

      return(NULL);
}

?>

Generated by  Doxygen 1.6.0   Back to index