From: Frank Brehm Date: Tue, 7 Dec 2010 22:01:03 +0000 (+0000) Subject: Getopt Parser integriert X-Git-Url: https://git.uhu-banane.org/?a=commitdiff_plain;h=f94f5f7609706995cedbdba27518687002527bc0;p=my-stuff%2Fnagios.git Getopt Parser integriert git-svn-id: http://svn.brehm-online.com/svn/my-stuff/nagios/trunk@147 ec8d2aa5-1599-4edb-8739-2b3a1bc399aa --- diff --git a/bin/check_nagios_config.py b/bin/check_nagios_config.py index 070da81..f2dbee7 100755 --- a/bin/check_nagios_config.py +++ b/bin/check_nagios_config.py @@ -4,6 +4,7 @@ import sys import pprint from nagios.config import NagiosConfig, NagiosConfigError +from fbrehm.common.getopt import BaseOptParser #print "Modul-Suchpfade:" #for p in sys.path: @@ -14,8 +15,27 @@ from nagios.config import NagiosConfig, NagiosConfigError # print " -", name #print "" +opt_parser = BaseOptParser( + version = '0.0.2', + prog = 'check_nagios_config.py', + description = u'Überprüft die Syntax einer Nagios-Konfiguration.', + usage = u'%s [Optionen] [
]' +) + +opt_parser.setBaseOptionHelp( 'test', u'Simuliert nur verändernde Aktionen, wenn gesetzt' ) +opt_parser.setBaseOptionHelp( 'verbose', u'Setzt das Ausführlichkeitsniveau der Debug-Meldungen.' ) +opt_parser.setBaseOptionHelp( 'version', u'Gibt die Versionsnummer des Programms aus und beendet sich' ) +opt_parser.setBaseOptionHelp( 'help', u'Stellt diese Hilfe dar und beendet sich' ) +opt_parser.getOpts() + +verbose = opt_parser.options.verbose + +file = None +if len(opt_parser.args): + file = opt_parser.args[0] + try: - nagios_conf = NagiosConfig() + nagios_conf = NagiosConfig( verbose = verbose, new_file = file ) nagios_conf.read() except NagiosConfigError as e: print >> sys.stderr, e diff --git a/bin/fbrehm/common/getopt.py b/bin/fbrehm/common/getopt.py index 4499a47..52b846e 100755 --- a/bin/fbrehm/common/getopt.py +++ b/bin/fbrehm/common/getopt.py @@ -32,7 +32,11 @@ class BaseOptParser(object): ''' #--------------------------------------------------------------------- - def __init__( self, prog='%prog', version=None, description='' ): + def __init__( self, prog = '%prog', + version = None, + description = '', + usage = 'Usage: %s [options]' + ): ''' Costructor. @param prog: The name of the calling process (e.g. sys.argv[0]) @@ -41,12 +45,14 @@ class BaseOptParser(object): @type version: str @param description: The Description the process should use @type description: str + @param usage: An usage string fro the help screen, must have a '%s' for the program name + @type usage: str @return: None ''' self.prog = prog self.version = version self.description = description - self.usage = 'Usage: %s [options]' %(prog) + self.usage = usage %(prog) self.options = None self.args = None @@ -55,9 +61,10 @@ class BaseOptParser(object): self.parsed = False self.parser = OptionParser( - prog=self.prog, - version=self.version, - description=self.description + prog = self.prog, + version = self.version, + description = self.description, + usage = self.usage ) self.addOption( @@ -79,6 +86,7 @@ class BaseOptParser(object): help = 'set the verbosity level' ) + #---------------------------------------------------------------------- def getOpts(self): ''' The baseimplentation of getOpts. It ensures that evry class @@ -94,6 +102,7 @@ class BaseOptParser(object): self.options, self.args = self.parser.parse_args() self.parsed = True + #---------------------------------------------------------------------- def addOption(self, *targs, **kwargs): ''' This Method adds the options to the parser instance. @@ -109,6 +118,40 @@ class BaseOptParser(object): if not self.__options_set: self.__options_set = True + #---------------------------------------------------------------------- + def setBaseOptionHelp( self, option_name, option_help ): + '''This method sets the help text of the named option. + @param option_name: The name of the option to change + @type option_name: str + @param option_help: The new option help text + @type option_help: str + @return: None + @rtype: None + ''' + + if not len(option_name): + raise SyntaxError( "empty option name given." ) + + as_long_option = True + if len(option_name) == 1: as_long_option = False + + for option in self.parser.option_list: + opt_found = False + if as_long_option: + o = '--' + option_name + for opt in option._long_opts: + if o == opt: + opt_found = True + break + else: + o = '-' + option_name + for opt in option._short_opts: + if o == opt: + opt_found = True + break + if opt_found: + option.help = option_help + break #--------------------------------------------------------------------- diff --git a/bin/nagios/config.py b/bin/nagios/config.py index 10974d2..0672800 100644 --- a/bin/nagios/config.py +++ b/bin/nagios/config.py @@ -66,21 +66,55 @@ class NagiosConfig(object): return repr(dump) #------------------------------------------------------ - def __init__( self, new_file = file_name, ignore_empty_object_props = True ): - "Konstruktor." + def __init__( self, new_file = None, + ignore_empty_object_props = True, + verbose = 0, ): + """Constructor. + @param new_file: The main nagios configuration file + @type new_file: str + @param ignore_empty_object_props: should empty object prperties ignored? default: True + @type ignore_empty_object_props: bool + @param verbose: verbosity level (default: 0) + @type verbose: int + @return: None + @rtype: None + + """ + + self.verbose = verbose + loglevel = logging.WARNING + logformat = '%(levelname)s: %(message)s' + if verbose == 1: + loglevel = logging.INFO + elif verbose > 1: + loglevel = logging.DEBUG + logformat = '%(name)s - %(module)s.%(funcName)s(%(lineno)d) - %(levelname)s: %(message)s' # Logging-Setup self.logger = logging.getLogger('nagiosConfig') - self.logger.setLevel(logging.DEBUG) + self.logger.setLevel(loglevel) ch = logging.StreamHandler() - ch.setLevel(logging.DEBUG) + ch.setLevel(loglevel) - formatter = logging.Formatter("%(name)s - %(funcName)s(%(lineno)d) - %(levelname)s - %(message)s") + formatter = logging.Formatter(logformat) ch.setFormatter(formatter) self.logger.addHandler(ch) + # Other properties + + # Konfigurationsverzeichnis von Nagios + self.default_conf_dir = os.sep + os.path.join('etc', 'nagios') + + # Basename der Nagios-Konfigurationsdatei + self.default_file_base = 'nagios.cfg' + + # Kompletter Pfad der Nagios-Konfigurationsdatei + self.default_file_name = os.path.join( self.default_conf_dir, self.default_file_base ) + + if new_file is None: + new_file = self.default_file_name self.file_name = self.canonize_file(new_file) self.conf = {} self.objects = {} @@ -145,13 +179,15 @@ class NagiosConfig(object): self.file_name = my_file return my_file - raise NagiosConfigError( "Nagios-Konfigurationsdatei nicht gefunden." ) + raise NagiosConfigError( "Nagios config file not found." ) return None #------------------------------------------------------ def read( self ): "Liest die in self.file_name hinterlegte Konfigurationsdatei ein und legt das Gelesene in self.conf ab" + self.logger.info( "Reading configuration file {0!r} ...".format( self.file_name ) ) + try: file = open( self.file_name, 'rU' ) except IOError as e: @@ -272,7 +308,7 @@ class NagiosConfig(object): self.read_objectfile(file_name) pp = pprint.PrettyPrinter( indent = 4, depth = 6, width = 120 ) - self.logger.debug( "Gelesene Objekte:\n{0}".format( pp.pformat( self.objects_read ) ) ) + self.logger.debug( "Read objects:\n{0}".format( pp.pformat( self.objects_read ) ) ) del self.struct_verifier @@ -378,26 +414,26 @@ class NagiosConfig(object): "Checkt absolute Angabe und Vorhandensein der übergebenen Datei bzw. Verzeichnis" directive = 'cfg_file' - file_type = 'Datei' + file_type = 'file' if as_dir: directive = 'cfg_dir' - file_type = 'Verzeichnis' + file_type = 'directory' if not os.path.isabs(file): - self.logger.error( "Keine absolute Pfadangabe in {0}={1}".format( directive, file ) ) + self.logger.error( "No absolute path given in {0}={1}".format( directive, file ) ) return None if not os.path.exists(file): - self.logger.error( "{0} {1} existiert nicht.".format( file_type, file ) ) + self.logger.error( "{0} {1} doesn't exists.".format( file_type, file ) ) return None if as_dir: if not os.path.isdir(file): - self.logger.error( "Verzeichnis {0} ist keine normales Verzeichnis.".format(file) ) + self.logger.error( "Directory {0} isn't a regular directory.".format(file) ) return None else: if not os.path.isfile(file): - self.logger.error( "Datei {0} ist keine normale Datei.".format(file) ) + self.logger.error( "File {0} isn't a regular file.".format(file) ) return None return os.path.realpath(file)