Package Products :: Package ZenUtils :: Module GlobalConfig
[hide private]
[frames] | no frames]

Source Code for Module Products.ZenUtils.GlobalConfig

  1  ########################################################################### 
  2  # 
  3  # This program is part of Zenoss Core, an open source monitoring platform. 
  4  # Copyright (C) 2010, Zenoss Inc. 
  5  # 
  6  # This program is free software; you can redistribute it and/or modify it 
  7  # under the terms of the GNU General Public License version 2 or (at your 
  8  # option) any later version as published by the Free Software Foundation. 
  9  # 
 10  # For complete information please visit: http://www.zenoss.com/oss/ 
 11  # 
 12  ########################################################################### 
 13  import sys 
 14  from optparse import OptionValueError, BadOptionError 
 15   
 16  from Products.ZenUtils.Utils import zenPath 
 17  from Products.ZenUtils.config import Config, ConfigLoader 
 18   
 19  CONFIG_FILE = zenPath('etc', 'global.conf') 
 20   
21 -class GlobalConfig(Config):
22 """ 23 A method for retrieving the global configuration options 24 outside of a daemon. This is used to configure the 25 AMQP connection in Zope and zenhub 26 27 @todo Add validation for expected keys and values 28 """ 29 pass
30 31 _GLOBAL_CONFIG = ConfigLoader(CONFIG_FILE, GlobalConfig)
32 -def getGlobalConfiguration():
33 return _GLOBAL_CONFIG()
34
35 -def _convertConfigLinesToArguments(parser, lines):
36 """ 37 Converts configuration file lines of the format: 38 39 myoption 1 40 mybooloption False 41 42 to the equivalent command-line arguments for the specified OptionParser. 43 For example, the configuration file above would return the argument 44 list ['--myoption', '1', '--mybooloption'] if mybooloption has action 45 store_false, and ['--myoption', '1'] if mybooloption has action store_true. 46 47 @parameter parser: OptionParser object containing configuration options. 48 @type parser: OptionParser 49 @parameter lines: List of dictionary object parsed from a configuration file. 50 Each option is expected to have 'type', 'key', 'value' entries. 51 @type lines: list of dictionaries. 52 @return: List of command-line arguments corresponding to the configuration file. 53 @rtype: list of strings 54 """ 55 # valid key 56 # an option's string without the leading "--" 57 # can differ from an option's destination 58 validkeys = [] 59 for opt in parser.option_list: 60 optstring = opt.get_opt_string() 61 validkey = optstring.lstrip("-") 62 validkeys.append(validkey) 63 64 args = [] 65 for line in lines: 66 if line.get('type', None) == 'option' and line['key'] in validkeys: 67 option = parser.get_option('--' + line['key']) 68 boolean_value = line.get('value', '').lower() in ('true','yes','1') 69 if option.action == 'store_true': 70 if boolean_value: 71 args += ['--%s' % line['key']] 72 elif option.action == 'store_false': 73 if not boolean_value: 74 args += ['--%s' % line['key']] 75 else: 76 args += ['--%s' % line['key'], line['value']] 77 78 return args
79
80 -class _GlobalConfParserAdapter(object):
81 - def __init__(self, parser):
82 self.parser = parser
83
84 - def apply(self):
85 self.parser.defaults = self._getGlobalConfigFileDefaults() 86 return self.parser
87
89 # TODO: This should be refactored - duplicated code with CmdBase. 90 """ 91 Parse a config file which has key-value pairs delimited by white space, 92 and update the parser's option defaults with these values. 93 """ 94 options = self.parser.get_default_values() 95 lines = self._loadConfigFile(CONFIG_FILE) 96 if lines: 97 args = _convertConfigLinesToArguments(self.parser, lines) 98 try: 99 self.parser._process_args([], args, options) 100 except (BadOptionError, OptionValueError) as err: 101 # Ignore it, we only care about our own options as defined in the parser 102 pass 103 return options.__dict__
104
105 - def _loadConfigFile(self, filename):
106 # TODO: This should be refactored - duplicated code with CmdBase. 107 """ 108 Parse a config file which has key-value pairs delimited by white space. 109 110 @parameter filename: path to the configuration file 111 @type filename: string 112 """ 113 lines = [] 114 try: 115 with open(filename) as file: 116 for line in file: 117 if line.lstrip().startswith('#') or line.strip() == '': 118 lines.append(dict(type='comment', line=line)) 119 else: 120 try: 121 key, value = line.strip().split(None, 1) 122 except ValueError: 123 lines.append(dict(type='option', line=line, key=line.strip(), value=None, option=None)) 124 else: 125 option = self.parser.get_option('--%s' % key) 126 lines.append(dict(type='option', line=line, key=key, value=value, option=option)) 127 except IOError as e: 128 errorMessage = 'WARN: unable to read config file {filename} \ 129 -- skipping. ({exceptionName}: {exception})'.format( 130 filename=filename, 131 exceptionName=e.__class__.__name__, 132 exception=e 133 ) 134 print >>sys.stderr, errorMessage 135 return [] 136 137 return lines
138 139
140 -def applyGlobalConfToParser(parser):
141 return _GlobalConfParserAdapter(parser).apply()
142