예제 #1
0
    def __init__(self, interface, ip, prefix_or_mask, broadcast, router=None,
                 connectivity_url=None):
        """Setup context manager and validate call signature.

        @param interface: Name of the network interface to bring up.
        @param ip: IP address to assign to the interface.
        @param prefix_or_mask: Either netmask of the format X.X.X.X or an int
            prefix.
        @param broadcast: Broadcast address for the IPv4 network.
        @param router: Optionally the default gateway IP.
        @param connectivity_url: Optionally, a URL to verify if a usable
           connection already exists.
        """
        if not all([interface, ip, prefix_or_mask, broadcast]):
            raise ValueError(
                'Cannot init network on {0} with {1}/{2} and bcast {3}'.format(
                    interface, ip, prefix_or_mask, broadcast))
        try:
            self.prefix = mask_to_net_prefix(prefix_or_mask)
        except ValueError as e:
            raise ValueError(
                'Cannot setup network: {0}'.format(e))

        self.connectivity_url = connectivity_url
        self.interface = interface
        self.ip = ip
        self.broadcast = broadcast
        self.router = router
        self.cleanup_cmds = []  # List of commands to run to cleanup state.
예제 #2
0
    def __init__(self, interface, ip, prefix_or_mask, broadcast, router=None,
                 connectivity_url=None, static_routes=None):
        """Setup context manager and validate call signature.

        @param interface: Name of the network interface to bring up.
        @param ip: IP address to assign to the interface.
        @param prefix_or_mask: Either netmask of the format X.X.X.X or an int
            prefix.
        @param broadcast: Broadcast address for the IPv4 network.
        @param router: Optionally the default gateway IP.
        @param connectivity_url: Optionally, a URL to verify if a usable
           connection already exists.
        @param static_routes: Optionally a list of static routes from DHCP
        """
        if not all([interface, ip, prefix_or_mask, broadcast]):
            raise ValueError(
                'Cannot init network on {0} with {1}/{2} and bcast {3}'.format(
                    interface, ip, prefix_or_mask, broadcast))
        try:
            self.prefix = mask_to_net_prefix(prefix_or_mask)
        except ValueError as e:
            raise ValueError(
                'Cannot setup network: {0}'.format(e))

        self.connectivity_url = connectivity_url
        self.interface = interface
        self.ip = ip
        self.broadcast = broadcast
        self.router = router
        self.static_routes = static_routes
        self.cleanup_cmds = []  # List of commands to run to cleanup state.
예제 #3
0
    def gen_ipv4_route(self, nic, gateways, netmask):
        """
        Return the routes list needed to configure additional Ipv4 route
        @return (list): the route list to configure the gateways
        @param nic (NicBase): the nic to configure
        @param gateways (str list): the list of gateways
        """
        route_list = []

        cidr = mask_to_net_prefix(netmask)

        for gateway in gateways:
            destination = "%s/%d" % (gen_subnet(gateway, netmask), cidr)
            route_list.append({'destination': destination,
                               'type': 'route',
                               'gateway': gateway,
                               'metric': 10000})

        return route_list
예제 #4
0
    def _write_network(self, settings):
        entries = net_util.translate_network(settings)
        LOG.debug("Translated ubuntu style network settings %s into %s",
                  settings, entries)
        route_entries = []
        route_entries = translate_routes(settings)
        dev_names = entries.keys()
        dev_index = 10
        nameservers = []
        searchdomains = []
        # Format for systemd
        for (dev, info) in entries.items():
            if 'dns-nameservers' in info:
                nameservers.extend(info['dns-nameservers'])
            if 'dns-search' in info:
                searchdomains.extend(info['dns-search'])
            if dev == 'lo':
                continue
            net_fn = network_file_name(self.network_conf_dir, dev)
            if not net_fn:
                net_fn = self.network_conf_dir + \
                    str(dev_index) + '-' + dev + '.network'
            else:
                net_fn = self.network_conf_dir + net_fn

            dhcp_enabled = 'no'
            if info.get('bootproto') == 'dhcp':
                if settings.find('inet dhcp') >= 0 and settings.find('inet6 dhcp') >= 0:
                    dhcp_enabled = 'yes'
                else:
                    dhcp_enabled = 'ipv6' if info.get(
                        'inet6') == True else 'ipv4'

            net_cfg = {
                'Name': dev,
                'DHCP': dhcp_enabled,
            }

            if info.get('hwaddress'):
                net_cfg['MACAddress'] = info.get('hwaddress')
            if info.get('address'):
                net_cfg['Address'] = "%s" % (info.get('address'))
                if info.get('netmask'):
                    net_cfg['Address'] += "/%s" % (
                        mask_to_net_prefix(info.get('netmask')))
            if info.get('gateway'):
                net_cfg['Gateway'] = info.get('gateway')
            if info.get('dns-nameservers'):
                net_cfg['DNS'] = str(
                    tuple(info.get('dns-nameservers'))).replace(',', '')
            if info.get('dns-search'):
                net_cfg['Domains'] = str(
                    tuple(info.get('dns-search'))).replace(',', '')
            route_entry = []
            if dev in route_entries:
                route_entry = route_entries[dev]
                route_index = 0
                found = True
                while found:
                    route_name = 'routes.' + str(route_index)
                    if route_name in route_entries[dev]:
                        val = str(tuple(route_entries[dev][route_name])).replace(
                            ',', '')
                        if val:
                            net_cfg[route_name] = val
                    else:
                        found = False
                    route_index += 1

            if info.get('auto'):
                self._write_interface_file(net_fn, net_cfg, route_entry)

        resolve_data = []
        new_resolve_data = []
        with open(self.resolve_conf_fn, "r") as rf:
            resolve_data = rf.readlines()
        LOG.debug("Old Resolve Data\n")
        LOG.debug("%s", resolve_data)
        for item in resolve_data:
            if (nameservers and ('DNS=' in item)) or (searchdomains and ('Domains=' in item)):
                continue
            else:
                new_resolve_data.append(item)

        new_resolve_data = new_resolve_data + \
            convert_resolv_conf(nameservers, searchdomains)
        LOG.debug("New resolve data\n")
        LOG.debug("%s", new_resolve_data)
        if nameservers or searchdomains:
            util.write_file(self.resolve_conf_fn, ''.join(new_resolve_data))

        return dev_names