Beispiel #1
0
def _change_dhcp_config(interface, enable_dhcp=True, filename=INTERFACES_CONFIG):
    '''
    Enable or disable dhcp for an interface which isn't a service (in a config file)

    :param interface: interface label
    :param enable_dhcp: True to enable dhcp and False to disable dhcp. Default is True
    :param filename: Config file name. Default is INTERFACES_CONFIG.
    '''
    parser = configparser.ConfigParser()
    parser.optionxform = str
    if os.path.exists(filename):
        try:
            with salt.utils.files.fopen(filename, 'r') as config_file:
                parser.readfp(config_file)
        except configparser.MissingSectionHeaderError:
            pass
    interface = pyiface.Interface(name=interface)
    hwaddr = interface.hwaddr[:-1]
    hwaddr_section_number = ''.join(hwaddr.split(':'))
    if parser.has_section('service_{0}'.format(hwaddr_section_number)):
        parser.remove_section('service_{0}'.format(hwaddr_section_number))
    parser.add_section('service_{0}'.format(hwaddr_section_number))
    parser.set('service_{0}'.format(hwaddr_section_number), 'MAC', hwaddr)
    parser.set('service_{0}'.format(hwaddr_section_number), 'Name', 'ethernet_cable_{0}'.format(hwaddr_section_number))
    parser.set('service_{0}'.format(hwaddr_section_number), 'Type', 'ethernet')
    if enable_dhcp:
        parser.set('service_{0}'.format(hwaddr_section_number), 'IPv4.Method', 'dhcp')
        parser.set('service_{0}'.format(hwaddr_section_number), 'AutoConnect', 'true')
        parser.set('service_{0}'.format(hwaddr_section_number), 'Nameservers', '\'\'')
    else:
        parser.set('service_{0}'.format(hwaddr_section_number), 'IPv4', 'off')
    with salt.utils.files.fopen(filename, 'w') as config_file:
        parser.write(config_file)
    return True
Beispiel #2
0
def serialize(obj, **options):
    '''
    Serialize Python data to a configparser formatted string or file.

    :param obj: the data structure to serialize
    :param options: options given to lower configparser module.
    '''

    try:
        if not isinstance(obj, dict):
            raise TypeError(
                "configparser can only serialize dictionaries, not {0}".format(
                    type(obj)))
        fp = options.pop('fp', None)
        if six.PY3:
            cp = configparser.ConfigParser(**options)
        else:
            cp = configparser.SafeConfigParser(**options)
        _read_dict(cp, obj)

        if fp:
            return cp.write(fp)
        else:
            s = six.moves.StringIO()
            cp.write(s)
            return s.getvalue()
    except Exception as error:
        raise SerializationError(error)
Beispiel #3
0
def _enable_dhcp(interface):
    '''
    Enable dhcp for an interface which isn't a service

    :param interface: interface label
    '''
    parser = configparser.ConfigParser()
    parser.optionxform = str
    if os.path.exists(INTERFACES_CONFIG):
        try:
            with salt.utils.files.fopen(INTERFACES_CONFIG, 'r') as config_file:
                parser.readfp(config_file)
        except configparser.MissingSectionHeaderError:
            pass
    interface = pyiface.Interface(name=interface)
    hwaddr = interface.hwaddr[:-1]
    hwaddr_section_number = ''.join(hwaddr.split(':'))
    if parser.has_section('service_{0}'.format(hwaddr_section_number)):
        parser.remove_section('service_{0}'.format(hwaddr_section_number))
    parser.add_section('service_{0}'.format(hwaddr_section_number))
    parser.set('service_{0}'.format(hwaddr_section_number), 'MAC', hwaddr)
    parser.set('service_{0}'.format(hwaddr_section_number), 'Name',
               'ethernet_cable_{0}'.format(hwaddr_section_number))
    parser.set('service_{0}'.format(hwaddr_section_number), 'IPv4.method',
               'dhcp')
    parser.set('service_{0}'.format(hwaddr_section_number), 'AutoConnect',
               'true')
    with salt.utils.files.fopen(INTERFACES_CONFIG, 'w') as config_file:
        parser.write(config_file)
    return True
Beispiel #4
0
def deserialize(stream_or_string, **options):
    '''
    Deserialize any string or stream like object into a Python data structure.

    :param stream_or_string: stream or string to deserialize.
    :param options: options given to lower configparser module.
    '''

    if six.PY3:
        cp = configparser.ConfigParser(**options)
    else:
        cp = configparser.SafeConfigParser(**options)

    try:
        if not isinstance(stream_or_string, (bytes, six.string_types)):
            if six.PY3:
                cp.read_file(stream_or_string)
            else:
                cp.readfp(stream_or_string)
        else:
            if six.PY3:
                cp.read_file(six.moves.StringIO(stream_or_string))
            else:
                # python2's ConfigParser cannot parse a config from a string
                cp.readfp(six.moves.StringIO(stream_or_string))
        data = {}
        for section_name in cp.sections():
            section = {}
            for k, v in cp.items(section_name):
                section[k] = v
            data[section_name] = section
        return data
    except Exception as error:
        raise DeserializationError(error)
Beispiel #5
0
def _get_static_info(interface):
    '''
    Return information about an interface from config file.

    :param interface: interface label
    '''
    parser = configparser.ConfigParser()
    if os.path.exists(INTERFACES_CONFIG):
        try:
            with salt.utils.fopen(INTERFACES_CONFIG, 'r') as config_file:
                parser.read_file(config_file)
        except configparser.MissingSectionHeaderError:
            pass
    data = {
        'connectionid': interface.name,
        'label': interface.name,
        'hwaddr': interface.hwaddr[:-1],
        'up': False,
        'ipv4': {
            'supportedrequestmodes': ['static', 'dhcp_linklocal'],
            'requestmode': 'static'
        },
        'wireless': False
    }
    hwaddr_section_number = ''.join(data['hwaddr'].split(':'))
    if parser.has_section('interface_{0}'.format(hwaddr_section_number)):
        ipv4_information = parser.get('interface_{0}'.format(hwaddr_section_number), 'IPv4').split('/')
        data['ipv4']['address'] = ipv4_information[0]
        data['ipv4']['dns'] = parser.get('interface_{0}'.format(hwaddr_section_number), 'Nameservers').split(',')
        data['ipv4']['netmask'] = ipv4_information[1]
        data['ipv4']['gateway'] = ipv4_information[2]
    return data
Beispiel #6
0
def _get_configured_repos():
    '''
    Get all the info about repositories from the configurations.
    '''

    repos_cfg = configparser.ConfigParser()
    repos_cfg.read([REPOS + '/' + fname for fname in os.listdir(REPOS)])

    return repos_cfg
Beispiel #7
0
def _create_cp_object(**options):
    '''
    build the configparser object
    '''
    preserve_case = options.pop('preserve_case', False)

    if six.PY3:
        cp = configparser.ConfigParser(**options)
        if preserve_case:
            cp.optionxform = str
    else:
        cp = configparser.SafeConfigParser(**options)
        if preserve_case:
            cp.optionxform = str
    return cp
Beispiel #8
0
def _configure_static_interface(interface, **settings):
    """
    Configure an interface that is not detected as a service by Connman (i.e. link is down)

    :param interface: interface label
    :param settings:
            - ip
            - netmask
            - gateway
            - dns
            - name
    :return: True if settings were applied successfully.
    :rtype: bool
    """
    interface = pyiface.Interface(name=interface)
    parser = configparser.ConfigParser()
    if os.path.exists(INTERFACES_CONFIG):
        try:
            with salt.utils.files.fopen(INTERFACES_CONFIG, "r") as config_file:
                parser.readfp(config_file)
        except configparser.MissingSectionHeaderError:
            pass
    hwaddr = interface.hwaddr[:-1]
    hwaddr_section_number = "".join(hwaddr.split(":"))
    if not parser.has_section("interface_{0}".format(hwaddr_section_number)):
        parser.add_section("interface_{0}".format(hwaddr_section_number))
    ip_address = settings.get("ip", "0.0.0.0")
    netmask = settings.get("netmask", "0.0.0.0")
    gateway = settings.get("gateway", "0.0.0.0")
    dns_servers = settings.get("dns", "")
    name = settings.get("name",
                        "ethernet_cable_{0}".format(hwaddr_section_number))
    parser.set(
        "interface_{0}".format(hwaddr_section_number),
        "IPv4",
        "{0}/{1}/{2}".format(ip_address, netmask, gateway),
    )
    parser.set("interface_{0}".format(hwaddr_section_number), "Nameservers",
               dns_servers)
    parser.set("interface_{0}".format(hwaddr_section_number), "Name", name)
    parser.set("interface_{0}".format(hwaddr_section_number), "MAC", hwaddr)
    parser.set("interface_{0}".format(hwaddr_section_number), "Type",
               "ethernet")
    with salt.utils.files.fopen(INTERFACES_CONFIG, "w") as config_file:
        parser.write(config_file)
    return True
Beispiel #9
0
def _configure_static_interface(interface, **settings):
    '''
    Configure an interface that is not detected as a service by Connman (i.e. link is down)

    :param interface: interface label
    :param settings:
            - ip
            - netmask
            - gateway
            - dns
            - name
    :return: True if settings were applied successfully.
    :rtype: bool
    '''
    interface = pyiface.Interface(name=interface)
    parser = configparser.ConfigParser()
    parser.optionxform = str
    if os.path.exists(INTERFACES_CONFIG):
        try:
            with salt.utils.files.fopen(INTERFACES_CONFIG, 'r') as config_file:
                parser.readfp(config_file)
        except configparser.MissingSectionHeaderError:
            pass
    hwaddr = interface.hwaddr[:-1]
    hwaddr_section_number = ''.join(hwaddr.split(':'))
    if parser.has_section('service_{0}'.format(hwaddr_section_number)):
        parser.remove_section('service_{0}'.format(hwaddr_section_number))
    parser.add_section('service_{0}'.format(hwaddr_section_number))
    ip_address = settings.get('ip', '0.0.0.0')
    netmask = settings.get('netmask', '0.0.0.0')
    gateway = settings.get('gateway', '0.0.0.0')
    dns_servers = settings.get('dns', '\'\'')
    name = settings.get('name',
                        'ethernet_cable_{0}'.format(hwaddr_section_number))
    parser.set('service_{0}'.format(hwaddr_section_number), 'IPv4',
               '{0}/{1}/{2}'.format(ip_address, netmask, gateway))
    parser.set('service_{0}'.format(hwaddr_section_number), 'Nameservers',
               dns_servers)
    parser.set('service_{0}'.format(hwaddr_section_number), 'Name', name)
    parser.set('service_{0}'.format(hwaddr_section_number), 'MAC', hwaddr)
    parser.set('service_{0}'.format(hwaddr_section_number), 'Type', 'ethernet')
    parser.set('service_{0}'.format(hwaddr_section_number), 'IPv4.method',
               'manual')
    with salt.utils.files.fopen(INTERFACES_CONFIG, 'w') as config_file:
        parser.write(config_file)
    return True
Beispiel #10
0
def _read_config(conf_file=None):
    '''
    Reads the config file using configparser
    '''
    if conf_file is None:
        paths = ('/etc/supervisor/supervisord.conf', '/etc/supervisord.conf')
        for path in paths:
            if os.path.exists(path):
                conf_file = path
                break
    if conf_file is None:
        raise CommandExecutionError('No suitable config file found')
    config = configparser.ConfigParser()
    try:
        config.read(conf_file)
    except (IOError, OSError) as exc:
        raise CommandExecutionError('Unable to read from {0}: {1}'.format(
            conf_file, exc))
    return config
Beispiel #11
0
    def test_repo_value_info(self):
        '''
        Tests if repo info is properly parsed.

        :return:
        '''
        repos_cfg = configparser.ConfigParser()
        for cfg in ['zypper-repo-1.cfg', 'zypper-repo-2.cfg']:
            repos_cfg.readfp(six.moves.StringIO(get_test_data(cfg)))

        for alias in repos_cfg.sections():
            r_info = zypper._get_repo_info(alias, repos_cfg=repos_cfg)
            self.assertEqual(type(r_info['type']), type(None))
            self.assertEqual(type(r_info['enabled']), bool)
            self.assertEqual(type(r_info['autorefresh']), bool)
            self.assertEqual(type(r_info['baseurl']), str)
            self.assertEqual(r_info['type'], None)
            self.assertEqual(r_info['enabled'], alias == 'SLE12-SP1-x86_64-Update')
            self.assertEqual(r_info['autorefresh'], alias == 'SLE12-SP1-x86_64-Update')
Beispiel #12
0
def _remove_interface_section(interface):
    '''
    Remove interface section from connman config file
    '''
    parser = configparser.ConfigParser()
    parser.optionxform = str
    if os.path.exists(INTERFACES_CONFIG):
        try:
            with salt.utils.files.fopen(INTERFACES_CONFIG, 'r') as config_file:
                parser.readfp(config_file)
        except configparser.MissingSectionHeaderError:
            pass
    interface = pyiface.Interface(name=interface)
    hwaddr = interface.hwaddr[:-1]
    hwaddr_section_number = ''.join(hwaddr.split(':'))
    if parser.has_section('service_{0}'.format(hwaddr_section_number)):
        parser.remove_section('service_{0}'.format(hwaddr_section_number))
    with salt.utils.files.fopen(INTERFACES_CONFIG, 'w') as config_file:
        parser.write(config_file)
    return True
Beispiel #13
0
def _change_dhcp_config(interface, enable_dhcp=True, filename=INTERFACES_CONFIG):
    """
    Enable or disable dhcp for an interface which isn't a service (in a config file)

    :param interface: interface label
    :param enable_dhcp: True to enable dhcp and False to disable dhcp. Default is True
    :param filename: Config file name. Default is INTERFACES_CONFIG.
    """
    parser = configparser.ConfigParser()
    parser.optionxform = str
    if os.path.exists(filename):
        try:
            with salt.utils.files.fopen(filename, "r") as config_file:
                parser.readfp(config_file)
        except configparser.MissingSectionHeaderError:
            pass
    interface = pyiface.Interface(name=interface)
    hwaddr = interface.hwaddr[:-1]
    hwaddr_section_number = "".join(hwaddr.split(":"))
    if parser.has_section("service_{}".format(hwaddr_section_number)):
        parser.remove_section("service_{}".format(hwaddr_section_number))
    parser.add_section("service_{}".format(hwaddr_section_number))
    parser.set("service_{}".format(hwaddr_section_number), "MAC", hwaddr)
    parser.set(
        "service_{}".format(hwaddr_section_number),
        "Name",
        "ethernet_cable_{}".format(hwaddr_section_number),
    )
    parser.set("service_{}".format(hwaddr_section_number), "Type", "ethernet")
    if enable_dhcp:
        parser.set("service_{}".format(hwaddr_section_number), "IPv4.Method", "dhcp")
        parser.set("service_{}".format(hwaddr_section_number), "AutoConnect", "true")
        parser.set("service_{}".format(hwaddr_section_number), "Nameservers", "''")
    else:
        parser.set("service_{}".format(hwaddr_section_number), "IPv4", "off")
    with salt.utils.files.fopen(filename, "w") as config_file:
        parser.write(config_file)
    return True
Beispiel #14
0
def _change_connman_backlist(interface, add=True):
    '''
    Remove or add an interface to connman blacklist

    :param interface: interface label
    :param add: True to add interface to blacklist, False otherwise. Default is True.
    '''
    parser = configparser.ConfigParser()
    parser.optionxform = str
    if os.path.exists(CONNMAN_MAIN_CONFIG):
        try:
            with salt.utils.files.fopen(CONNMAN_MAIN_CONFIG,
                                        'r') as config_file:
                parser.readfp(config_file)
        except configparser.MissingSectionHeaderError:
            pass
    if not parser.has_section('General'):
        parser.add_section('General')
        parser.set('General', 'AlwaysConnectedTechnologies',
                   'wifi,ehternet,bluetooth')
    if parser.has_option('General', 'NetworkInterfaceBlacklist'):
        blacklist = parser.get('General', 'NetworkInterfaceBlacklist')
        blacklist = [] if blacklist == '' else blacklist.split(',')
        if add:
            blacklist.append(interface)
        else:
            blacklist.remove(interface)
        blacklist = ','.join(blacklist)
    else:
        blacklist = interface if add else ""
    parser.set('General', 'NetworkInterfaceBlacklist', blacklist)
    with salt.utils.files.fopen(CONNMAN_MAIN_CONFIG, 'w') as config_file:
        parser.write(config_file)
    if add:
        return _remove_interface_section(interface)
    return _enable_dhcp(interface)