Beispiel #1
0
def load():
    """Loads FileDirectives from ConfigFile into this module's attributes."""
    section = "*"
    module = sys.modules[__name__]
    parser = RawConfigParser()
    parser.optionxform = str # Force case-sensitivity on names
    try:
        parser.read(ConfigFile)

        def parse_value(name):
            try: # parser.get can throw an error if value not found
                value_raw = parser.get(section, name)
            except Exception:
                return False, None
            # First, try to interpret as JSON
            try:
                value = json.loads(value_raw)
            except ValueError: # JSON failed, try to eval it
                try:
                    value = eval(value_raw)
                except SyntaxError: # Fall back to string
                    value = value_raw
            return True, value

        for oldname, name in FileDirectiveCompatiblity.items():
            [setattr(module, name, v) for s, v in [parse_value(oldname)] if s]
        for name in FileDirectives:
            [setattr(module, name, v) for s, v in [parse_value(name)] if s]
        for name in OptionalFileDirectives:
            OptionalFileDirectiveDefaults[name] = getattr(module, name, None)
            success, value = parse_value(name)
            if success:
                setattr(module, name, value)
    except Exception:
        pass # Fail silently
     def __init__(self, hashfile=LOCATION, storeKey="", configFile=CONFIGFILE):
          self.userDict = { }                       # Mapping of username -> salt:hash
          self.hashfile = hashfile                  # Encrypted file, contains lines of user:salt:hash 
          self.h = SHA256.new()
          self.crypto = crypto.TBCrypt()            # AES encryption/IV functions
          self.storeKey = storeKey                  # Key material to open encrypted hash store
          if configFile:
               try:
                   fp = open(configFile)
               except IOError as e:
                   error = 'IOError: can''t access file ''%s'' (%s).' % (configFile, os.strerror(e.errno))
                   raise HashStoreException(error)
          
               config = RawConfigParser()
               config.read(configFile)
               self.storeKey = config.get('hashstore', 'key')
               self.hashfile = config.get('hashstore', 'location')
          else:
               if os.path.exists(self.hashfile):
                    self.updateUserDict()
               else:
                    self.__saveHashstore()

          if self.storeKey == '':
               print "WARNING: hashstoremanager.py: no hashstore key defined!"

#          print "h.update"
          self.h.update(self.storeKey)
#          print "self.storeKey = self.h.digest()"
          self.storeKey = self.h.digest()
Beispiel #3
0
    def render_POST(self, request):

        def _renderResponse(response):
            if isinstance(response, Failure):
                request.write(json.dumps({'success': False, 'message': response.getErrorMessage()}))
            else:
                request.write(json.dumps({'success': True}))
            request.finish()

        content = parse_qs(request.content.read())

        command = content.get('playlist.add', [None])[0]
        item = content['item'][0]


        config_parser = RawConfigParser()
        config_parser.read(os.path.expanduser("~/.config/smplayer/smplayer.ini"))
        port = config_parser.getint('instances', 'temp\\autoport')


        creator = ClientCreator(reactor, SMPlayer, item = item)
        creator.connectTCP('127.0.0.1', port).addBoth(_renderResponse)

        request.setHeader('Access-Control-Allow-Origin', '*')
        request.setHeader('Content-Type', 'application/json')
        return NOT_DONE_YET
Beispiel #4
0
def load():
    """Loads FileDirectives from ConfigFile into this module's attributes."""
    section = "*"
    module = sys.modules[__name__]
    parser = RawConfigParser()
    parser.optionxform = str # Force case-sensitivity on names
    try:
        parser.read(ConfigFile)
        for name in FileDirectives:
            try: # parser.get can throw an error if not found
                value_raw = parser.get(section, name)
                success = False
                # First, try to interpret as JSON
                try:
                    value = json.loads(value_raw)
                    success = True
                except:
                    pass
                if not success:
                    # JSON failed, try to eval it
                    try:
                        value = eval(value_raw)
                        success = True
                    except:
                        # JSON and eval failed, fall back to string
                        value = value_raw
                        success = True
                if success:
                    setattr(module, name, value)
            except:
                pass
    except Exception, e:
        pass # Fail silently
Beispiel #5
0
class ApplicationConfig(object):
    """A thin wrapper around ConfigParser that remembers what we read.

    The remembered settings can then be written out to a minimal config file
    when building the Elastic Beanstalk zipfile.

    """
    def __init__(self):
        self.input = RawConfigParser()
        with open("production.ini") as f:
            self.input.readfp(f)
        self.output = RawConfigParser()

    def get(self, section, key):
        value = self.input.get(section, key)

        # remember that we needed this configuration value
        if (section.upper() != "DEFAULT" and
            not self.output.has_section(section)):
            self.output.add_section(section)
        self.output.set(section, key, value)

        return value

    def to_config(self):
        io = cStringIO.StringIO()
        self.output.write(io)
        return io.getvalue()
Beispiel #6
0
def test_imap_config_values_should_be_stored():
	am = AccountManager()
	option_spec = get_mailbox_parameter_specs('imap')
	options = {
		'user': 'you',
		'password': '',
		'server': 'imap.example.org',
		'port': '',
		'ssl': True,
		'imap': True,
		'idle': True,
		'folders': ['a', 'b'],
	}
	config = RawConfigParser()
	config.add_section('account1')
	am._set_cfg_options(config, 'account1', options, option_spec)
	expected_config_items = [
		('user', 'you'),
		('password', ''),
		('server', 'imap.example.org'),
		('port', ''),
		('ssl', '1'),
		('imap', '1'),
		('idle', '1'),
		('folder', '["a", "b"]'),
	]
	assert set(expected_config_items) == set(config.items('account1'))
Beispiel #7
0
def get_license_devices():
    """
    Retrieves the number of assets for a given license

    Return:
        Number of devices signed for a license
        0 if an error occurs
        1000000 if 'devices' is not specified in the ossim.lic file
    """
    rc, pro = system_is_professional()
    devices = 0
    if rc and pro:
        if os.path.isfile("/etc/ossim/ossim.lic"):
            try:
                config = RawConfigParser()
                license_file = config.read('/etc/ossim/ossim.lic')
                devices = config.getint('appliance', 'devices')
            except NoOptionError:
                devices = 1000000

        else:
            api_log.debug("License devices can't be determined: License file not found")
            devices = 0

    else:
        devices = 1000000

    return devices
Beispiel #8
0
def _fetchAzureAccountKey(accountName):
    """
    Find the account key for a given Azure storage account.

    The account key is taken from the AZURE_ACCOUNT_KEY_<account> environment variable if it
    exists, then from plain AZURE_ACCOUNT_KEY, and then from looking in the file
    ~/.toilAzureCredentials. That file has format:

    [AzureStorageCredentials]
    accountName1=ACCOUNTKEY1==
    accountName2=ACCOUNTKEY2==
    """
    try:
        return os.environ['AZURE_ACCOUNT_KEY_' + accountName]
    except KeyError:
        try:
            return os.environ['AZURE_ACCOUNT_KEY']
        except KeyError:
            configParser = RawConfigParser()
            configParser.read(os.path.expanduser(credential_file_path))
            try:
                return configParser.get('AzureStorageCredentials', accountName)
            except NoOptionError:
                raise RuntimeError("No account key found for '%s', please provide it in '%s'" %
                                   (accountName, credential_file_path))
Beispiel #9
0
    def __init__(self, path=None, with_defaults=False):
        RawConfigParser.__init__(self, dict_type=OrderedDict)
        self.path = path or os.environ.get(CONFIG_ENV, CONFIG_PATH)

        # Check if self.path is accessible
        abspath = os.path.abspath(self.path)
        if not os.path.exists(self.path):
            log.warning('Config file %s does not exist' % abspath)
        elif os.access(self.path, os.R_OK):
            if not os.access(self.path, os.W_OK):
                log.warning('Config file %s is not writable' % abspath)
        else:
            raise CLIError(
                'Config file %s is inaccessible' % abspath,
                importance=3, details=['No read permissions for this file'])

        self._overrides = defaultdict(dict)
        if with_defaults:
            self._load_defaults()
        self.read(self.path)

        for section in self.sections():
            r = self.cloud_name(section)
            if r:
                for k, v in self.items(section):
                    self.set_cloud(r, k, v)
                self.remove_section(section)
Beispiel #10
0
class Config(dict):
    def __init__(self):
        dict.__init__(self)
        self.refresh()

    def __get_conf_val(self, section, param, var_name, p_type=str):
        try:
            val = self.__config.get(section, param)
            self[var_name] = p_type(val)
        except ConfigParser.Error:
            pass

    def refresh(self):
        try:
            self.update(self.get_defaults())
            config_file = self.get_config_file_path()

            if not os.path.exists(config_file):
                self.save()

            self.__config = RawConfigParser()
            self.__config.read(config_file)

            self.__get_conf_val('LOG','log_level', 'log_level')
            self.__get_conf_val('FABNET', 'fabnet_url', 'fabnet_hostname')
            self.__get_conf_val('FABNET', 'parallel_put_count', 'parallel_put_count', int)
            self.__get_conf_val('FABNET', 'parallel_get_count', 'parallel_get_count', int)
            self.__get_conf_val('CACHE', 'data_dir', 'data_dir')
            self.__get_conf_val('CACHE', 'cache_size', 'cache_size', int)
            self.__get_conf_val('WEBDAV', 'bind_hostname', 'webdav_bind_host')
            self.__get_conf_val('WEBDAV', 'bind_port', 'webdav_bind_port')
            self.__get_conf_val('WEBDAV', 'mount_type', 'mount_type')
            self.__get_conf_val('CA', 'ca_address', 'ca_address')
        except ConfigParser.Error, msg:
            raise Exception('ConfigParser: %s' % msg)
Beispiel #11
0
    def check_file(self, pkg, filename):
        root = pkg.dirName()
        f = root + filename
        st = getstatusoutput(('desktop-file-validate', f), True)
        if st[0]:
            error_printed = False
            for line in st[1].splitlines():
                if 'error: ' in line:
                    printError(pkg, 'invalid-desktopfile', filename,
                               line.split('error: ')[1])
                    error_printed = True
            if not error_printed:
                printError(pkg, 'invalid-desktopfile', filename)
        if not is_utf8(f):
            printError(pkg, 'non-utf8-desktopfile', filename)

        cfp = RawConfigParser()
        cfp.read(f)
        binary = None
        if cfp.has_option('Desktop Entry', 'Exec'):
            binary = cfp.get('Desktop Entry', 'Exec').split(' ', 1)[0]
        if binary:
            found = False
            if binary.startswith('/'):
                found = os.path.exists(root + binary)
            else:
                for i in STANDARD_BIN_DIRS:
                    if os.path.exists(root + i + binary):
                        # no need to check if the binary is +x, rpmlint does it
                        # in another place
                        found = True
                        break
            if not found:
                printWarning(pkg, 'desktopfile-without-binary', filename,
                             binary)
Beispiel #12
0
    def get_backend(self, backend_name):
        """
        Get options of backend.

        :returns: a tuple with the module name and the module options dict
        :rtype: tuple
        """

        config = RawConfigParser()
        config.read(self.confpath)
        if not config.has_section(backend_name):
            raise KeyError(u'Configured backend "%s" not found' % backend_name)

        items = dict(config.items(backend_name))

        try:
            module_name = items.pop('_module')
        except KeyError:
            try:
                module_name = items.pop('_backend')
                self.edit_backend(backend_name, module_name, items)
            except KeyError:
                warning('Missing field "_module" for configured backend "%s"', backend_name)
                raise KeyError(u'Configured backend "%s" not found' % backend_name)
        return module_name, items
Beispiel #13
0
def pms_readConf(filename):
	class multiKeyDict(DictMixin):
		def __init__(self, d=None):
			self._data = d or {}
		def __setitem__(self, key, value):
			if key in self._data and isinstance(self._data[key], list) and isinstance(value, list):
				self._data[key].extend(value)
			else:
				self._data[key] = value
		def __getitem__(self, key):
			return self._data[key]
		def __delitem__(self, key):
			del self._data[key]
		def keys(self):
			return self._data.keys()
		def copy(self):
			return multiKeyDict(self._data.copy())
	conf = RawConfigParser(dict_type=multiKeyDict)
	for c in [filename, os.path.join(pms.getProfileDir(), os.path.basename(filename))]:
		if os.path.exists(c):
			conf.readfp(StringIO('[.]\n'+open(c).read()))
	try:
		conf = dict(conf.items('.'))
		print '%s: %s' % (filename, conf)
		return conf
	except:
		return {}
Beispiel #14
0
def save():
    """Saves FileDirectives into ConfigFile."""
    section = "*"
    module = sys.modules[__name__]
    parser = RawConfigParser()
    parser.optionxform = str # Force case-sensitivity on names
    parser.add_section(section)
    try:
        f, fname = open(ConfigFile, "wb"), util.longpath(ConfigFile)
        f.write("# %s configuration autowritten on %s.\n" %
                (fname, datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
        for name in FileDirectives:
            try:
                parser.set(section, name, json.dumps(getattr(module, name)))
            except Exception: pass
        for name in OptionalFileDirectives:
            try:
                value = getattr(module, name, None)
                if OptionalFileDirectiveDefaults.get(name) != value:
                    parser.set(section, name, json.dumps(value))
            except Exception: pass
        parser.write(f)
        f.close()
    except Exception:
        pass # Fail silently
Beispiel #15
0
    def __init__(self, configfiles):
        self.configfiles = configfiles

        configparser = RawConfigParser()
        config_tmp = configparser.read(self.configfiles)
        self.conf = dict()
        for section in configparser.sections():
            self.conf[section] = dict(configparser.items(section))

        #self.conf = ConfigObj(self.configfile, interpolation=False)

        @message("file could not be found")
        def check_file(v):
            f = os.path.expanduser(os.path.expanduser(v))
            if os.path.exists(f):
                return f
            else:
                raise Invalid("file could not be found `%s`" % v)

        @message("Unsupported nova API version")
        def nova_api_version(version):
            try:
                from novaclient import client, exceptions
                client.get_client_class(version)
                return version
            except exceptions.UnsupportedVersion as ex:
                raise Invalid(
                    "Invalid option for `nova_api_version`: %s" % ex)

        self.schemas = {
            "cloud": Schema(
                {"provider": Any('ec2_boto', 'google', 'openstack'),
                 "ec2_url": Url(str),
                 "ec2_access_key": All(str, Length(min=1)),
                 "ec2_secret_key": All(str, Length(min=1)),
                 "ec2_region": All(str, Length(min=1)),
                 "auth_url": All(str, Length(min=1)),
                 "username": All(str, Length(min=1)),
                 "password": All(str, Length(min=1)),
                 "tenant_name": All(str, Length(min=1)),
                 Optional("region_name"): All(str, Length(min=1)),
                 "gce_project_id": All(str, Length(min=1)),
                 "gce_client_id": All(str, Length(min=1)),
                 "gce_client_secret": All(str, Length(min=1)),
                 "nova_client_api": nova_api_version()}, extra=True),
            "cluster": Schema(
                {"cloud": All(str, Length(min=1)),
                 "setup_provider": All(str, Length(min=1)),
                 "login": All(str, Length(min=1))}, required=True, extra=True),
            "setup": Schema(
                {"provider": All(str, Length(min=1)),
                    }, required=True, extra=True),
            "login": Schema(
                {"image_user": All(str, Length(min=1)),
                 "image_user_sudo": All(str, Length(min=1)),
                 "image_sudo": Boolean(str),
                 "user_key_name": All(str, Length(min=1)),
                 "user_key_private": check_file(),
                 "user_key_public": check_file()}, required=True)
        }
Beispiel #16
0
 def remove_option(self, section, option, also_remove_default=False):
     try:
         if also_remove_default:
             DEFAULTS[section].pop(option)
         RawConfigParser.remove_option(self, section, option)
     except (NoSectionError, KeyError):
         pass
Beispiel #17
0
def test_no_notListed():
    cfg = RawConfigParser()
    cfg.add_section('group hackers')
    cfg.set('group hackers', 'members', 'wsmith')
    gen = group.getMembership(config=cfg, user='jdoe')
    eq(gen.next(), 'all')
    assert_raises(StopIteration, gen.next)
Beispiel #18
0
class Config(object):

    def __init__(self):
        self._load()
        self._read()

    def _load(self):
        path = os.path.join(os.getcwd(), 'syncer.cfg')
        self.config = RawConfigParser()
        self.config.read(path)

    def _read(self):
        self.sync_crons = self._get_multiline(
            'cron', 'sync', [])
        self.unison_executable = self._get(
            'unison', 'executable',
            '/usr/local/bin/unison')

    def _get(self, section, option, default):
        if not self.config.has_option(section, option):
            return default

        value = self.config.get(section, option)
        if value:
            return value
        else:
            return default

    def _get_multiline(self, section, option, default):
        value = self._get(section, option, default)
        if value is not default:
            return value.strip().split('\n')
        else:
            return value
Beispiel #19
0
def __config_to_dict(conf_fp):
	config_parser = RawConfigParser()
	config_parser.read(conf_fp)
	config = {}

	# shortcut, but everything comes in as a str
	[config.__setitem__(section, dict(config_parser.items(section)))
		for section in config_parser.sections()]

	# convert bools
	b = bool(int(config['loris.Loris']['enable_caching']))
	config['loris.Loris']['enable_caching'] = b

	b = bool(int(config['loris.Loris']['redirect_conneg']))
	config['loris.Loris']['redirect_conneg'] = b

	b = bool(int(config['loris.Loris']['redirect_base_uri']))
	config['loris.Loris']['redirect_base_uri'] = b

	b = bool(int(config['loris.Loris']['redirect_cannonical_image_request']))
	config['loris.Loris']['redirect_cannonical_image_request'] = b

	b = bool(int(config['loris.Loris']['enable_cors']))
	config['loris.Loris']['enable_cors'] = b

	# convert lists
	l = map(string.strip, config['loris.Loris']['cors_whitelist'].split(','))
	config['loris.Loris']['cors_whitelist'] = l

	# convert transforms.*.target_formats to lists
	for tf in __transform_sections_from_config(config):
		config[tf]['target_formats'] = [s.strip() for s in config[tf]['target_formats'].split(',')]

	return config
	def __init__(self, conf_path = '..'):
		'''
		初始化配置文件
		'''
		#数据库、redis等配置
		self.conncfg = '%s/conf/connect.cfg' % (conf_path)
		#日志文件配置 
		self.logcfg = '%s/conf/logger.conf' % (conf_path)
		logging.config.fileConfig(self.logcfg)
		self.logger = logging.getLogger('Request')
		#sql语句配置
		self.sqlcfg = '%s/conf/sql.cfg' % (conf_path)

		self.config = RawConfigParser()
		self.config.read(self.conncfg)
		self.con_lock = threading.Lock()
		self.sqlfig = RawConfigParser()
		self.sqlfig.read(self.sqlcfg)		

		self.custid_ip_count = 0
		self.ip_in_db = 0
		self.tel_in_spamlist = 0
		self.permid_custid_count = 0
		self.tel_total = 0
		self.tel_custid_count = 0
Beispiel #21
0
    def from_config_file(self, config_file, allow_profile = False):
        """
        Get the settings from a configuration file.

        :param config_file: Configuration file.
        :type config_file: str

        :param allow_profile: True to allow reading the profile name
            from the config file, False to forbid it. Global config
            files should allow setting a default profile, but profile
            config files should not, as it wouldn't make sense.
        """
        parser = RawConfigParser()
        parser.read(config_file)
        if parser.has_section("golismero"):
            options = { k:v for k,v in parser.items("golismero") if v }
            if "profile" in options:
                if allow_profile:
                    self.profile = options["profile"]
                    self.profile_file = get_profile(self.profile)
                else:
                    del options["profile"]
            for k in self._forbidden_:
                if k in options:
                    del options[k]
            if options:
                self.from_dictionary(options)
Beispiel #22
0
    def __init__(self, config_file, config_type=None):
        """
        Init a fits_reduce config instance.

        Parameters
        ----------
        config_file : string
            Path to the config file

        config_type : string
            Means which script is calling this object.

        See Also
        --------
        ConfigParser.RawConfigParser
        """
        RawConfigParser.__init__(self)

        # Permitted units for the images
        self._permitted_image_units = ['adu', 'electron', 'photon', '1', '']

        # Check if file exists
        if not os.path.exists(config_file):
            raise IOError('File %s does not exists.' % config_file)
        # Load configfile
        self.read(config_file)
        if config_type == 'reducer':
            self.ret = self._load_reducer_vars()
        else:
            print 'Error! Invalid config_type %s.' % config_type
Beispiel #23
0
 def parseSettings(self):
     try:
         self.prnt("Reading in settings from settings.ini...")
         oldchans = self.joinchans
         settings = ConfigParser()
         settings.read("settings.ini")
         channels = settings.items("channels")
         for element in self.joinchans:
             self.joinchans.remove(element)
         for element in channels:
             self.joinchans.append(element)
             if not element in oldchans and not self.firstjoin == 1:
                 self.join("#%s" % element[0])
         for element in oldchans:
             if element not in self.joinchans and not self.firstjoin == 1:
                 self.part("#%s" % element[0])
         self.password = settings.get("info", "password")
         if not self.firstjoin == 1:
             self.sendmsg("nickserv", "IDENTIFY %s" % self.password)
         self.loginpass = settings.get("info", "loginpass")
         self.control_char = settings.get("info", "control_character")
         self.data_dir = settings.get("info", "data_folder")
         self.index_file = settings.get("info", "index_file")
         self.api_key = settings.get("mcbans", "api_key")
     except:
         return False
     else:
         self.prnt("Done!")
         return True
Beispiel #24
0
    def get_items(self):
        parameters = {}
        mysql_config = RawConfigParser()

        sections = []

        try:
            contents = file(path(MY_CNF))
            lines = contents.readlines()

            # Workaround for `allow_no_value` (which is available in only Python 2.7+).
            body = ''
            for line in lines:
                stripped_line = line.strip()
                if not stripped_line or stripped_line[0] in ('#', ';'):
                    pass

                elif line[0] != '[' and line[-1] != ']' and \
                   '=' not in line:
                    line = '%s=\n' % line.rstrip('\n')

                body += line

            mysql_config.readfp(cStringIO.StringIO(body))

            sections = mysql_config.sections()
        except IOError:
            #sys.exit("Notice: Cannot open MySQL configuration file '%s'" % MY_CNF)
            print "Notice: Cannot open MySQL configuration file '%s'" % MY_CNF
        except ParsingError, error:
            print "Notice: Cannot parse PHP configuration file '%s'\n%s" % (PHP_INI, error)
Beispiel #25
0
def do_10_install_packages():
  """Install or remove packages (as per debfix/debfix-packages.conf"""
  from ConfigParser import RawConfigParser
  config = RawConfigParser(allow_no_value=True)
  config.read(data_dir + 'debfix-packages.conf')
  sections = config.sections()
  run('apt-get -y -q update')
  run('apt-get -y -q --allow-unauthenticated install aptitude debian-archive-keyring deb-multimedia-keyring')
  run('apt-get -y -q update')
  if user_choice('Upgrade all upgradable packages'):
    run('aptitude -y -q full-upgrade')
  marked = {'install':'', 'remove':'', 'sections':''}
  for section in sections:
    question = "{} packages from '{}' section".format('Install' if section != 'remove' else 'Remove', section)
    packages = ' '.join(i[0] for i in config.items(section))
    while True:
      choice = user_choice(question, other_choices='?')
      if choice == '?':
        log.info("Section '{}' contains packages: {}".format(section, packages))
        continue
      if choice:
        marked['sections'] += section + ' '
        if section == 'remove':
          marked['remove'] += packages + ' '
        else:
          marked['install'] += packages + ' '
      break
  if user_choice('Install: {install}\nRemove: {remove}\nApply changes'.format(**marked)):
    _apt_install_packages(marked)
    # due to assume-yes-based decisions, some packages may not be successfully installed (yet), retry
    _apt_install_packages(marked, second_time_around=True)
  run('aptitude -y -q clean')
  log.info('Done installing packages')
Beispiel #26
0
 def __init__(self, node_type, config_file):
     self.__params = self.__get_fields(self.CommonConfig)
     self.node_type = node_type
     if node_type == NodeType.VXRD:
         self.__params.update(self.__get_fields(self.VxrdConfig))
         pidfile = DefaultPidFile.VXRD
         udsfile = DefaultUdsFile.VXRD
     elif node_type == NodeType.VXSND:
         self.__params.update(self.__get_fields(self.VxsndConfig))
         pidfile = DefaultPidFile.VXSND
         udsfile = DefaultUdsFile.VXSND
     else:
         raise RuntimeError('Invalid node type %s. Acceptable values are '
                            '%s' % (node_type, ', '.join(NodeType.VALUES)))
     default_dict = {field.name: field.default for field in self.__params}
     config_parser = RawConfigParser(defaults=default_dict,
                                     allow_no_value=True)
     config_parser.read([config_file, config_file + '.override'])
     for field in self.__params:
         try:
             value = config_parser.get(field.section, field.name)
         except NoSectionError:
             value = field.default
         setattr(self, field.name, field(value))
     self.pidfile = self.pidfile or pidfile
     self.udsfile = self.udsfile or udsfile
Beispiel #27
0
class HostTest(unittest.TestCase):
    """
    Test various host configurations
    """
    
    def setUp(self):
        optparser = BaseOptions()
        optparser.parseOptions(['dummyfile.xml', '--debug=%s' % logging._levelNames[log.level].lower()])

        self.defaults = RawConfigParser()
        configfiles = self.defaults.read(TESTCONF)
        self.defaults.get('global', 'dns_domain_name')
        if len(configfiles) == 0:
            raise ValueError("Cannot load configuration file: %s" % optparser.options.configfile)

        self.sitea = Site()
        self.sitea.name = 'sitea'
        self.sitea.type = 'primary'
        self.sitea.location = 'testlab'

    def test_empty_host(self):
        """
        Test an empty host node
        """
        xmlfile = os.path.join(XML_FILE_LOCATION, 'host_empty.xml')
        tree = etree.parse(xmlfile)
        node = tree.getroot()
        self.failUnlessRaises(KeyError, host.create_host_from_node, node, self.defaults, self.sitea)
        
    def test_named_host(self):
        """
        Test a host node with just a name
        """
        xmlfile = os.path.join(XML_FILE_LOCATION, 'host_named.xml')
        tree = etree.parse(xmlfile)
        node = tree.getroot()
        self.failUnlessRaises(KeyError, host.create_host_from_node, node, self.defaults, self.sitea)

    def test_named_host_os(self):
        """
        Test a host node with just a name
        """
        xmlfile = os.path.join(XML_FILE_LOCATION, 'host_named_os.xml')
        tree = etree.parse(xmlfile)
        node = tree.getroot()
        hostobj = host.create_host_from_node(node, self.defaults, self.sitea)
        self.failUnlessEqual(hostobj.name, 'fred')
        self.failUnlessEqual(hostobj.operatingsystem, 'Linux')

    def test_named_host_os_platform(self):
        """
        Test a host node with just a name
        """
        xmlfile = os.path.join(XML_FILE_LOCATION, 'host_named_os_platform.xml')
        tree = etree.parse(xmlfile)
        node = tree.getroot()
        hostobj = host.create_host_from_node(node, self.defaults, self.sitea)
        self.failUnlessEqual(hostobj.name, 'fred')
        self.failUnlessEqual(hostobj.operatingsystem, 'Linux')
        self.failUnlessEqual(hostobj.platform, 'intel')
 def parser_to_dict(self, filename):
     parser = RawConfigParser()
     parser.readfp(open(filename, "r"))
     dict_ = {}
     options = parser.options("LIB")
     for option in options: dict_[option] = parser.get("LIB", option)
     return dict_
Beispiel #29
0
 def backend_exists(self, name):
     """
     Return True if the backend exists in config.
     """
     config = RawConfigParser()
     config.read(self.confpath)
     return name in config.sections()
    def get_option(self, key, default=NoDefault, asbool=False, section="options"):
        config = RawConfigParser()
        fp = StringIO(self.config)
        try:
            config.readfp(fp)
        except MissingSectionHeaderError:
            if default is NoDefault:
                raise
            return default
        try:
            value = config.get(section, key)
        except (NoOptionError, NoSectionError):
            if default is NoDefault:
                raise
            return default

        if not asbool:
            return value.strip()

        value = value.lower()
        if value in ("1", "true", "t", "yes", "y", "on"):
            return True
        elif value in ("0", "false", "f", "no", "n", "off"):
            return False
        else:
            raise TypeError("Cannot convert to bool: %s" % value)