Changeset 11028

Show
Ignore:
Timestamp:
11/19/08 18:41:44 (7 weeks ago)
Author:
kkearney
Message:
 * Refs #3403: Allow command-line params to override config-file defaults
Files:
1 modified

Legend:

Unmodified
Added
Removed
  • sandboxen/kells/3403/CmdBase.py

    r10813 r11028  
    1616Provide utility functions for logging and config file parsing 
    1717to command line programs 
    18  
    19  
    20 $Id: CmdBase.py,v 1.10 2004/04/04 02:22:21 edahl Exp $""" 
    21  
    22 __version__ = "$Revision: 1.10 $"[11:-2] 
     18""" 
    2319 
    2420import os 
     
    3632unused(pkg_resources) 
    3733 
    38 def parseconfig(options): 
    39     """parse a config file which has key value pairs delimited by white space""" 
    40     if not os.path.exists(options.configfile): 
    41         print >>sys.stderr, "WARN: config file %s not found skipping" % ( 
    42                             options.configfile) 
    43         return 
    44     lines = open(options.configfile).readlines() 
    45     for line in lines: 
    46         if line.lstrip().startswith('#'): continue 
    47         if line.strip() == '': continue 
    48         key, value = line.split(None, 1) 
    49         value = value.rstrip('\r\n') 
    50         key = key.lower() 
    51         defval = getattr(options, key, None) 
    52         # hack around for #2290: ignore config file values for 
    53         # list types when the user has provided a value 
    54         if type(defval) == type([]) and defval: continue 
    55         if defval: value = type(defval)(value) 
    56         setattr(options, key, value) 
    57  
    58  
    5934class DMDError: pass 
    6035 
    6136class CmdBase: 
     37    """ 
     38    Class used for all Zenoss commands 
     39    """ 
    6240     
    6341    doesLogging = True 
     
    7654        self.buildParser() 
    7755        self.buildOptions() 
     56         
    7857        self.parseOptions() 
    7958        if self.options.configfile: 
    80             parseconfig(self.options) 
     59            self.getConfigFileDefaults( self.options.configfile ) 
     60            self.parseOptions() 
     61 
    8162        if self.doesLogging: 
    8263            self.setupLogging() 
    8364 
    8465 
     66    def getConfigFileDefaults(self, filename): 
     67        """ 
     68        Parse a config file which has key-value pairs delimited by white space, 
     69        and update the parser's option defaults with these values. 
     70        """ 
     71        try: 
     72            lines = open(filename).readlines() 
     73        except: 
     74            import traceback 
     75            print >>sys.stderr, "WARN: unable to read config file %s -- skipping" % \ 
     76                   filename 
     77            traceback.print_exc(0) 
     78            return 
     79 
     80        for line in lines: 
     81            if line.lstrip().startswith('#'): continue 
     82            if line.strip() == '': continue 
     83 
     84            key, value = line.split(None, 1) 
     85            value = value.rstrip('\r\n') 
     86 
     87            flag= "--%s" % key 
     88            option= self.parser.get_option( flag ) 
     89            if option is None: 
     90                print >>sys.stderr, "WARN: Ignoring unknown option '%s' found in config file" % key 
     91                continue 
     92 
     93            # NB: At this stage, optparse accepts even bogus values 
     94            #     It will report unhappiness when it parses the arguments 
     95            self.parser.set_default( option.dest, type(option.type)(value) ) 
     96 
     97 
    8598    def setupLogging(self): 
     99        """ 
     100        Set common logging options 
     101        """ 
    86102        rlog = logging.getLogger() 
    87103        rlog.setLevel(logging.WARN) 
     
    90106        zlog = logging.getLogger("zen") 
    91107        zlog.setLevel(self.options.logseverity) 
     108 
    92109        if self.options.logpath: 
    93110            logdir = self.options.logpath 
     
    105122 
    106123    def buildParser(self): 
     124        """ 
     125        Create the options parser 
     126        """ 
    107127        if not self.parser: 
     128            from Products.ZenModel.ZenossInfo import ZenossInfo 
     129            try: 
     130                zinfo= ZenossInfo() 
     131                version= zinfo.getZenossVersion() 
     132            except: 
     133                from Products.ZenModel.ZVersion import VERSION 
     134                version= VERSION 
    108135            self.parser = OptionParser(usage=self.usage,  
    109                                        version="%prog " + __version__) 
     136                                       version="%prog " + version ) 
    110137 
    111138    def buildOptions(self): 
    112         """basic options setup sub classes can add more options here""" 
     139        """ 
     140        Basic options setup. Other classes should call this before adding 
     141        more options 
     142        """ 
    113143        self.buildParser() 
    114144        if self.doesLogging: 
     
    118148                        type='int', 
    119149                        help='Logging severity threshold') 
     150 
    120151            self.parser.add_option('--logpath',dest='logpath', 
    121                         help='override default logging path') 
     152                        help='Override the default logging path') 
     153 
    122154        self.parser.add_option("-C", "--configfile",  
    123155                    dest="configfile", 
    124                     help="config file must define all params (see man)") 
     156                    help="Use an alternate configuration file" ) 
     157 
     158        self.parser.add_option("--genconf", 
     159                               action="store_true", 
     160                               default=False, 
     161                               help="Generate a template configuration file" ) 
     162 
     163        self.parser.add_option("--genxmltable", 
     164                               action="store_true", 
     165                               default=False, 
     166                               help="Generate a Docbook table showing command-line switches." ) 
     167 
    125168 
    126169 
    127170 
    128171    def pretty_print_config_comment( self, comment ): 
    129         """Quick and dirty pretty printer for comments that happen to be longer than can comfortably 
    130 be seen on the display.""" 
     172        """ 
     173        Quick and dirty pretty printer for comments that happen to be longer than can comfortably 
     174be seen on the display. 
     175        """ 
    131176 
    132177        max_size= 40 
     
    181226 
    182227    def generate_configs( self, parser, options ): 
    183         """Create a configuration file based on the long-form of the option names""" 
     228        """ 
     229        Create a configuration file based on the long-form of the option names 
     230 
     231        @parameter parser: an optparse parser object which contains defaults, help 
     232        @parameter options: parsed options list containing actual values 
     233        """ 
    184234 
    185235        # 
     
    263313 
    264314    def generate_xml_table( self, parser, options ): 
    265         """Create a Docbook table based on the long-form of the option names""" 
     315        """ 
     316        Create a Docbook table based on the long-form of the option names 
     317 
     318        @parameter parser: an optparse parser object which contains defaults, help 
     319        @parameter options: parsed options list containing actual values 
     320        """ 
    266321 
    267322        # 
     
    378433 
    379434    def parseOptions(self): 
    380  
    381         self.parser.add_option("--genconf", 
    382                                action="store_true", 
    383                                default=False, 
    384                                help="Generate a template configuration file" ) 
    385  
    386         self.parser.add_option("--genxmltable", 
    387                                action="store_true", 
    388                                default=False, 
    389                                help="Generate a Docbook table showing command-line switches." ) 
     435        """ 
     436        Uses the optparse parse previously populated and performs common options. 
     437        """ 
    390438 
    391439        if self.noopts: