Exemplo n.º 1
0
 def testGetSubnetForSingle128(self):
     ip = ipaddr.IPv6Network('::1/128')
     subnets1 = [str(x) for x in ip.subnet()]
     subnets2 = [str(x) for x in ip.subnet(2)]
     self.assertEqual(subnets1, ['::1/128'])
     self.assertEqual(subnets1, subnets2)
Exemplo n.º 2
0
def search_ip(request):
    if request.method == "POST":
        form = IpSearchForm(request.POST)
        try:
            if form.is_valid():
                ip_type = form.cleaned_data['ip_type']
                search_ip = form.cleaned_data['search_ip']
                try:
                    if ip_type == '4':
                        network = ipaddr.IPv4Network(search_ip)
                    if ip_type == '6':
                        network = ipaddr.IPv6Network(search_ip)
                except ipaddr.AddressValueError, e:
                    form._errors['__all__'] = ErrorList(
                        ["Bad IPv{0} Address {1}".format(ip_type, search_ip)])
                    return render(request, 'cydhcp/cydhcp_form.html',
                                  {'form': form})
                try:
                    network = Network.objects.get(network_str=search_ip)
                    search_ip = network
                    found_exact = True
                except ObjectDoesNotExist:
                    found_exact = False
                    network = Network(ip_type,
                                      network_str=search_ip,
                                      ip_type=ip_type)
                parent = calc_parent(network)
                eldars, sub_networks = calc_networks(network)
                if ip_type == '6':
                    sip_upper, sip_lower = ipv6_to_longs(network.network.ip)
                    eip_upper, eip_lower = ipv6_to_longs(
                        network.network.broadcast)
                else:
                    sip_upper, sip_lower = 0, int(network.network.ip)
                    eip_upper, eip_lower = 0, int(network.network.broadcast)

                addrs_count = AddressRecord.objects.filter(
                    ip_upper__gte=sip_upper,
                    ip_lower__gte=sip_lower,
                    ip_upper__lte=eip_upper,
                    ip_lower__lte=eip_lower).count()

                if addrs_count > 100:
                    addrs = None  # This is too much
                else:
                    addrs = AddressRecord.objects.filter(
                        ip_upper__gte=sip_upper,
                        ip_lower__gte=sip_lower,
                        ip_upper__lte=eip_upper,
                        ip_lower__lte=eip_lower)

                ptrs_count = PTR.objects.filter(
                    ip_upper__gte=sip_upper,
                    ip_lower__gte=sip_lower,
                    ip_upper__lte=eip_upper,
                    ip_lower__lte=eip_lower).count()

                if ptrs_count > 100:
                    ptrs = None  # This is too much
                else:
                    ptrs = PTR.objects.filter(ip_upper__gte=sip_upper,
                                              ip_lower__gte=sip_lower,
                                              ip_upper__lte=eip_upper,
                                              ip_lower__lte=eip_lower)

            return render(
                request, 'cydhcp/cydhcp_results.html', {
                    'search_ip': search_ip,
                    'found_exact': found_exact,
                    'addrs': addrs,
                    'addrs_count': addrs_count,
                    'ptrs_count': ptrs_count,
                    'ptrs': ptrs,
                    'parent': parent,
                    'eldars': eldars,
                    'sub_networks': sub_networks,
                })
        except ValidationError, e:
            form._errors['__all__'] = ErrorList(e.messages)
            return render(request, 'cydhcp/cydhcp_form.html', {'form': form})
Exemplo n.º 3
0
 def setUp(self):
     self.ipv4 = ipaddr.IPv4Network('1.2.3.4/24')
     self.ipv4_hostmask = ipaddr.IPv4Network('10.0.0.1/0.255.255.255')
     self.ipv6 = ipaddr.IPv6Network('2001:658:22a:cafe:200:0:0:1/64')
Exemplo n.º 4
0
def create_ipv4_interface(label,
                          vlan_str,
                          site_str,
                          system,
                          mac,
                          domain_suffix,
                          network_str=None):
    """This is an api for creating an interface.

    :param label: The label of the interface.
    :type lavel: str
    :param vlan_str: The name of the vlan the interface should be put into.
    :type vlan_str: str
    :param site_str: The Datacenter (and possibly the Buisness Unit)
                     the vlan is in.
    :type site_str: str
    :param system: The system the interface belongs to.
    :type system: :class:`System`
    :param mac: The mac address of the new interface.
    :type mac: str
    :param domain_suffix: The suffix of the domain. This is usually
        'mozilla.com'.
    :type domain_suffix: str
    :param network_str: This is an optional paramter. If you get a
        :class:`MultipleObjectsReturned` error when trying to find a network,
        you can specify which network to use by passing the network's name
        using this kwarg. E.g. ``network="10.22.9.0/24"``
    :type network_str: str

    This function returns two values. The first value is the
    :class:`StaticInterface` instance. If the interface was succesfully created
    the second return value is meaningless. If there were errors while creating
    the interface the first value is None and the second return value is an
    ErrorDict containing errors that should be displayed to the user. Always
    check the first return value for being a NoneType.

    Using this function requires that certain objects exist in the database.
    *Understanding these objects before using this function is a good thing*.
    ::

                    <label> (.<BU>) .<DC> . <domain_suffix>

    1. This function starts by looking for a site in the site table that has a
        site path (i.e. `<BU>.<DC>` like 'relenge.scl3' or just 'scl3') equal
        to the 'site_str' paramter.

        If you get errors from this step (i.e. There is a 'site' key in the
        errors dictionary), create the site you are trying to use in the Web
        UI.


    2.  The function then looks in the site found in Step 1 for a :class:`Vlan`
        instance with a name equal to the 'vlan_str' parameter.

        If you get errors from this step (i.e. There is a 'vlan' key in the
        errors dictionary), create the vlan you are trying to use in the Web
        UI.


    3.  Using the :class:`Site` and :class:`Vlan` instance found in Step 1 & 2
        and the `domain_suffix` paramter, the function constructs the following
        string.::

            <vlan>.<site>.<domain_suffix>

        As an example, imaging we were using::

            site = relenge.scl3
            vlan = db
            domain_suffix = mozilla.com

        The constructed string would be::

            db.relenge.scl3.mozilla.com

        The function will now use this constructed string as the domain name
        for creating the interface's A/PTR records. For this reason *a domain
        with the constructed name _must_ be in the database*.

        If you get errors from this step (i.e. There is a 'domain' key in the
        errors dictionary), create the domain you are trying to use in the Web
        UI.


    4.  The function then looks at the networks associated with that vlan found
        in Step 2 and chooses the networks that are associated to the site
        found in Step 1.

        If you get errors from this step (i.e. There is a 'network' key in the
        errors dictionary), create the network you are trying to use in the Web
        UI and associate it with the vlan *and* site you are trying to use.


    5.  The function then looks for ranges within the networks found in Step 4.
        If the function finds more than one range it does not make a choice for
        you and returns an error. If the function finds only one range it looks
        for a free IP in that range while returning an error if no free IP is
        found.

    6.  Using the 'label', 'system', 'mac', and IP address found in Step 4, a
        new StaticInterface is created. If there are errors while creating the
        Interface those errors are returned. If there are no errors while
        creating the Interface the Interface is returned.
    """
    errors = ErrorDict()
    if not label:
        errors['label'] = ErrorList(["Please supply a label."])
        return None, errors

    if not system:
        errors['system'] = ErrorList(
            "Please supply a system.".format(site_str))
        return None, errors

    site = None
    for s in Site.objects.all():
        if '.'.join(s.get_site_path().split('.')) == site_str:
            site = s
            break
    if not site:
        errors['site'] = ErrorList(
            ["Site {0} does not exist".format(site_str)])
        return None, errors

    try:
        vlan = Vlan.objects.get(name=vlan_str)
    except ObjectDoesNotExist:
        errors['vlan'] = ErrorList(
            ["Vlan {0} does not exist.".format(vlan_str)])
        return None, errors

    tmp_site_str = '.'.join(s.get_site_path().split('.'))
    domain_name = vlan.name + "." + tmp_site_str + "." + domain_suffix
    try:
        domain = Domain.objects.get(name=domain_name)
    except ObjectDoesNotExist:
        errors['domain'] = ErrorList(
            ["Could not find domain "
             "{0}".format(domain_name)])
        return None, errors

    if not network_str:
        try:
            network = vlan.network_set.get(site=site)
        except MultipleObjectsReturned:
            networks = vlan.network_set.filter(site=site)
            errors['network'] = ErrorList([
                "There were too many networks "
                "associated with vlan {0} in {1}. "
                "Manually specify which network to "
                "use. Your choces are {2}".format(
                    vlan, site, ", ".join([n.network_str for n in networks]))
            ])
            return None, errors
        except ObjectDoesNotExist:
            errors['network'] = "No network for vlan {0} in {1}.".format(
                vlan, site)
            return None, errors
    else:
        try:
            # Guess which type of network it is.
            try:
                if network_str.find(':') > -1:
                    ip_type = '6'
                    tmp_network = ipaddr.IPv6Network(network_str)
                    ip_upper, ip_lower = ipv6_to_longs(tmp_network)
                else:
                    ip_type = '4'
                    tmp_network = ipaddr.IPv4Network(network_str)
                    ip_upper, ip_lower = 0, int(tmp_network)
            except ipaddr.AddressValueError:
                errors['network'] = ErrorList([
                    "The network {0} is not a "
                    "valid IPv{1} network.".format(network_str, ip_type)
                ])
                return None, errors
            # Now try to find a network that matches the query. Error out if we
            # can't find one and recommend the user create it.
            network = Network.objects.get(ip_type=ip_type,
                                          ip_upper=ip_upper,
                                          ip_lower=ip_lower,
                                          prefixlen=tmp_network.prefixlen)
        except ObjectDoesNotExist:
            errors['network'] = ErrorList([
                "The network {0} was not found. "
                "Consider creating it in the web "
                "UI.".format(network_str)
            ])
            return None, errors

    if not network.range_set.all().exists():
        errors['range'] = ErrorList([
            "No range for network {0} in vlan {1} in "
            "site {0}. Create it via the web UI too "
            "many networks associated with vlan "
            "{0} in {1}".format(network, vlan, site)
        ])
        return None, errors

    if network.range_set.all().count() > 1:
        errors['ip'] = ErrorList([
            "Too many ranges. In the face of ambiguity, "
            "*this script* has refused the temptation "
            "to guess which range you want to put the "
            "interface in."
        ])
        return None, errors

    range_ = network.range_set.all()[0]
    return _create_ipv4_intr_from_range(label, domain.name, system, mac,
                                        range_.start_lower, range_.end_lower)
Exemplo n.º 5
0
    def process_flow_stats(self, stats, dp):
        self.logger.debug("flow stat processor")
        self.logger.debug("flows stats: " + str(len(stats)))
        #--- figure out the time since last stats
        prefix_bps = defaultdict(lambda: defaultdict(int))
        prefix_bytes = {}
        flows = []
        dpid = dp.id
        ofproto = dp.ofproto
        old_time = self.lastStatsTime
        now = int(time.time())

        stats_et = None
        if (old_time != None):
            stats_et = now - old_time

        self.lastStatsTime = now

        for stat in stats:

            dur_sec = stat.duration_sec
            in_port = stat.match.in_port
            src_mask = 32 - ((stat.match.wildcards & ofproto.OFPFW_NW_SRC_MASK)
                             >> ofproto.OFPFW_NW_SRC_SHIFT)
            dst_mask = 32 - ((stat.match.wildcards & ofproto.OFPFW_NW_DST_MASK)
                             >> ofproto.OFPFW_NW_DST_SHIFT)
            if (stat.match.dl_type == 34525):
                prefix = ipaddr.IPv6Network("::/128")
                dir = "tx"
            elif (src_mask > 0):
                #--- this is traffic TX from target prefix
                id = ipaddr.IPv4Address(stat.match.nw_src)
                prefix = ipaddr.IPv4Network(str(id) + "/" + str(src_mask))
                dir = "tx"
            elif (dst_mask > 0):
                #--- this is traffic RX from target prefix
                id = ipaddr.IPv4Address(stat.match.nw_dst)
                prefix = ipaddr.IPv4Network(str(id) + "/" + str(dst_mask))
                dir = "rx"
            else:
                self.logger.error("Flow:" + str(stat.match))
                #--- no mask, lets skip
                continue

            if (not prefix_bytes.has_key(prefix)):
                prefix_bytes[prefix] = {}
                prefix_bytes[prefix]["tx"] = 0
                prefix_bytes[prefix]["rx"] = 0

            prefix_bytes[prefix][dir] += stat.byte_count

            match = stat.match.__dict__
            wildcards = stat.match.wildcards
            del match['dl_dst']
            del match['dl_src']
            del match['dl_type']
            del match['wildcards']

            if (match['dl_vlan_pcp'] == 0):
                del match['dl_vlan_pcp']

            if (match['dl_vlan'] == 0):
                del match['dl_vlan']

            if (match['nw_proto'] == 0):
                del match['nw_proto']

            if (match['nw_tos'] == 0):
                del match['nw_tos']

            if (match['nw_src'] == 0):
                del match['nw_src']

            if (match['nw_dst'] == 0):
                del match['nw_dst']

            if (match['tp_src'] == 0):
                del match['tp_src']

            if (match['tp_dst'] == 0):
                del match['tp_dst']

            if (match['in_port'] == 0):
                del match['in_port']
            else:
                match['phys_port'] = int(match['in_port'])
                del match['in_port']

            mask = 32 - ((wildcards & ofproto_v1_0.OFPFW_NW_SRC_MASK) >>
                         ofproto_v1_0.OFPFW_NW_SRC_SHIFT)
            match['nw_src_mask'] = mask

            mask = 32 - ((wildcards & ofproto_v1_0.OFPFW_NW_DST_MASK) >>
                         ofproto_v1_0.OFPFW_NW_DST_SHIFT)
            match['nw_dst_mask'] = mask

            flows.append({
                'match': match,
                'wildcards': wildcards,
                'packet_count': stat.packet_count
            })

        for prefix in prefix_bytes:
            for dir in ("rx", "tx"):
                old_bytes = self.prefix_bytes[prefix][dir]
                new_bytes = prefix_bytes[prefix][dir]
                bytes = new_bytes - old_bytes
                #if we are less than the previous counter then we re-balanced
                #set back to 0 and start again
                if (bytes < 0):
                    self.prefix_bytes[prefix][dir] = 0
                    bytes = 0

                if (stats_et == None):
                    stats_et = 0

                try:
                    rate = bytes / float(int(stats_et))
                except ZeroDivisionError:
                    self.logger.debug("Division by zero, rate = 0")
                    rate = 0

                prefix_bps[prefix][dir] = rate
                self.prefix_bytes[prefix][dir] = prefix_bytes[prefix][dir]

        #--- update the balancer
        for prefix in prefix_bps.keys():
            rx = prefix_bps[prefix]["rx"]
            tx = prefix_bps[prefix]["tx"]
            self.api.updatePrefixBW("%016x" % dpid, prefix, tx, rx)

        self.api.TimeoutFlows("%016x" % dpid, flows)
Exemplo n.º 6
0
    def testCollapsing(self):
        # test only IP addresses including some duplicates
        ip1 = ipaddr.IPv4Address('1.1.1.0')
        ip2 = ipaddr.IPv4Address('1.1.1.1')
        ip3 = ipaddr.IPv4Address('1.1.1.2')
        ip4 = ipaddr.IPv4Address('1.1.1.3')
        ip5 = ipaddr.IPv4Address('1.1.1.4')
        ip6 = ipaddr.IPv4Address('1.1.1.0')
        # check that addreses are subsumed properly.
        collapsed = ipaddr.collapse_address_list(
            [ip1, ip2, ip3, ip4, ip5, ip6])
        self.assertEqual(collapsed, [
            ipaddr.IPv4Network('1.1.1.0/30'),
            ipaddr.IPv4Network('1.1.1.4/32')
        ])

        # test a mix of IP addresses and networks including some duplicates
        ip1 = ipaddr.IPv4Address('1.1.1.0')
        ip2 = ipaddr.IPv4Address('1.1.1.1')
        ip3 = ipaddr.IPv4Address('1.1.1.2')
        ip4 = ipaddr.IPv4Address('1.1.1.3')
        ip5 = ipaddr.IPv4Network('1.1.1.4/30')
        ip6 = ipaddr.IPv4Network('1.1.1.4/30')
        # check that addreses are subsumed properly.
        collapsed = ipaddr.collapse_address_list(
            [ip5, ip1, ip2, ip3, ip4, ip6])
        self.assertEqual(collapsed, [ipaddr.IPv4Network('1.1.1.0/29')])

        # test only IP networks
        ip1 = ipaddr.IPv4Network('1.1.0.0/24')
        ip2 = ipaddr.IPv4Network('1.1.1.0/24')
        ip3 = ipaddr.IPv4Network('1.1.2.0/24')
        ip4 = ipaddr.IPv4Network('1.1.3.0/24')
        ip5 = ipaddr.IPv4Network('1.1.4.0/24')
        # stored in no particular order b/c we want CollapseAddr to call [].sort
        ip6 = ipaddr.IPv4Network('1.1.0.0/22')
        # check that addreses are subsumed properly.
        collapsed = ipaddr.collapse_address_list(
            [ip1, ip2, ip3, ip4, ip5, ip6])
        self.assertEqual(collapsed, [
            ipaddr.IPv4Network('1.1.0.0/22'),
            ipaddr.IPv4Network('1.1.4.0/24')
        ])

        # test that two addresses are supernet'ed properly
        collapsed = ipaddr.collapse_address_list([ip1, ip2])
        self.assertEqual(collapsed, [ipaddr.IPv4Network('1.1.0.0/23')])

        # test same IP networks
        ip_same1 = ip_same2 = ipaddr.IPv4Network('1.1.1.1/32')
        self.assertEqual(ipaddr.collapse_address_list([ip_same1, ip_same2]),
                         [ip_same1])

        # test same IP addresses
        ip_same1 = ip_same2 = ipaddr.IPv4Address('1.1.1.1')
        self.assertEqual(ipaddr.collapse_address_list([ip_same1, ip_same2]),
                         [ipaddr.IPNetwork('1.1.1.1/32')])
        ip1 = ipaddr.IPv6Network('::2001:1/100')
        ip2 = ipaddr.IPv6Network('::2002:1/120')
        ip3 = ipaddr.IPv6Network('::2001:1/96')
        # test that ipv6 addresses are subsumed properly.
        collapsed = ipaddr.collapse_address_list([ip1, ip2, ip3])
        self.assertEqual(collapsed, [ip3])

        # the toejam test
        ip1 = ipaddr.IPAddress('1.1.1.1')
        ip2 = ipaddr.IPAddress('::1')
        self.assertRaises(TypeError, ipaddr.collapse_address_list, [ip1, ip2])
Exemplo n.º 7
0
 def testExplodeShortHandIpStr(self):
     addr1 = ipaddr.IPv6Network('2001::1')
     self.assertEqual('2001:0000:0000:0000:0000:0000:0000:0001',
                      addr1._explode_shorthand_ip_string(str(addr1.ip)))
     self.assertEqual('0000:0000:0000:0000:0000:0000:0000:0001',
                      ipaddr.IPv6Network('::1/128').exploded)
# check for some prefixes
for line in raw_prefixes:
    try:
        if '2001:db8::/32' in line:
            print "pass: 2001:db8::/32 is in the list"
            break
    except:
        print "error: the list seems corrupt, 2001:db8::/32 is missing"
        sys.exit(1)

#   - are valid ipv6 prefixes and copy them to new list
valid_prefixes = []
for line in raw_prefixes:
    try:
        prefix = line.split("^")[0]
        if ipaddr.IPv6Network(prefix):
            valid_prefixes.append(line)
    except ValueError:
        print 'entry is not valid: %s' % prefix
        pass

# get last entry and remove the comma

formatted_prefixes = '\n    '.join(valid_prefixes)

# construct object
# RPSL object: 
header = """filter-set: fltr-martian-v6
descr: Current IPv6 martians
mp-filter: {
    """
Exemplo n.º 9
0
    def test_switch_init(self):
        api = SciPass(logger=logging.getLogger(__name__),
                      config=str(os.getcwd()) + "/t/etc/SciPass.xml")

        #first setup the handler to get all the flows that were sent
        flows = []

        def flowSent(dpid=None,
                     domain=None,
                     header=None,
                     actions=None,
                     command=None,
                     priority=None,
                     idle_timeout=None,
                     hard_timeout=None):
            obj = {
                'dpid': dpid,
                'header': header,
                'actions': actions,
                'command': command,
                'priority': priority,
                'idle_timeout': idle_timeout,
                'hard_timeout': hard_timeout
            }
            flows.append(obj)
            logging.error(obj)

        api.registerForwardingStateChangeHandler(flowSent)
        datapath = Mock(id=1)
        api.switchJoined(datapath)

        self.assertTrue(len(flows) == 25)
        #verify all of the 'flow details are set properly'
        for flow in flows:
            self.assertEquals(flow['dpid'], "%016x" % datapath.id)
            self.assertEquals(flow['hard_timeout'], 0)
            self.assertEquals(flow['idle_timeout'], 0)

        flow = flows[0]
        self.assertEquals(flow['actions'], [{'type': 'output', 'port': 5}])
        self.assertEquals(flow['command'], "ADD")
        self.assertEquals(flow['header'], {'phys_port': 1, 'dl_type': None})
        self.assertEquals(flow['priority'], 5)
        flow = flows[1]
        self.assertEquals(flow['actions'], [{'type': 'output', 'port': 1}])
        self.assertEquals(flow['command'], "ADD")
        self.assertEquals(flow['header'], {
            'phys_port': 5,
            'nw_dst': ipaddr.IPv4Network('10.0.17.0/24')
        })
        self.assertEquals(flow['priority'], 10)
        flow = flows[2]
        self.assertEquals(flow['actions'], [{'type': 'output', 'port': 5}])
        self.assertEquals(flow['command'], "ADD")
        self.assertEquals(flow['header'], {
            'phys_port': 1,
            'nw_src': ipaddr.IPv4Network('10.0.17.0/24')
        })
        self.assertEquals(flow['priority'], 10)
        flow = flows[3]
        self.assertEquals(flow['actions'], [{'type': 'output', 'port': 1}])
        self.assertEquals(flow['command'], "ADD")
        self.assertEquals(flow['header'], {
            'phys_port': 5,
            'nw_dst': ipaddr.IPv4Network('10.0.18.0/24')
        })
        self.assertEquals(flow['priority'], 10)
        flow = flows[4]
        self.assertEquals(flow['actions'], [{'type': 'output', 'port': 5}])
        self.assertEquals(flow['command'], "ADD")
        self.assertEquals(flow['header'], {
            'phys_port': 1,
            'nw_src': ipaddr.IPv4Network('10.0.18.0/24')
        })
        self.assertEquals(flow['priority'], 10)
        flow = flows[5]
        self.assertEquals(flow['actions'], [{'type': 'output', 'port': 5}])
        self.assertEquals(flow['command'], "ADD")
        self.assertEquals(flow['header'], {'phys_port': 2, 'dl_type': None})
        self.assertEquals(flow['priority'], 5)
        flow = flows[6]
        self.assertEquals(flow['actions'], [{'type': 'output', 'port': 2}])
        self.assertEquals(flow['command'], "ADD")
        self.assertEquals(flow['header'], {
            'phys_port': 5,
            'nw_dst': ipaddr.IPv4Network('10.0.19.0/24')
        })
        self.assertEquals(flow['priority'], 10)
        flow = flows[7]
        self.assertEquals(flow['actions'], [{'type': 'output', 'port': 5}])
        self.assertEquals(flow['command'], "ADD")
        self.assertEquals(flow['header'], {
            'phys_port': 2,
            'nw_src': ipaddr.IPv4Network('10.0.19.0/24')
        })
        self.assertEquals(flow['priority'], 10)
        flow = flows[8]
        self.assertEquals(flow['actions'], [{'type': 'output', 'port': 2}])
        self.assertEquals(flow['command'], "ADD")
        self.assertEquals(flow['header'], {
            'phys_port': 5,
            'nw_dst': ipaddr.IPv4Network('10.0.20.0/24')
        })
        self.assertEquals(flow['priority'], 10)
        flow = flows[9]
        self.assertEquals(flow['actions'], [{'type': 'output', 'port': 5}])
        self.assertEquals(flow['command'], "ADD")
        self.assertEquals(flow['header'], {
            'phys_port': 2,
            'nw_src': ipaddr.IPv4Network('10.0.20.0/24')
        })
        self.assertEquals(flow['priority'], 10)
        flow = flows[10]
        self.assertEquals(flow['actions'], [{'type': 'output', 'port': 2}])
        self.assertEquals(flow['command'], "ADD")
        self.assertEquals(flow['header'], {
            'phys_port': 5,
            'nw_dst': ipaddr.IPv6Network('2001:0DB8::/48')
        })
        self.assertEquals(flow['priority'], 10)
        flow = flows[11]
        self.assertEquals(flow['actions'], [{'type': 'output', 'port': 5}])
        self.assertEquals(flow['command'], "ADD")
        self.assertEquals(flow['header'], {
            'phys_port': 2,
            'nw_src': ipaddr.IPv6Network('2001:0DB8::/48')
        })
        self.assertEquals(flow['priority'], 10)
        flow = flows[12]
        self.assertEquals(flow['actions'], [{
            'type': 'output',
            'port': 1
        }, {
            'type': 'output',
            'port': 2
        }])
        self.assertEquals(flow['command'], "ADD")
        self.assertEquals(flow['header'], {'phys_port': 5, 'dl_type': None})
        self.assertEquals(flow['priority'], 3)
        flow = flows[13]
        self.assertEquals(flow['actions'], [{'type': 'output', 'port': 10}])
        self.assertEquals(flow['command'], "ADD")
        self.assertEquals(flow['header'], {'phys_port': 6, 'dl_type': None})
        self.assertEquals(flow['priority'], 10)
        flow = flows[14]
        self.assertEquals(flow['actions'], [{'type': 'output', 'port': 6}])
        self.assertEquals(flow['command'], "ADD")
        self.assertEquals(flow['header'], {'phys_port': 10, 'dl_type': None})
        self.assertEquals(flow['priority'], 10)
        flow = flows[15]
        self.assertEquals(flow['actions'], [{
            'type': 'output',
            'port': 27
        }, {
            'type': 'output',
            'port': 26
        }, {
            'type': 'output',
            'port': 5
        }])
        self.assertEquals(flow['command'], "ADD")
        self.assertEquals(flow['header'], {
            'phys_port': 1,
            'nw_src': ipaddr.IPv4Network('10.0.17.0/24')
        })
        self.assertEquals(flow['priority'], 500)
        flow = flows[16]
        self.assertEquals(flow['actions'], [{
            'type': 'output',
            'port': 27
        }, {
            'type': 'output',
            'port': 26
        }, {
            'type': 'output',
            'port': 6
        }])
        self.assertEquals(flow['command'], "ADD")
        self.assertEquals(flow['header'], {
            'phys_port': 10,
            'nw_dst': ipaddr.IPv4Network('10.0.17.0/24')
        })
        self.assertEquals(flow['priority'], 500)
        flow = flows[17]
        self.assertEquals(flow['actions'], [{
            'type': 'output',
            'port': 21
        }, {
            'type': 'output',
            'port': 20
        }, {
            'type': 'output',
            'port': 5
        }])
        self.assertEquals(flow['command'], "ADD")
        self.assertEquals(flow['header'], {
            'phys_port': 1,
            'nw_src': ipaddr.IPv4Network('10.0.18.0/24')
        })
        self.assertEquals(flow['priority'], 600)
        flow = flows[18]
        self.assertEquals(flow['actions'], [{
            'type': 'output',
            'port': 21
        }, {
            'type': 'output',
            'port': 20
        }, {
            'type': 'output',
            'port': 6
        }])
        self.assertEquals(flow['command'], "ADD")
        self.assertEquals(flow['header'], {
            'phys_port': 10,
            'nw_dst': ipaddr.IPv4Network('10.0.18.0/24')
        })
        self.assertEquals(flow['priority'], 600)
        flow = flows[19]
        self.assertEquals(flow['actions'], [{
            'type': 'output',
            'port': 25
        }, {
            'type': 'output',
            'port': 24
        }, {
            'type': 'output',
            'port': 5
        }])
        self.assertEquals(flow['command'], "ADD")
        self.assertEquals(flow['header'], {
            'phys_port': 2,
            'nw_src': ipaddr.IPv4Network('10.0.19.0/24')
        })
        self.assertEquals(flow['priority'], 700)
        flow = flows[20]
        self.assertEquals(flow['actions'], [{
            'type': 'output',
            'port': 25
        }, {
            'type': 'output',
            'port': 24
        }, {
            'type': 'output',
            'port': 6
        }])
        self.assertEquals(flow['command'], "ADD")
        self.assertEquals(flow['header'], {
            'phys_port': 10,
            'nw_dst': ipaddr.IPv4Network('10.0.19.0/24')
        })
        self.assertEquals(flow['priority'], 700)
        flow = flows[21]
        self.assertEquals(flow['actions'], [{
            'type': 'output',
            'port': 23
        }, {
            'type': 'output',
            'port': 22
        }, {
            'type': 'output',
            'port': 5
        }])
        self.assertEquals(flow['command'], "ADD")
        self.assertEquals(flow['header'], {
            'phys_port': 2,
            'nw_src': ipaddr.IPv4Network('10.0.20.0/24')
        })
        self.assertEquals(flow['priority'], 800)
        flow = flows[22]
        self.assertEquals(flow['actions'], [{
            'type': 'output',
            'port': 23
        }, {
            'type': 'output',
            'port': 22
        }, {
            'type': 'output',
            'port': 6
        }])
        self.assertEquals(flow['command'], "ADD")
        self.assertEquals(flow['header'], {
            'phys_port': 10,
            'nw_dst': ipaddr.IPv4Network('10.0.20.0/24')
        })
        self.assertEquals(flow['priority'], 800)
Exemplo n.º 10
0
tablepart = strftime("%d-%m-%y")

#IPv4:
source = open("rirs", "r")

for line in source:
    prefix = line.rstrip().split(" ")[0]
    rir = line.rstrip().split(" ")[1]
    cursor.execute(
        "UPDATE `%s_routes` SET `RIR` = '%s' WHERE IPver = '4' AND `Prefix` LIKE '%s.%%'"
        % (tablepart, rir, prefix))

connection.commit()

#IPv6:
source = open("rirs-ipv6", "r")

for line in source:
    prefix = line.rstrip().split(" ")[0]
    binprefix = "%0128d\n" % (long(
        bin(ipaddr.IPv6Network(prefix).network)[2:]))
    length = int(prefix.split("/")[1])
    matchprefix = "%s" % (binprefix[:length])
    rir = line.rstrip().split(" ")[1]
    cursor.execute(
        "UPDATE `%s_routes` SET `RIR` = '%s' WHERE IPver = '6' AND `Bin` LIKE '%s%%'"
        % (tablepart, rir, matchprefix))

connection.commit()
connection.close()
Exemplo n.º 11
0
             "associated with vlan {0} in {1}. Manually specify which "
             "network to use. Your choces are {2}".format(
                 vlan, site, ", ".join([n.network_str for n in networks]))
         ])
         return None, errors
     except ObjectDoesNotExist, e:
         errors['network'] = "No network for vlan {0} in {1}.".format(
             vlan, site)
         return None, errors
 else:
     try:
         # Guess which type of network it is.
         try:
             if network_str.find(':') > -1:
                 ip_type = '6'
                 tmp_network = ipaddr.IPv6Network(network_str)
                 ip_upper, ip_lower = ipv6_to_longs(network_str)
             else:
                 ip_type = '4'
                 tmp_network = ipaddr.IPv4Network(network_str)
                 ip_upper, ip_lower = 0, int(tmp_network)
         except ipaddr.AddressValueError, e:
             errors['network'] = ErrorList([
                 "The network {0} is not a "
                 "valid IPv{1} network.".format(network_str, ip_type)
             ])
             return None, errors
         # Now try to find a network that matches the query. Error out if we
         # can't find one and recommend the user create it.
         network = Network.objects.get(ip_type=ip_type,
                                       ip_upper=ip_upper,
Exemplo n.º 12
0
 lines = 0
 for line in csvin:
     lines = lines + 1
     if lines >= 10000:
         break
     # print(line)
     newline = {}
     newheader = []
     # print(line)
     cprefixes = 0
     for key in line:
         k = key  # this is needed because the type of line being OrderedDict
         v = line[key]
         # print("\tk={}, v={}".format(k,v))
         try:
             n6 = ipaddr.IPv6Network(v)
             orgid = rdapc.prefixToOrgid(v)
             newline[k] = v
             newheader.append(k)
             # newline.append(orgid)
             newline['orgid' + str(cprefixes)] = orgid
             newheader.append('orgid' + str(cprefixes))
             cprefixes = cprefixes + 1
         except ipaddr.AddressValueError:
             # raise
             newline[k] = v
             newheader.append(k)
             next
         except Exception as err:
             print("Unexpected error {0}".format(err))
             print("Current RDAP JSON: {0}".format(rdapc.last_response))
Exemplo n.º 13
0
    def read_delegated(self):
        """
        Load the stats file specified in the constructor.
        """
        # init variables
        self.file = open(self.filename, 'rb')
        self.version_line = {}
        self.summary_lines = []
        self.record_lines = []
        self.cnt = {}
        csv_r = csv.reader(self.file, delimiter="|")

        # load version line
        while True:
            try:
                row = csv_r.next()
                if string.find(str(row), "#") == -1:
                    self.version_line['version'] = row[0].strip()
                    self.version_line['registry'] = row[1].strip()
                    self.version_line['serial'] = row[2].strip()
                    self.version_line['records'] = row[3].strip()
                    self.version_line['startdate'] = row[4].strip()
                    self.version_line['enddate'] = row[4].strip()
                    self.version_line['UTCoffset'] = row[5].strip()
                    break
            except IndexError as e:
                dprint("Error importing line: [%s]\n" % (row))
                sys.exit(1)
        ##

        # load summary lines
        if string.find(str(row), "#") == -1:
            row = csv_r.next()
            while row[5].strip() == 'summary':
                summary_entry = {
                    'registry': row[0].strip(),
                    'type': row[2].strip(),
                    'count': row[4].strip()
                }
                self.summary_lines.append(summary_entry)
                row = csv_r.next()
        # end loading summary lines

        # load records
        self.cnt['all'] = 0
        self.cnt['imported'] = 0
        self.cnt['filtered'] = 0
        while row:
            try:
                record = {
                    'registry': row[0].strip(),
                    'cc': row[1].strip(),
                    'type': row[2].strip(),
                    'start': row[3].strip(),
                    'value': row[4].strip(),
                    'date': row[5].strip(),
                    'status': row[6].strip(),
                    'uid': row[7].strip() if len(row) > 7 else "0"
                }
                # insert into db
                if record['type'] == 'ipv4':
                    pfx_len = 32 - int(math.log(int(record['value']), 2))
                    pfx = ipaddr.IPv4Network(record['start'] + "/" +
                                             str(pfx_len))
                    record['prefix'] = str(pfx)
                    record['istart'] = int(pfx.network)
                    record['iend'] = int(pfx.broadcast)
                    record['equiv'] = (record['iend'] -
                                       record['istart']) / 256 + 1
                elif record['type'] == 'ipv6':
                    pfx_norm_base = pow(2, 64)
                    pfx = ipaddr.IPv6Network(record['start'] + "/" +
                                             record['value'])
                    record['prefix'] = str(pfx)
                    record['istart'] = int(pfx.network) / pfx_norm_base
                    record['iend'] = int(pfx.broadcast) / pfx_norm_base
                    record['equiv'] = (record['iend'] - record['istart'] +
                                       1) / pow(2, 32)
                else:
                    record['prefix'] = 'na/asn'
                    record['istart'] = int(record['start'])
                    record['iend'] = int(record['start']) + int(
                        record['value'])
                    record['equiv'] = 'na'
                #
                self.cursor.execute(
                    "INSERT INTO resources VALUES (:registry, :cc, :type, :start, :value, :date, :status, "
                    + " :prefix, :istart, :iend, :equiv, :uid)", record)
                #
                row = csv_r.next()
            except ValueError:
                sys.stderr.write(
                    'ERROR parsing line from delegated file: %s\n' % (row))
                raise
            except IndexError:
                # print "*"
                row = csv_r.next()
                pass
            except StopIteration:
                break
            except Exception as e:
                dprint("Could not read line %s: %s" % (self.cnt['all'], row))
                dprint("Exception message %s" % (e.message))
                raise
                #
        self.conn.commit()
        self.file.close()
Exemplo n.º 14
0
        if "IPv6" in row:
            ipv6 = ipaddr.IPv6Address(row["IPv6"])
            add_ipv6_host(hostname, fwd_zonename, ipv6, (row["dns"] == "fwd"),
                          (row["dns"] == "rev"))

    # is it a subnet with auto dns?
    elif "IPv4-Subnet" in row and "dns" in row and row["dns"] == "auto":
        subnet = ipaddr.IPv4Network(row["IPv4-Subnet"])
        # router entry
        if "VLAN" in row:
            vlan = row["VLAN"]
            add_ipv4_host("vlan" + vlan + ".ESNORE", "emf.camp",
                          subnet.network + 1, False, False)
            #      if "IPv6" in row:
            ipv6 = ipaddr.IPv6Network(row["IPv6"])
            add_ipv6_host("vlan" + vlan + ".ESNORE", "emf.camp",
                          ipv6.network + 1, False, False)

        # host entries
        for ipv4 in subnet.iterhosts():
            if ipv4 == subnet.network + 1:  # first host is the gateway
                continue
            hostname = pretty_host(fwd_zonename, ipv4)
            if "Subdomain" in row:
                hostname += "." + row["Subdomain"]
            add_ipv4_host(hostname, fwd_zonename, ipv4, False, False)

    # is it a cname or other fixed record?
    elif "dns" in row and row["dns"] == "record":
        hostname = row["Hostname"]
Exemplo n.º 15
0
 def testRepr(self):
     self.assertEqual("IPv4Network('1.2.3.4/32')",
                      repr(ipaddr.IPv4Network('1.2.3.4')))
     self.assertEqual("IPv6Network('::1/128')",
                      repr(ipaddr.IPv6Network('::1')))
def pfxExplode(w_pfx):
    """
    Calculates meta columns for the delegated file.
    :param w_pfx:  prefix to be exploded

    Returns a dictionary with the following fields:
        'pfx'
        'type'
        'istart'
        'iend'
        'pfxlen'
    """
    # record = dict(w_row)
    record = dict()
    #
    if w_pfx:
        if w_pfx.find(":") != -1:
            loc_type = 'ipv6'
        else:
            loc_type = 'ipv4'
    else:
        loc_type = 'na'
    #
    record['pfx'] = w_pfx

    record['type'] = loc_type
    record['pfxlen'] = 0
    record['equiv'] = 0

    if record['type'] == 'ipv4' and w_pfx:
        record['prefix'] = w_pfx
        #print "prefix %s" % (w_pfx)
        try:
            pfx = ipaddr.IPv4Network(w_pfx)
            record['istart'] = int(pfx.network)
            record['iend'] = int(pfx.broadcast)
            record['pfxlen'] = pfx.prefixlen
            record['equiv'] = (record['iend']-record['istart']+1)/256
        except ipaddr.AddressValueError:
            sys.stderr.write("##### bad ip prefix: %s\n\n\n" % (record['prefix']))
            record['istart'] = -1
            record['iend']   = -1
            record['pfxlen'] = -1
            record['type'] ='badipv4'
        # record['equiv'] = (record['iend']-record['istart'])/256 + 1
        # return record
        return record
    elif record['type'] == 'ipv6' and w_pfx:
        if w_pfx.startswith("2"):
            pfx_norm_base = pow(2,64)
            try:
                pfx = ipaddr.IPv6Network( w_pfx )
                record['istart'] = int(pfx.network) / pfx_norm_base
                record['iend'] = int(pfx.broadcast) / pfx_norm_base
                record['pfxlen'] = pfx.prefixlen
                record['equiv'] = (record['iend'] - record['istart']+1) / math.pow(2, 32)
            except ipaddr.AddressValueError:
                sys.stderr.write("##### bad ip prefix: %s\n\n\n" % (record['prefix']))
                record['istart'] = -1
                record['iend']   = -1
                record['pfxlen'] = -1
                record['type'] = 'badipv6'                
        else:
            record['istart'] = 0
            record['iend']   = 0
            record['pfxlen'] = 0
            record['equiv'] = 0
        return record
    else:
        # return record['type']
        return record
Exemplo n.º 17
0
 def testSlash128Constructor(self):
     self.assertEquals(str(ipaddr.IPv6Network('::1/128')), '::1/128')
Exemplo n.º 18
0
def generate(override_template):
    if os.path.isfile("data/switches") and os.path.isfile(
            "data/users") and os.path.isfile("data/addressing"):

        switches = shelve.open("data/switches")["list"]
        port_types = shelve.open("data/port_types")["list"]
        users = shelve.open("data/users")["list"]

        addressing = shelve.open("data/addressing")["list"]
        print "generating VLANs"
        vlans = get_vlans(addressing)

        links = shelve.open("data/links")["list"]

        sw_links = {}

        sw_cvlan = {}
        cvlan_to_sw = {}

        # check camper vlans for issues
        for sw in switches:
            if "Camper-VLAN" in sw:
                if sw["Hostname"] in sw_cvlan:
                    print "PANIC: Duplicate Hostname: >" + sw["Hostname"] + "<"
                    sys.exit(1)
                sw_cvlan[sw["Hostname"]] = sw["Camper-VLAN"]

                if sw["Camper-VLAN"] in cvlan_to_sw:
                    print "PANIC: Duplicate camper vlan id: >" + sw[
                        "Camper-VLAN"] + "<"
                    print "for " + sw["Hostname"] + " and " + cvlan_to_sw[
                        sw["Camper-VLAN"]]
                    sys.exit(1)
                cvlan_to_sw[sw["Camper-VLAN"]] = sw["Hostname"]

        for a in addressing:
            if "VLAN" in a:
                if a["VLAN"] in cvlan_to_sw:
                    if cvlan_to_sw[a["VLAN"]] != a["Description"]:
                        print "WARNING - Camper VLAN missmatch?!?!"
                        print a["VLAN"], a["Description"], cvlan_to_sw[
                            a["VLAN"]]
                        print "^---"

        for link in links:
            o = {"Dir": "down"}
            o2 = {"Dir": "up"}
            #    print link

            if not switch_hostname_exists(switches, link["Switch1"]):
                print "WARNING: switch in links but not on the Switches sheet >" + link[
                    "Switch1"] + "<"

            if not switch_hostname_exists(switches, link["Switch2"]):
                print "WARNING: switch in links but not on the Switches sheet >" + link[
                    "Switch2"] + "<"

            if link["Switch1"] not in sw_links:
                sw_links[link["Switch1"]] = []

            if link["Switch2"] not in sw_links:
                sw_links[link["Switch2"]] = []

            o["To"] = link["Switch2"]
            o2["To"] = link["Switch1"]
            o["Ports"] = []
            for port in (("Switch1-Port1", "Switch2-Port1"),
                         ("Switch1-Port2", "Switch2-Port2")):
                if port[0] in link:
                    o["Ports"].append((link[port[0]], link[port[1]]))

            o2["Ports"] = []
            for port in (("Switch2-Port1", "Switch1-Port1"),
                         ("Switch2-Port2", "Switch1-Port2")):
                if port[0] in link:
                    o2["Ports"].append((link[port[0]], link[port[1]]))

            sw_links[link["Switch1"]].append(o)
            sw_links[link["Switch2"]].append(o2)

        loader = FileSystemLoader('templates')
        env = Environment(loader=loader)

        if not os.path.exists('out'):
            os.mkdir('out')
        if not os.path.exists('out' + os.path.sep + "switches"):
            os.mkdir('out' + os.path.sep + "switches")

        # Hostname  -> vlan_id
        sw_to_vlan = {}
        for sw in switches:
            if "Camper-VLAN" in sw:
                sw_to_vlan[sw["Hostname"]] = sw["Camper-VLAN"]

        # Hostname -> [child Hostname, child Hostname]
        sw_children = {}
        for sw in switches:
            if sw["Hostname"] in sw_links:
                sw["Links"] = sw_links[sw["Hostname"]]
                for l in sw["Links"]:
                    if l["Dir"] == "down":
                        #          print l["To"], l["Dir"]
                        if sw["Hostname"] not in sw_children:
                            sw_children[sw["Hostname"]] = []
                        sw_children[sw["Hostname"]].append(l["To"])

        # all sitewide vlans
        sitewide_vlans = ""
        for id, vlan in vlans.items():
            if vlan['sitewide']:
                if sitewide_vlans:
                    sitewide_vlans += ","
                sitewide_vlans += str(vlan['vlan'])

    #  for k in sw_children:
    #    print k, sw_children[k]

    # graphiz is fun :)
        gfh = open("out/vlans.gv", "w")

        gfh.write(
            "##Command to produce the output: \"neato -Tpng thisfile > thisfile.png\"\n\n"
        )

        gfh.write("""digraph Vlans {\n""")
        #  node [shape=box];  gy2; yr2; rg2; gy1; yr1; rg1;
        #  node [shape=circle,fixedsize=true,width=0.9];  green2; yellow2; red2; safe2; safe1; green1; yellow1; red1;

        for k in sw_children:
            for c in sw_children[k]:
                gfh.write('"' + k + '"' + " -> " + '"' + c + "\";\n")

        gfh.write("""
    overlap=false
    label="EMFCamp Switches and Vlans\\nlaid out by Graphviz"
    fontsize=12;
    }
    """)

        gfh.close()

    #  print sw_to_vlan
    #  print
    #  print sw_children
    #  print

    else:
        print "No datasources, did you --download first?"
        sys.exit(1)

    def get_swchildren(sw, cs=None):
        if not cs:
            cs = {}
        if sw not in sw_children:
            return {}
        for c in sw_children[sw]:
            if c in sw_to_vlan:
                if sw_to_vlan[c] not in cs:
                    cs[sw_to_vlan[c]] = 1
#      else:
#        print "no vlan for " + c
            cs.update(get_swchildren(c, cs))
        return cs

    sw_uplink_vlans = {}
    for sw in switches:
        k = sw["Hostname"]
        if k not in sw_uplink_vlans:
            sw_uplink_vlans[k] = get_swchildren(k)
            if k in sw_to_vlan:
                sw_uplink_vlans[k][sw_to_vlan[k]] = 1

    o = {}
    for sw in sw_uplink_vlans:
        ks = sw_uplink_vlans[sw].keys()
        ks.sort()
        o[sw] = ks

    sw_uplink_vlans = o

    #  for k in sw_uplink_vlans:
    #    print k, sw_uplink_vlans[k]

    for sw in switches:
        print "Generating " + sw["Hostname"] + " of type " + sw["Type"]

        ##
        ## Do something smart with port assignments here..
        ## Artnet, Voip, Dect, Voc, Bar
        ##
        if not "Ports" in sw or len(sw["Ports"]) == 0:
            sw["Ports"] = 48

        sw['port_configs'] = []
        for i in range(int(sw['Camper-Ports'])):
            sw['port_configs'].append({
                'description': 'Camper',
                'vlan': sw['Camper-VLAN']
            })

        for port_type in reversed(port_types):
            if ('#' + port_type["Port-Type"]) in sw:
                for i in range(int(sw['#' + port_type['Port-Type']])):
                    sw['port_configs'].append({
                        'description':
                        port_type['Port-Type'],
                        'vlan':
                        port_type['VLAN']
                    })
        print sw

        if "Links" not in sw:
            print "*** No links found for switch ", sw["Hostname"]

        mycampervlan = None
        if "Camper-VLAN" in sw:
            mycampervlan = vlans[sw["Camper-VLAN"]]
            mycampervlan["ipv4-subnet"] = ipaddr.IPv4Network(
                mycampervlan["ipv4"])
            mycampervlan["ipv6-subnet"] = ipaddr.IPv6Network(
                mycampervlan["ipv6"])


#      print mycampervlan["ipv4-subnet"].network

        if sw["Hostname"] in sw_uplink_vlans:
            sw["Uplink Vlans"] = sw_uplink_vlans[sw["Hostname"]]

        if override_template:
            template = env.get_template(override_template + ".j2")
            found = True
        else:
            found = False
            for tname in (sw["Hostname"], sw["Model"], sw["Type"]):
                if os.path.exists("templates" + os.path.sep + tname + ".j2"):
                    template = env.get_template(tname + ".j2")
                    found = True
                    break

        if found:
            out = template.render(users=users,
                                  switch=sw,
                                  vlans=vlans,
                                  mycampervlan=mycampervlan,
                                  config=config,
                                  uplink_vlans=sw_uplink_vlans,
                                  sitewide_vlans=sitewide_vlans).encode(
                                      "utf-8", "replace")

            # remove excess empty lines
            while "\n\n\n" in out:
                out = out.replace("\n\n\n", "\n\n")

            ofh = open(
                "out" + os.path.sep + "switches" + os.path.sep +
                sw["Hostname"] + ".emf.camp", "w")
            ofh.write(out)
            ofh.close()
        else:
            print " - No template found for " + sw["Hostname"] + "!"

    # make it eaiser to match switch config to a switch
    for sw in switches:
        if os.path.islink("out" + os.path.sep + "switches" + os.path.sep +
                          sw["Serial"]):
            os.unlink("out" + os.path.sep + "switches" + os.path.sep +
                      sw["Serial"])
        os.symlink(
            sw["Hostname"] + ".emf.camp",
            "out" + os.path.sep + "switches" + os.path.sep + sw["Serial"])

    # rancid
    rfh = open("out" + os.path.sep + "router.db", "w")
    for sw in switches:
        o = sw["Hostname"].lower() + ".emf.camp"
        if sw["Type"] == "ios":
            o += ";cisco;up"
        elif sw["Type"] == "ios-core":
            o += ";cisco;up"
        elif sw["Type"] == "xos":
            o += ";Extreme;up"
        elif sw["Type"] == "eos":
            o += ";arista;up"
        elif sw["Type"] == "eos-core":
            o += ";arista;up"
        elif sw["Type"] == "junos":
            o += ";juniper;up"
        elif sw["Type"] == "junos-els":
            o += ";juniper;up"
        elif sw["Type"] == "procurve":
            o += ";hp;up"
        else:
            print "**** unknown type:", sw["Type"]
            exit()
        rfh.write(o + "\n")
    rfh.close()
Exemplo n.º 19
0
    def testNetworkComparison(self):
        # ip1 and ip2 have the same network address
        ip1 = ipaddr.IPv4Network('1.1.1.0/24')
        ip2 = ipaddr.IPv4Network('1.1.1.1/24')
        ip3 = ipaddr.IPv4Network('1.1.2.0/24')

        self.assertTrue(ip1 < ip3)
        self.assertTrue(ip3 > ip2)

        self.assertEquals(ip1.compare_networks(ip2), 0)
        self.assertTrue(ip1._get_networks_key() == ip2._get_networks_key())
        self.assertEquals(ip1.compare_networks(ip3), -1)
        self.assertTrue(ip1._get_networks_key() < ip3._get_networks_key())

        ip1 = ipaddr.IPv6Network('2001::2000/96')
        ip2 = ipaddr.IPv6Network('2001::2001/96')
        ip3 = ipaddr.IPv6Network('2001:ffff::2000/96')

        self.assertTrue(ip1 < ip3)
        self.assertTrue(ip3 > ip2)
        self.assertEquals(ip1.compare_networks(ip2), 0)
        self.assertTrue(ip1._get_networks_key() == ip2._get_networks_key())
        self.assertEquals(ip1.compare_networks(ip3), -1)
        self.assertTrue(ip1._get_networks_key() < ip3._get_networks_key())

        # Test comparing different protocols.
        # Should always raise a TypeError.
        ipv6 = ipaddr.IPv6Network('::/0')
        ipv4 = ipaddr.IPv4Network('0.0.0.0/0')
        self.assertRaises(TypeError, ipv4.__lt__, ipv6)
        self.assertRaises(TypeError, ipv4.__gt__, ipv6)
        self.assertRaises(TypeError, ipv6.__lt__, ipv4)
        self.assertRaises(TypeError, ipv6.__gt__, ipv4)

        # Regression test for issue 19.
        ip1 = ipaddr.IPNetwork('10.1.2.128/25')
        self.assertFalse(ip1 < ip1)
        self.assertFalse(ip1 > ip1)
        ip2 = ipaddr.IPNetwork('10.1.3.0/24')
        self.assertTrue(ip1 < ip2)
        self.assertFalse(ip2 < ip1)
        self.assertFalse(ip1 > ip2)
        self.assertTrue(ip2 > ip1)
        ip3 = ipaddr.IPNetwork('10.1.3.0/25')
        self.assertTrue(ip2 < ip3)
        self.assertFalse(ip3 < ip2)
        self.assertFalse(ip2 > ip3)
        self.assertTrue(ip3 > ip2)

        # Regression test for issue 28.
        ip1 = ipaddr.IPNetwork('10.10.10.0/31')
        ip2 = ipaddr.IPNetwork('10.10.10.0')
        ip3 = ipaddr.IPNetwork('10.10.10.2/31')
        ip4 = ipaddr.IPNetwork('10.10.10.2')
        sorted = [ip1, ip2, ip3, ip4]
        unsorted = [ip2, ip4, ip1, ip3]
        unsorted.sort()
        self.assertEqual(sorted, unsorted)
        unsorted = [ip4, ip1, ip3, ip2]
        unsorted.sort()
        self.assertEqual(sorted, unsorted)
        self.assertRaises(TypeError, ip1.__lt__,
                          ipaddr.IPAddress('10.10.10.0'))
        self.assertRaises(TypeError, ip2.__lt__,
                          ipaddr.IPAddress('10.10.10.0'))

        # <=, >=
        self.assertTrue(
            ipaddr.IPNetwork('1.1.1.1') <= ipaddr.IPNetwork('1.1.1.1'))
        self.assertTrue(
            ipaddr.IPNetwork('1.1.1.1') <= ipaddr.IPNetwork('1.1.1.2'))
        self.assertFalse(
            ipaddr.IPNetwork('1.1.1.2') <= ipaddr.IPNetwork('1.1.1.1'))
        self.assertTrue(ipaddr.IPNetwork('::1') <= ipaddr.IPNetwork('::1'))
        self.assertTrue(ipaddr.IPNetwork('::1') <= ipaddr.IPNetwork('::2'))
        self.assertFalse(ipaddr.IPNetwork('::2') <= ipaddr.IPNetwork('::1'))
Exemplo n.º 20
0
def is_ipv6netmask(addr_netmask):
    try:
        ipaddr.IPv6Network(addr_netmask)
    except (ValueError, ipaddr.NetmaskValueError, ipaddr.AddressValueError):
        return False
    return True
Exemplo n.º 21
0
class FaucetTestBase(unittest.TestCase):
    """Base class for all FAUCET unit tests."""

    ONE_GOOD_PING = '1 packets transmitted, 1 received, 0% packet loss'
    FAUCET_VIPV4 = ipaddr.IPv4Network('10.0.0.254/24')
    FAUCET_VIPV4_2 = ipaddr.IPv4Network('172.16.0.254/24')
    FAUCET_VIPV6 = ipaddr.IPv6Network('fc00::1:254/64')
    FAUCET_VIPV6_2 = ipaddr.IPv6Network('fc01::1:254/64')
    OFCTL = 'ovs-ofctl -OOpenFlow13'
    BOGUS_MAC = '01:02:03:04:05:06'
    FAUCET_MAC = '0e:00:00:00:00:01'
    LADVD = 'timeout 30s ladvd -e lo -f'

    CONFIG = ''
    CONFIG_GLOBAL = ''

    config = None
    dpid = None
    hardware = 'Open vSwitch'
    hw_switch = False
    gauge_of_port = None
    net = None
    of_port = None
    port_map = {'port_1': 1, 'port_2': 2, 'port_3': 3, 'port_4': 4}
    switch_map = {}
    tmpdir = None

    def __init__(self, name, config, root_tmpdir, ports_sock):
        super(FaucetTestBase, self).__init__(name)
        self.config = config
        self.root_tmpdir = root_tmpdir
        self.ports_sock = ports_sock

    def tmpdir_name(self):
        test_name = '-'.join(self.id().split('.')[1:])
        return tempfile.mkdtemp(prefix='%s-' % test_name, dir=self.root_tmpdir)

    def tearDown(self):
        """Clean up after a test."""
        # must not be any controller exception.
        self.assertEquals(0,
                          os.path.getsize(os.environ['FAUCET_EXCEPTION_LOG']))
        controller_names = []
        for controller in self.net.controllers:
            controller_names.append(controller.name)
        if self.net is not None:
            self.net.stop()
        test_class_name = self.id().split('.')[1]
        if (not test_class_name.startswith('FaucetGroup')
                and not test_class_name.startswith('FaucetSingleGroup')):
            for dp_name, debug_log in self.get_ofchannel_logs():
                self.assertFalse(re.search('OFPErrorMsg',
                                           open(debug_log).read()),
                                 msg='debug log has OFPErrorMsgs')
        # Associate controller log with test results, if we are keeping
        # the temporary directory, or effectively delete it if not.
        # mininet doesn't have a way to change its log name for the controller.
        for controller_name in controller_names:
            shutil.move('/tmp/%s.log' % controller_name, self.tmpdir)

    def pre_start_net(self):
        """Hook called after Mininet initializtion, before Mininet started."""
        return

    def get_config_header(self, config_global, debug_log, dpid, hardware):
        """Build v2 FAUCET config header."""
        return """
version: 2
%s
dps:
    faucet-1:
        ofchannel_log: %s
        dp_id: 0x%x
        hardware: "%s"
""" % (config_global, debug_log, int(dpid), hardware)

    def get_gauge_config(self, faucet_config_file, monitor_stats_file,
                         monitor_state_file, monitor_flow_table_file):
        """Build Gauge config."""
        return """
version: 2
faucet_configs:
    - %s
watchers:
    port_stats:
        dps: ['faucet-1']
        type: 'port_stats'
        interval: 5
        db: 'stats_file'
    port_state:
        dps: ['faucet-1']
        type: 'port_state'
        interval: 5
        db: 'state_file'
    flow_table:
        dps: ['faucet-1']
        type: 'flow_table'
        interval: 5
        db: 'flow_file'
dbs:
    stats_file:
        type: 'text'
        file: %s
    state_file:
        type: 'text'
        file: %s
    flow_file:
        type: 'text'
        file: %s
""" % (faucet_config_file, monitor_stats_file, monitor_state_file,
        monitor_flow_table_file)

    def get_controller(self):
        """Return the first (only) controller."""
        return self.net.controllers[0]

    def ofctl_rest_url(self):
        """Return control URL for Ryu ofctl module."""
        return 'http://127.0.0.1:%u' % self.get_controller().ofctl_port

    def get_all_groups_desc_from_dpid(self, dpid, timeout=2):
        int_dpid = faucet_mininet_test_util.str_int_dpid(dpid)
        for _ in range(timeout):
            try:
                ofctl_result = json.loads(
                    requests.get('%s/stats/groupdesc/%s' %
                                 (self.ofctl_rest_url(), int_dpid)).text)
                flow_dump = ofctl_result[int_dpid]
                return [json.dumps(flow) for flow in flow_dump]
            except (ValueError, requests.exceptions.ConnectionError):
                # Didn't get valid JSON, try again
                time.sleep(1)
                continue
        return []

    def get_group_id_for_matching_flow(self, exp_flow, timeout=10):
        for _ in range(timeout):
            flow_dump = self.get_all_flows_from_dpid(self.dpid, timeout)
            for flow in flow_dump:
                if re.search(exp_flow, flow):
                    flow = json.loads(flow)
                    group_id = int(re.findall(r'\d+', str(flow['actions']))[0])
                    return group_id
            time.sleep(1)
        self.assertTrue(False,
                        "Can't find group_id for matching flow %s" % exp_flow)

    def wait_matching_in_group_table(self, exp_flow, group_id, timeout=10):
        exp_group = '%s.+"group_id": %d' % (exp_flow, group_id)
        for _ in range(timeout):
            group_dump = self.get_all_groups_desc_from_dpid(self.dpid, 1)
            for group_desc in group_dump:
                if re.search(exp_group, group_desc):
                    return True
            time.sleep(1)
        return False

    def get_all_flows_from_dpid(self, dpid, timeout=10):
        """Return all flows from DPID."""
        for _ in range(timeout):
            try:
                ofctl_result = json.loads(
                    requests.get('%s/stats/flow/%s' %
                                 (self.ofctl_rest_url(), dpid)).text)
            except (ValueError, requests.exceptions.ConnectionError):
                # Didn't get valid JSON, try again
                time.sleep(1)
                continue
            flow_dump = ofctl_result[dpid]
            return [json.dumps(flow) for flow in flow_dump]
        return []

    def get_matching_flow_on_dpid(self, dpid, exp_flow, timeout=10):
        """Return flow matching an RE from DPID."""
        for _ in range(timeout):
            flow_dump = self.get_all_flows_from_dpid(dpid)
            for flow in flow_dump:
                if re.search(exp_flow, flow):
                    return json.loads(flow)
            time.sleep(1)
        return {}

    def get_matching_flow(self, exp_flow, timeout=10):
        """Return flow matching an RE from default DPID."""
        return self.get_matching_flow_on_dpid(self.dpid, exp_flow, timeout)

    def matching_flow_present_on_dpid(self, dpid, exp_flow, timeout=10):
        """Return True if matching flow is present on a DPID."""
        if self.get_matching_flow_on_dpid(dpid, exp_flow, timeout):
            return True
        return False

    def matching_flow_present(self, exp_flow, timeout=10):
        """Return True if matching flow is present on default DPID."""
        return self.matching_flow_present_on_dpid(self.dpid, exp_flow, timeout)

    def wait_until_matching_flow(self, exp_flow, timeout=10):
        """Wait (require) for flow to be present on default DPID."""
        self.assertTrue(self.matching_flow_present(exp_flow, timeout),
                        msg=exp_flow)

    def host_learned(self, host, timeout=10):
        """Return True if a host has been learned on default DPID."""
        return self.matching_flow_present(
            '"table_id": 3,.+"dl_src": "%s"' % host.MAC(), timeout)

    def host_ipv4(self, host):
        """Return first IPv4/netmask for host's default interface."""
        host_ip_cmd = (
            r'ip -o -f inet addr show %s|grep -m 1 -Eo "[0-9\\.]+\/[0-9]+"')
        return host.cmd(host_ip_cmd % host.defaultIntf()).strip()

    def host_ipv6(self, host):
        """Return first IPv6/netmask for host's default interface."""
        host_ip_cmd = (
            r'ip -o -f inet6 addr show %s|grep -m 1 -Eo "[0-9a-f\:]+\/[0-9]+"')
        return host.cmd(host_ip_cmd % host.defaultIntf()).strip()

    def require_host_learned(self, host, retries=3):
        """Require a host be learned on default DPID."""
        host_ip_net = self.host_ipv4(host)
        ping_cmd = 'ping'
        if not host_ip_net:
            host_ip_net = self.host_ipv6(host)
        broadcast = (ipaddr.IPNetwork(host_ip_net).broadcast)
        if broadcast.version == 6:
            ping_cmd = 'ping6'
        for _ in range(retries):
            if self.host_learned(host, timeout=1):
                return
            # stimulate host learning with a broadcast ping
            host.cmd('%s -i 0.2 -c 1 -b %s' % (ping_cmd, broadcast))
        self.fail('host %s could not be learned' % host)

    def get_ofchannel_logs(self):
        config = yaml.load(open(os.environ['FAUCET_CONFIG']))
        ofchannel_logs = []
        for dp_name, dp_config in config['dps'].iteritems():
            if 'ofchannel_log' in dp_config:
                debug_log = dp_config['ofchannel_log']
                ofchannel_logs.append((dp_name, debug_log))
        return ofchannel_logs

    def wait_debug_log(self):
        """Require all switches to have exchanged flows with controller."""
        ofchannel_logs = self.get_ofchannel_logs()
        for dp_name, debug_log in ofchannel_logs:
            debug_log_present = False
            for _ in range(20):
                if (os.path.exists(debug_log)
                        and os.path.getsize(debug_log) > 0):
                    debug_log_present = True
                    break
                time.sleep(1)
            if not debug_log_present:
                self.fail('no controller debug log for switch %s' % dp_name)

    def hup_faucet(self):
        """Send a HUP signal to the controller."""
        controller = self.get_controller()
        tcp_pattern = '%s/tcp' % controller.port
        fuser_out = controller.cmd('fuser %s -k -1' % tcp_pattern)
        self.assertTrue(re.search(r'%s:\s+\d+' % tcp_pattern, fuser_out))

    def force_faucet_reload(self, new_config):
        """Force FAUCET to reload by adding new line to config file."""
        open(os.environ['FAUCET_CONFIG'], 'a').write(new_config)
        self.hup_faucet()

    def curl_portmod(self, int_dpid, port_no, config, mask):
        """Use curl to send a portmod command via the ofctl module."""
        curl_format = ' '.join(
            ('curl -X POST -d'
             '\'{"dpid": %s, "port_no": %u, "config": %u, "mask": %u}\'',
             '%s/stats/portdesc/modify'))
        return curl_format % (int_dpid, port_no, config, mask,
                              self.ofctl_rest_url())

    def flap_all_switch_ports(self, flap_time=1):
        """Flap all ports on switch."""
        for port_no in self.port_map.itervalues():
            os.system(
                self.curl_portmod(self.dpid, port_no, ofp.OFPPC_PORT_DOWN,
                                  ofp.OFPPC_PORT_DOWN))
            time.sleep(flap_time)
            os.system(
                self.curl_portmod(self.dpid, port_no, 0, ofp.OFPPC_PORT_DOWN))

    def add_host_ipv6_address(self, host, ip_v6):
        """Add an IPv6 address to a Mininet host."""
        self.assertEquals(
            '', host.cmd('ip -6 addr add %s dev %s' % (ip_v6, host.intf())))

    def add_host_ipv6_route(self, host, ip_dst, ip_gw):
        """Add an IPv6 route to a Mininet host."""
        host.cmd('ip -6 route del %s' % ip_dst.masked())
        self.assertEquals(
            '',
            host.cmd('ip -6 route add %s via %s' % (ip_dst.masked(), ip_gw)))

    def add_host_ipv4_route(self, host, ip_dst, ip_gw):
        """Add an IPv4 route to a Mininet host."""
        host.cmd('ip -4 route del %s' % ip_dst.masked())
        self.assertEquals(
            '',
            host.cmd('ip -4 route add %s via %s' % (ip_dst.masked(), ip_gw)))

    def one_ipv4_ping(self, host, dst, retries=3):
        """Ping an IPv4 destination from a host."""
        self.require_host_learned(host)
        for _ in range(retries):
            ping_result = host.cmd('ping -c1 %s' % dst)
            if re.search(self.ONE_GOOD_PING, ping_result):
                return
        self.assertTrue(re.search(self.ONE_GOOD_PING, ping_result))

    def one_ipv4_controller_ping(self, host):
        """Ping the controller from a host with IPv4."""
        self.one_ipv4_ping(host, self.FAUCET_VIPV4.ip)
        self.verify_ipv4_host_learned_mac(host, self.FAUCET_VIPV4.ip,
                                          self.FAUCET_MAC)

    def one_ipv6_ping(self, host, dst, retries=3):
        """Ping an IPv6 destination from a host."""
        self.require_host_learned(host)
        # TODO: retry our one ping. We should not have to retry.
        for _ in range(retries):
            ping_result = host.cmd('ping6 -c1 %s' % dst)
            if re.search(self.ONE_GOOD_PING, ping_result):
                return
        self.assertTrue(re.search(self.ONE_GOOD_PING, ping_result))

    def one_ipv6_controller_ping(self, host):
        """Ping the controller from a host with IPv6."""
        self.one_ipv6_ping(host, self.FAUCET_VIPV6.ip)
        self.verify_ipv6_host_learned_mac(host, self.FAUCET_VIPV6.ip,
                                          self.FAUCET_MAC)

    def wait_for_tcp_listen(self, host, port, timeout=10):
        """Wait for a host to start listening on a port."""
        for _ in range(timeout):
            fuser_out = host.cmd('fuser -n tcp %u' % port)
            if re.search(r'.*%u/tcp.*' % port, fuser_out):
                return
            time.sleep(1)
        self.fail('%s never listened on port %u (%s)' %
                  (host, port, fuser_out))

    def serve_hello_on_tcp_port(self, host, port):
        """Serve 'hello' on a TCP port on a host."""
        host.cmd('timeout 10s echo hello | nc -l %s %u &' % (host.IP(), port))
        self.wait_for_tcp_listen(host, port)

    def verify_tp_dst_blocked(self, port, first_host, second_host):
        """Verify that a TCP port on a host is blocked from another host."""
        self.serve_hello_on_tcp_port(second_host, port)
        self.assertEquals(
            '',
            first_host.cmd('timeout 10s nc %s %u' % (second_host.IP(), port)))
        self.wait_until_matching_flow(r'"packet_count": [1-9]+.+"tp_dst": %u' %
                                      port)

    def verify_tp_dst_notblocked(self, port, first_host, second_host):
        """Verify that a TCP port on a host is NOT blocked from another host."""
        self.serve_hello_on_tcp_port(second_host, port)
        self.assertEquals(
            'hello\r\n',
            first_host.cmd('nc -w 5 %s %u' % (second_host.IP(), port)))
        self.wait_until_matching_flow(r'"packet_count": [1-9]+.+"tp_dst": %u' %
                                      port)

    def swap_host_macs(self, first_host, second_host):
        """Swap the MAC addresses of two Mininet hosts."""
        first_host_mac = first_host.MAC()
        second_host_mac = second_host.MAC()
        first_host.setMAC(second_host_mac)
        second_host.setMAC(first_host_mac)

    def start_exabgp(self, exabgp_conf, listen_address='127.0.0.1', port=179):
        """Start exabgp process on controller host."""
        self.stop_exabgp(port)
        exabgp_conf_file = os.path.join(self.tmpdir, 'exabgp.conf')
        exabgp_log = os.path.join(self.tmpdir, 'exabgp.log')
        exabgp_err = os.path.join(self.tmpdir, 'exabgp.err')
        exabgp_env = ' '.join((
            'exabgp.tcp.bind="%s"' % listen_address,
            'exabgp.tcp.port=%u' % port,
            'exabgp.log.all=true',
            'exabgp.log.routes=true',
            'exabgp.log.rib=true',
            'exabgp.log.packets=true',
            'exabgp.log.parser=true',
        ))
        open(exabgp_conf_file, 'w').write(exabgp_conf)
        controller = self.get_controller()
        controller.cmd('env %s timeout -s9 180s '
                       'stdbuf -o0 -e0 exabgp %s -d 2> %s > %s &' %
                       (exabgp_env, exabgp_conf_file, exabgp_err, exabgp_log))
        self.wait_for_tcp_listen(controller, port)
        return exabgp_log

    def wait_bgp_up(self, exabgp_log):
        """Wait for BGP to come up."""
        for _ in range(60):
            exabgp_log_content = open(exabgp_log).read()
            if exabgp_log_content.find('OPENCONFIRM') > -1:
                return
            time.sleep(1)
        self.fail('exabgp did not peer with FAUCET')

    def stop_exabgp(self, port=179):
        """Stop exabgp process on controller host."""
        controller = self.get_controller()
        controller.cmd('fuser %s/tcp -k -9' % port)

    def exabgp_updates(self, exabgp_log):
        """Verify that exabgp process has received BGP updates."""
        controller = self.get_controller()
        # exabgp should have received our BGP updates
        for _ in range(60):
            updates = controller.cmd(
                r'grep UPDATE %s |grep -Eo "\S+ next-hop \S+"' % exabgp_log)
            if updates:
                return updates
            time.sleep(1)
        self.fail('exabgp did not receive BGP updates')

    def wait_exabgp_sent_updates(self, exabgp_log):
        """Verify that exabgp process has sent BGP updates."""
        for _ in range(60):
            exabgp_log_content = open(exabgp_log).read()
            if re.search(r'>> [1-9]+[0-9]* UPDATE', exabgp_log_content):
                return
            time.sleep(1)
        self.fail('exabgp did not send BGP updates')

    def ping_all_when_learned(self, retries=3):
        """Verify all hosts can ping each other once FAUCET has learned all."""
        # Cause hosts to send traffic that FAUCET can use to learn them.
        for _ in range(retries):
            loss = self.net.pingAll()
            # we should have learned all hosts now, so should have no loss.
            for host in self.net.hosts:
                self.require_host_learned(host)
            if loss == 0:
                return
        self.assertEquals(0, loss)

    def wait_for_route_as_flow(self,
                               nexthop,
                               prefix,
                               timeout=10,
                               with_group_table=False):
        """Verify a route has been added as a flow."""
        if prefix.version == 6:
            exp_prefix = '/'.join(
                (str(prefix.masked().ip), str(prefix.netmask)))
            nw_dst_match = '"ipv6_dst": "%s"' % exp_prefix
        else:
            exp_prefix = prefix.masked().with_netmask
            nw_dst_match = '"nw_dst": "%s"' % exp_prefix
        if with_group_table:
            group_id = self.get_group_id_for_matching_flow(nw_dst_match)
            self.wait_matching_in_group_table(
                'SET_FIELD: {eth_dst:%s}' % nexthop, group_id, timeout)
        else:
            self.wait_until_matching_flow(
                'SET_FIELD: {eth_dst:%s}.+%s' % (nexthop, nw_dst_match),
                timeout)

    def host_ipv4_alias(self, host, alias_ip):
        """Add an IPv4 alias address to a host."""
        del_cmd = 'ip addr del %s/%s dev %s' % (
            alias_ip.ip, alias_ip.prefixlen, host.intf())
        add_cmd = 'ip addr add %s/%s dev %s label %s:1' % (
            alias_ip.ip, alias_ip.prefixlen, host.intf(), host.intf())
        host.cmd(del_cmd)
        self.assertEquals('', host.cmd(add_cmd))

    def verify_ipv4_host_learned_mac(self, host, ip, mac):
        learned_mac = host.cmd("arp -n %s | grep %s | awk '{ print $3 }'" %
                               (ip, ip))
        self.assertEqual(learned_mac.strip(),
                         mac,
                         msg='MAC learned on host mismatch')

    def verify_ipv4_host_learned_host(self, host, learned_host):
        learned_ip = ipaddr.IPNetwork(self.host_ipv4(learned_host))
        self.verify_ipv4_host_learned_mac(host, learned_ip.ip,
                                          learned_host.MAC())

    def verify_ipv6_host_learned_mac(self, host, ip6, mac):
        learned_mac = host.cmd("ip -6 neighbor show %s | awk '{ print $5 }'" %
                               ip6)
        self.assertEqual(learned_mac.strip(),
                         mac,
                         msg='MAC learned on host mismatch')

    def verify_ipv6_host_learned_host(self, host, learned_host):
        learned_ip6 = ipaddr.IPNetwork(self.host_ipv6(learned_host))
        self.verify_ipv6_host_learned_mac(host, learned_ip6.ip,
                                          learned_host.MAC())

    def verify_ipv4_routing(self,
                            first_host,
                            first_host_routed_ip,
                            second_host,
                            second_host_routed_ip,
                            with_group_table=False):
        """Verify one host can IPV4 route to another via FAUCET."""
        self.host_ipv4_alias(first_host, first_host_routed_ip)
        self.host_ipv4_alias(second_host, second_host_routed_ip)
        self.add_host_ipv4_route(first_host, second_host_routed_ip,
                                 self.FAUCET_VIPV4.ip)
        self.add_host_ipv4_route(second_host, first_host_routed_ip,
                                 self.FAUCET_VIPV4.ip)
        self.net.ping(hosts=(first_host, second_host))
        self.wait_for_route_as_flow(first_host.MAC(),
                                    first_host_routed_ip,
                                    with_group_table=with_group_table)
        self.wait_for_route_as_flow(second_host.MAC(),
                                    second_host_routed_ip,
                                    with_group_table=with_group_table)
        self.one_ipv4_ping(first_host, second_host_routed_ip.ip)
        self.one_ipv4_ping(second_host, first_host_routed_ip.ip)
        self.verify_ipv4_host_learned_host(first_host, second_host)
        self.verify_ipv4_host_learned_host(second_host, first_host)

    def verify_ipv4_routing_mesh(self, with_group_table=False):
        """Verify hosts can route to each other via FAUCET."""
        host_pair = self.net.hosts[:2]
        first_host, second_host = host_pair
        first_host_routed_ip = ipaddr.IPv4Network('10.0.1.1/24')
        second_host_routed_ip = ipaddr.IPv4Network('10.0.2.1/24')
        second_host_routed_ip2 = ipaddr.IPv4Network('10.0.3.1/24')
        self.verify_ipv4_routing(first_host,
                                 first_host_routed_ip,
                                 second_host,
                                 second_host_routed_ip,
                                 with_group_table=with_group_table)
        self.verify_ipv4_routing(first_host,
                                 first_host_routed_ip,
                                 second_host,
                                 second_host_routed_ip2,
                                 with_group_table=with_group_table)
        self.swap_host_macs(first_host, second_host)
        self.verify_ipv4_routing(first_host,
                                 first_host_routed_ip,
                                 second_host,
                                 second_host_routed_ip,
                                 with_group_table=with_group_table)
        self.verify_ipv4_routing(first_host,
                                 first_host_routed_ip,
                                 second_host,
                                 second_host_routed_ip2,
                                 with_group_table=with_group_table)

    def setup_ipv6_hosts_addresses(self, first_host, first_host_ip,
                                   first_host_routed_ip, second_host,
                                   second_host_ip, second_host_routed_ip):
        """Configure host IPv6 addresses for testing."""
        for host in first_host, second_host:
            host.cmd('ip -6 addr flush dev %s' % host.intf())
        self.add_host_ipv6_address(first_host, first_host_ip)
        self.add_host_ipv6_address(second_host, second_host_ip)
        self.add_host_ipv6_address(first_host, first_host_routed_ip)
        self.add_host_ipv6_address(second_host, second_host_routed_ip)
        for host in first_host, second_host:
            self.require_host_learned(host)

    def verify_ipv6_routing(self,
                            first_host,
                            first_host_ip,
                            first_host_routed_ip,
                            second_host,
                            second_host_ip,
                            second_host_routed_ip,
                            with_group_table=False):
        """Verify one host can IPV6 route to another via FAUCET."""
        self.one_ipv6_ping(first_host, second_host_ip.ip)
        self.one_ipv6_ping(second_host, first_host_ip.ip)
        self.add_host_ipv6_route(first_host, second_host_routed_ip,
                                 self.FAUCET_VIPV6.ip)
        self.add_host_ipv6_route(second_host, first_host_routed_ip,
                                 self.FAUCET_VIPV6.ip)
        self.wait_for_route_as_flow(first_host.MAC(),
                                    first_host_routed_ip,
                                    with_group_table=with_group_table)
        self.wait_for_route_as_flow(second_host.MAC(),
                                    second_host_routed_ip,
                                    with_group_table=with_group_table)
        self.one_ipv6_controller_ping(first_host)
        self.one_ipv6_controller_ping(second_host)
        self.one_ipv6_ping(first_host, second_host_routed_ip.ip)
        self.one_ipv6_ping(second_host, first_host_routed_ip.ip)
        self.verify_ipv6_host_learned_mac(first_host, second_host_ip.ip,
                                          second_host.MAC())
        self.verify_ipv6_host_learned_mac(second_host, first_host_ip.ip,
                                          first_host.MAC())

    def verify_ipv6_routing_pair(self,
                                 first_host,
                                 first_host_ip,
                                 first_host_routed_ip,
                                 second_host,
                                 second_host_ip,
                                 second_host_routed_ip,
                                 with_group_table=False):
        """Verify hosts can route IPv6 to each other via FAUCET."""
        self.setup_ipv6_hosts_addresses(first_host, first_host_ip,
                                        first_host_routed_ip, second_host,
                                        second_host_ip, second_host_routed_ip)
        self.verify_ipv6_routing(first_host,
                                 first_host_ip,
                                 first_host_routed_ip,
                                 second_host,
                                 second_host_ip,
                                 second_host_routed_ip,
                                 with_group_table=with_group_table)

    def verify_ipv6_routing_mesh(self, with_group_table=False):
        """Verify IPv6 routing between hosts and multiple subnets."""
        host_pair = self.net.hosts[:2]
        first_host, second_host = host_pair
        first_host_ip = ipaddr.IPv6Network('fc00::1:1/112')
        second_host_ip = ipaddr.IPv6Network('fc00::1:2/112')
        first_host_routed_ip = ipaddr.IPv6Network('fc00::10:1/112')
        second_host_routed_ip = ipaddr.IPv6Network('fc00::20:1/112')
        second_host_routed_ip2 = ipaddr.IPv6Network('fc00::30:1/112')
        self.verify_ipv6_routing_pair(first_host,
                                      first_host_ip,
                                      first_host_routed_ip,
                                      second_host,
                                      second_host_ip,
                                      second_host_routed_ip,
                                      with_group_table=with_group_table)
        self.verify_ipv6_routing_pair(first_host,
                                      first_host_ip,
                                      first_host_routed_ip,
                                      second_host,
                                      second_host_ip,
                                      second_host_routed_ip2,
                                      with_group_table=with_group_table)
        self.swap_host_macs(first_host, second_host)
        self.verify_ipv6_routing_pair(first_host,
                                      first_host_ip,
                                      first_host_routed_ip,
                                      second_host,
                                      second_host_ip,
                                      second_host_routed_ip,
                                      with_group_table=with_group_table)
        self.verify_ipv6_routing_pair(first_host,
                                      first_host_ip,
                                      first_host_routed_ip,
                                      second_host,
                                      second_host_ip,
                                      second_host_routed_ip2,
                                      with_group_table=with_group_table)

    def verify_invalid_bgp_route(self, pattern):
        """Check if we see the pattern in Faucet's Log"""
        controller = self.get_controller()
        count = controller.cmd('grep -c "%s" %s' %
                               (pattern, os.environ['FAUCET_LOG']))
        self.assertGreater(count, 0)
Exemplo n.º 22
0
 def get_ip6_for_flow(self, node_name, flow_id):
    if node_name in self.nodes:
        return(self.nodes[node_name].ip6net.ip + flow_id)
    else:
         return ipaddr.IPv6Network('::/128').ip