Ejemplo n.º 1
0
    def __init__(self, config_file, validate=True, credentials_only=False):
        self.config_file = config_file
        self.cfg = ConfigParser.ConfigParser()
        self.read_config()
        self.as_config = AutoscaleConfig()
        self.lc_config = LaunchConfig()
        self.ras_config = AutoscalerConfig()
        self.username = None
        self.api_key = None
        self.region = None
        self.credentials_file = None

        self.parse_credentials()
        if not credentials_only:
            self.parse_config()
        if validate and not credentials_only:
            self.validate()
Ejemplo n.º 2
0
class config(object):
    """ Holds all variables related to our configuration as attributes
        Parses configuration file and populates instances of AutoscaleConfig,
        and LaunchConfig.
    """

    def __init__(self, config_file, validate=True, credentials_only=False):
        self.config_file = config_file
        self.cfg = ConfigParser.ConfigParser()
        self.read_config()
        self.as_config = AutoscaleConfig()
        self.lc_config = LaunchConfig()
        self.ras_config = AutoscalerConfig()
        self.username = None
        self.api_key = None
        self.region = None
        self.credentials_file = None

        self.parse_credentials()
        if not credentials_only:
            self.parse_config()
        if validate and not credentials_only:
            self.validate()

    def validate(self):
        self.lc_config.validate()
        self.as_config.validate()
        self.ras_config.validate()

    def get(self, section, key):
        try:
            ret = self.cfg.get(section, key)
            if isinstance(ret, str):
                return ret.strip()
            return ret
        except (ConfigParser.NoOptionError, ConfigParser.ConfigParser):
            return None

    def get_credentials(self):
        return (self.username, self.api_key, self.region)

    def set_config_option(self, section, key, value):
        """ Sets an attribute of a config class and
            writes they key and value out to the config file
            under the appropriate section
        """
        if not self.cfg.has_section(section):
            self.cfg.add_section(section)

        if isinstance(value, str) or isinstance(value, unicode):
            value = "'%s'" % value
        if section == 'autoscale':
            setattr(self.as_config, key, value)
        elif section == 'launch_configuration':
            setattr(self.lc_config, key, value)
        elif section == 'rax-autoscaler':
            setattr(self.ras_config, key, value)
        self.cfg.set(section, key, value)
        self.cfg.write(open(self.config_file, 'w'))

    def get_keys(self, section):
        ret = []
        try:
            for k, v in self.cfg.items(section):
                ret.append(k)
        except (AttributeError, ConfigParser.NoSectionError):
            return []

        return ret

    def read_config(self, config_file=None):
        """ Reads the config file into self.cfg instance """
        config_file = config_file if config_file else self.config_file
        try:
            self.cfg.readfp(open(config_file, 'r'))
        except IOError as ex:
            raise Exception("Unable to open config file: %s" % ex)

    def parse_credentials(self, config_file=None):
        if self.username and self.api_key and self.region:
            return

        config_file = config_file if config_file else self.config_file
        self.read_config(config_file)
        # We need to be able to read both our config as well as a pyrax one
        section = 'rackspace_cloud' if self.cfg.has_section('rackspace_cloud')\
                  else 'cloud'

        # First check whether credentials are specified explicitly
        try:
            self.username = self.cfg.get(section, 'username').strip("'")
            self.api_key = self.cfg.get(section, 'api_key').strip("'")
            self.region = self.cfg.get(section, 'region').strip("'")
            # We don't want to write these out to the config file...
            self.cfg.remove_section(section)
            return
        except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
            # Ignore if they aren't
            pass

        # And check for a credentials_file key, and re-parse using that file
        # if found. If it isn't, bomb out, we have no credentials
        try:
            self.credentials_file = ast.literal_eval(self.cfg.get(section,
                                                     'credentials_file'))
            self.parse_credentials(self.credentials_file)
        except ConfigParser.NoSectionError:
            print_msg("Config file %s does not contain a 'cloud' or"
                      " 'rackspace_cloud' section" % config_file,
                      bcolors.FAIL)
            exit(1)
        except ConfigParser.NoOptionError:
            print_msg("Config file %s does not contain the keys username,"
                      " api_key, region or credentials_file" % config_file,
                      bcolors.FAIL)
            exit(1)

        self.cfg.remove_section(section)

    def parse_config(self):

        self.read_config()
        conf = {}

        for section in self.cfg.sections():
            if section not in conf:
                conf[section] = {}
            for key, val in self.cfg.items(section):
                try:
                    if section == 'cloud':
                        getattr(self, key)
                        setattr(self, key, ast.literal_eval(val))

                    elif section == 'autoscale':
                        getattr(self.as_config, key)
                        setattr(self.as_config, key, ast.literal_eval(val))

                    elif section == 'launch-configuration':
                        getattr(self.lc_config, key)
                        setattr(self.lc_config, key, ast.literal_eval(val))

                    elif section == 'rax-autoscaler':
                        getattr(self.ras_config, key)
                        setattr(self.ras_config, key, ast.literal_eval(val))

                    conf[section][key] = val
                except AttributeError:
                    raise Exception("Config file parsing failed. Unknown key"
                                    " '%s' found in section '%s'" % (
                                        key, section))
                except (ValueError, SyntaxError):
                    raise Exception("Config file parsing failed. Key '%s' in"
                                    " section %s appears to have a malformed"
                                    " value (enclose strings in quotes, lists"
                                    " in [] and dictionaries in {} ): %s" % (
                                        key, section, val))
        return conf

    def get_autoscale_config(self):
        return self.as_config

    def get_launch_config(self):
        return self.lc_config