Esempio n. 1
0
    def addNetworks(self):
        """
        Add networks in the session to the scenPlan.
        """
        for net in self.coreSession.objects.itervalues():
            if not isinstance(net, coreobj.PyCoreNet):
                continue

            if nodeutils.is_node(net, NodeTypes.CONTROL_NET):
                continue

            # Do not add switches and hubs that belong to another network
            if nodeutils.is_node(net, (NodeTypes.SWITCH, NodeTypes.HUB)):
                if in_other_network(net):
                    continue

            try:
                NetworkElement(self, self, net)
            except:
                logger.exception("error adding node")
                if hasattr(net, "name") and net.name:
                    logger.warn('Unsupported net name: %s, class: %s, type: %s',
                                net.name, net.__class__.__name__, net.type)
                else:
                    logger.warn('Unsupported net class: %s', net.__class__.__name__)
Esempio n. 2
0
    def addNetworks(self):
        """
        Add networks in the session to the scenPlan.
        """
        for net in self.coreSession.objects.itervalues():
            if not isinstance(net, coreobj.PyCoreNet):
                continue

            if nodeutils.is_node(net, NodeTypes.CONTROL_NET):
                continue

            # Do not add switches and hubs that belong to another network
            if nodeutils.is_node(net, (NodeTypes.SWITCH, NodeTypes.HUB)):
                if in_other_network(net):
                    continue

            try:
                NetworkElement(self, self, net)
            except:
                logger.exception("error adding node")
                if hasattr(net, "name") and net.name:
                    logger.warn(
                        'Unsupported net name: %s, class: %s, type: %s',
                        net.name, net.__class__.__name__, net.type)
                else:
                    logger.warn('Unsupported net class: %s',
                                net.__class__.__name__)
Esempio n. 3
0
 def add_configs(self):
     if nodeutils.is_node(self.node, NodeTypes.PEER_TO_PEER):
         self.add_peer_to_peer_config()
     elif nodeutils.is_node(
             self.node,
         (NodeTypes.SWITCH, NodeTypes.HUB, NodeTypes.TUNNEL)):
         self.add_switch_hub_tunnel_config()
Esempio n. 4
0
    def __init__(self, scen_plan, parent, network_object):
        """
        Add one PyCoreNet object as one network XML element.
        """
        element_name = self.getNetworkName(scen_plan, network_object)
        NamedXmlElement.__init__(self, scen_plan, parent, "network", element_name)

        self.scenPlan = scen_plan

        self.addPoint(network_object)

        network_type = None
        if nodeutils.is_node(network_object, (NodeTypes.WIRELESS_LAN, NodeTypes.EMANE)):
            network_type = NetType.WIRELESS
        elif nodeutils.is_node(network_object, (NodeTypes.SWITCH, NodeTypes.HUB,
                                                NodeTypes.PEER_TO_PEER, NodeTypes.TUNNEL)):
            network_type = NetType.ETHERNET
        else:
            network_type = "%s" % network_object.__class__.__name__

        type_element = self.createElement("type")
        type_element.appendChild(self.createTextNode(network_type))
        self.appendChild(type_element)

        # Gather all endpoints belonging to this network
        self.endpoints = get_endpoints(network_object)

        # Special case for a network of switches and hubs
        create_alias = True
        self.l2devices = []
        if nodeutils.is_node(network_object, (NodeTypes.SWITCH, NodeTypes.HUB)):
            create_alias = False
            self.appendChild(type_element)
            self.addL2Devices(network_object)

        if create_alias:
            a = self.createAlias(Alias.ID, "%d" % int(network_object.objid))
            self.appendChild(a)

        # XXXX TODO: Move this to  channel?
        # key used with tunnel node
        if hasattr(network_object, 'grekey') and network_object.grekey is not None:
            a = self.createAlias("COREGREKEY", "%s" % network_object.grekey)
            self.appendChild(a)

        self.addNetMembers(network_object)
        self.addChannels(network_object)

        presentation_element = self.createElement("CORE:presentation")
        add_presentation_element = False
        if network_object.icon and not network_object.icon.isspace():
            presentation_element.setAttribute("icon", network_object.icon)
            add_presentation_element = True
        if network_object.canvas:
            presentation_element.setAttribute("canvas", str(network_object.canvas))
            add_presentation_element = True
        if add_presentation_element:
            self.appendChild(presentation_element)
Esempio n. 5
0
    def addNetMembers(self, network_object):
        """
        Add members to a network XML element.
        """

        for ep in self.endpoints:
            if ep.type:
                MemberElement(self.scenPlan,
                              self,
                              referenced_type=ep.type,
                              referenced_id=ep.id)

                if ep.l2devport:
                    MemberElement(self.scenPlan,
                                  self,
                                  referenced_type=MembType.INTERFACE,
                                  referenced_id="%s/%s" %
                                  (self.id, ep.l2devport))

        # XXX Revisit this
        # Create implied members given the network type
        if nodeutils.is_node(network_object, NodeTypes.TUNNEL):
            MemberElement(self.scenPlan,
                          self,
                          referenced_type=MembType.TUNNEL,
                          referenced_id="%s/%s" %
                          (network_object.name, network_object.name))
Esempio n. 6
0
    def add_virtual_host(self, physical_host, node):
        assert isinstance(node, PyCoreNode)

        # create virtual host element
        host_id = "%s/%s" % (physical_host.get("id"), node.name)
        host_element = etree.SubElement(physical_host, "testHost", id=host_id, name=node.name)

        # TODO: need to inject mapping into device element?
        self.find_device(node.name)
        # device = self.find_device(self.root.base_element, obj.name)
        # if device is None:
        #     logger.warn("corresponding XML device not found for %s", obj.name)
        #     return
        # add_mapping(device, "testHost", host_id)

        # add host type
        add_type(host_element, "virtual")

        for netif in node.netifs():
            emane_element = None
            if nodeutils.is_node(netif.net, NodeTypes.EMANE):
                emane_element = add_emane_interface(host_element, netif)

            parent_element = host_element
            if emane_element is not None:
                parent_element = emane_element

            for address in netif.addrlist:
                address_type = get_address_type(address)
                add_address(parent_element, address_type, address, netif.name)
Esempio n. 7
0
    def addInterfaces(self, device_object):
        """
        Add interfaces to a device element.
        """
        idx = 0
        for interface_object in device_object.netifs(sort=True):
            if interface_object.net and nodeutils.is_node(interface_object.net, NodeTypes.CONTROL_NET):
                continue
            if isinstance(device_object, nodes.PyCoreNode):
                interface_element = InterfaceElement(self.scenPlan, self, device_object, interface_object)
            else:  # isinstance(node, (nodes.HubNode nodes.SwitchNode)):
                interface_element = InterfaceElement(self.scenPlan, self, device_object, interface_object, idx)
            idx += 1

            netmodel = None
            if interface_object.net:
                if hasattr(interface_object.net, "model"):
                    netmodel = interface_object.net.model
            if interface_object.mtu and interface_object.mtu != 1500:
                interface_element.setAttribute("mtu", "%s" % interface_object.mtu)

            # The interfaces returned for Switches and Hubs are the interfaces of the nodes connected to them.
            # The addresses are for those interfaces. Don't include them here.
            if isinstance(device_object, nodes.PyCoreNode):
                # could use ifcObj.params, transport_type
                interface_element.addAddresses(interface_object)
                # per-interface models
                # XXX Remove???
                if netmodel and netmodel.name[:6] == "emane_":
                    cfg = self.coreSession.emane.getifcconfig(device_object.objid, interface_object, netmodel.name)
                    if cfg:
                        interface_element.addModels(((netmodel, cfg),))

            self.interfaces.append(interface_element)
Esempio n. 8
0
    def add_virtual_host(self, physical_host, node):
        if not isinstance(node, PyCoreNode):
            raise TypeError("invalid node type: %s" % node)

        # create virtual host element
        host_id = "%s/%s" % (physical_host.get("id"), node.name)
        host_element = etree.SubElement(physical_host,
                                        "testHost",
                                        id=host_id,
                                        name=node.name)

        # add host type
        add_type(host_element, "virtual")

        for netif in node.netifs():
            emane_element = None
            if nodeutils.is_node(netif.net, NodeTypes.EMANE):
                emane_element = add_emane_interface(host_element, netif)

            parent_element = host_element
            if emane_element is not None:
                parent_element = emane_element

            for address in netif.addrlist:
                address_type = get_address_type(address)
                add_address(parent_element, address_type, address, netif.name)
Esempio n. 9
0
    def boot_nodes(self):
        """
        Invoke the boot() procedure for all nodes and send back node
        messages to the GUI for node messages that had the status
        request flag.
        """
        with self._objects_lock:
            pool = ThreadPool()
            results = []

            start = time.time()
            for obj in self.objects.itervalues():
                # TODO: PyCoreNode is not the type to check
                if isinstance(obj, nodes.PyCoreNode) and not nodeutils.is_node(obj, NodeTypes.RJ45):
                    # add a control interface if configured
                    logger.info("booting node: %s", obj.name)
                    self.add_remove_control_interface(node=obj, remove=False)
                    result = pool.apply_async(self.services.boot_services, (obj,))
                    results.append(result)

            pool.close()
            pool.join()
            for result in results:
                result.get()
            logger.debug("boot run time: %s", time.time() - start)

        self.update_control_interface_hosts()
Esempio n. 10
0
def get_endpoint(node, interface):
    l2devport = None
    othernet = getattr(interface, "othernet", None)

    # reference interface of node that is part of this network
    if interface.net.objid == node.objid and interface.node:
        params = interface.getparams()
        if nodeutils.is_node(interface.net, (NodeTypes.HUB, NodeTypes.SWITCH)):
            l2devport = "%s/e%s" % (interface.net.name, interface.netindex)
        endpoint_id = "%s/%s" % (interface.node.name, interface.name)
        endpoint = Endpoint(node, interface, "interface", endpoint_id,
                            l2devport, params)
    # references another node connected to this network
    elif othernet and othernet.objid == node.objid:
        interface.swapparams("_params_up")
        params = interface.getparams()
        interface.swapparams("_params_up")
        l2devport = "%s/e%s" % (othernet.name, interface.netindex)
        endpoint_id = "%s/%s/%s" % (node.name, interface.node.name,
                                    interface.netindex)
        endpoint = Endpoint(interface.net, interface, "interface", endpoint_id,
                            l2devport, params)
    else:
        endpoint = Endpoint(
            node,
            interface,
        )

    return endpoint
Esempio n. 11
0
    def boot_nodes(self):
        """
        Invoke the boot() procedure for all nodes and send back node
        messages to the GUI for node messages that had the status
        request flag.
        """
        with self._objects_lock:
            pool = ThreadPool()
            results = []

            start = time.time()
            for obj in self.objects.itervalues():
                # TODO: PyCoreNode is not the type to check
                if isinstance(obj, nodes.PyCoreNode) and not nodeutils.is_node(
                        obj, NodeTypes.RJ45):
                    # add a control interface if configured
                    logger.info("booting node: %s", obj.name)
                    self.add_remove_control_interface(node=obj, remove=False)
                    result = pool.apply_async(self.services.boot_services,
                                              (obj, ))
                    results.append(result)

            pool.close()
            pool.join()
            for result in results:
                result.get()
            logger.debug("boot run time: %s", time.time() - start)

        self.update_control_interface_hosts()
Esempio n. 12
0
 def parse_interface(self, node, device_id, interface):
     """
     Each interface can have multiple 'address' elements.
     """
     if_name = interface.getAttribute('name')
     network = self.find_interface_network_object(interface)
     if not network:
         msg = 'skipping node \'%s\' interface \'%s\': ' \
               'unknown network' % (node.name, if_name)
         logger.warn(msg)
         assert False  # XXX for testing
     mac, ipv4, ipv6, hostname = self.parse_addresses(interface)
     if mac:
         hwaddr = MacAddress.from_string(mac[0])
     else:
         hwaddr = None
     ifindex = node.newnetif(network,
                             addrlist=ipv4 + ipv6,
                             hwaddr=hwaddr,
                             ifindex=None,
                             ifname=if_name)
     # TODO: 'hostname' addresses are unused
     msg = 'node \'%s\' interface \'%s\' connected ' \
           'to network \'%s\'' % (node.name, if_name, network.name)
     logger.info(msg)
     # set link parameters for wired links
     if nodeutils.is_node(
             network,
         (NodeTypes.HUB, NodeTypes.PEER_TO_PEER, NodeTypes.SWITCH)):
         netif = node.netif(ifindex)
         self.set_wired_link_parameters(network, netif, device_id)
Esempio n. 13
0
    def add_virtual_host(self, physical_host, node):
        assert isinstance(node, PyCoreNode)

        # create virtual host element
        host_id = "%s/%s" % (physical_host.get("id"), node.name)
        host_element = etree.SubElement(physical_host,
                                        "testHost",
                                        id=host_id,
                                        name=node.name)

        # TODO: need to inject mapping into device element?
        self.find_device(node.name)
        # device = self.find_device(self.root.base_element, obj.name)
        # if device is None:
        #     logger.warn("corresponding XML device not found for %s", obj.name)
        #     return
        # add_mapping(device, "testHost", host_id)

        # add host type
        add_type(host_element, "virtual")

        for netif in node.netifs():
            emane_element = None
            if nodeutils.is_node(netif.net, NodeTypes.EMANE):
                emane_element = add_emane_interface(host_element, netif)

            parent_element = host_element
            if emane_element is not None:
                parent_element = emane_element

            for address in netif.addrlist:
                address_type = get_address_type(address)
                add_address(parent_element, address_type, address, netif.name)
Esempio n. 14
0
    def get_node_count(self):
        """
        Returns the number of CoreNodes and CoreNets, except for those
        that are not considered in the GUI's node count.
        """

        with self._objects_lock:
            count = len(filter(lambda x: not nodeutils.is_node(x, (NodeTypes.PEER_TO_PEER, NodeTypes.CONTROL_NET)),
                               self.objects))

            # on Linux, GreTapBridges are auto-created, not part of GUI's node count
            count -= len(filter(
                lambda (x): nodeutils.is_node(x, NodeTypes.TAP_BRIDGE) and not nodeutils.is_node(x, NodeTypes.TUNNEL),
                self.objects))

        return count
Esempio n. 15
0
    def _link_wireless(self, objects, connect):
        """
        Objects to deal with when connecting/disconnecting wireless links.

        :param list objects: possible objects to deal with
        :param bool connect: link interfaces if True, unlink otherwise
        :return: nothing
        """
        objects = [x for x in objects if x]
        if len(objects) < 2:
            raise ValueError("wireless link failure: %s", objects)
        logger.debug("handling wireless linking objects(%s) connect(%s)",
                     objects, connect)
        common_networks = objects[0].commonnets(objects[1])
        if not common_networks:
            raise ValueError(
                "no common network found for wireless link/unlink")

        for common_network, interface_one, interface_two in common_networks:
            if not nodeutils.is_node(
                    common_network, [NodeTypes.WIRELESS_LAN, NodeTypes.EMANE]):
                logger.info(
                    "skipping common network that is not wireless/emane: %s",
                    common_network)
                continue

            logger.info("wireless linking connect(%s): %s - %s", connect,
                        interface_one, interface_two)
            if connect:
                common_network.link(interface_one, interface_two)
            else:
                common_network.unlink(interface_one, interface_two)
Esempio n. 16
0
def link_config(network,
                interface,
                link_options,
                devname=None,
                interface_two=None):
    """
    Convenience method for configuring a link,

    :param network: network to configure link for
    :param interface: interface to configure
    :param core.emulator.emudata.LinkOptions link_options: data to configure link with
    :param str devname: device name, default is None
    :param interface_two: other interface associated, default is None
    :return: nothing
    """
    config = {
        "netif": interface,
        "bw": link_options.bandwidth,
        "delay": link_options.delay,
        "loss": link_options.per,
        "duplicate": link_options.dup,
        "jitter": link_options.jitter,
        "netif2": interface_two
    }

    # hacky check here, because physical and emane nodes do not conform to the same linkconfig interface
    if not nodeutils.is_node(network, [NodeTypes.EMANE, NodeTypes.PHYSICAL]):
        config["devname"] = devname

    network.linkconfig(**config)
Esempio n. 17
0
    def waitfordevicenode(self):
        """
        Check for presence of a node device - tap device may not appear right away waits.

        :return: nothing
        """
        def nodedevexists():
            args = [constants.IP_BIN, "link", "show", self.name]
            return self.node.cmd(args)

        count = 0
        while True:
            result = self.waitfor(nodedevexists)
            if result:
                break

            # check if this is an EMANE interface; if so, continue
            # waiting if EMANE is still running
            # TODO: remove emane code
            should_retry = count < 5
            is_emane_node = nodeutils.is_node(self.net, NodeTypes.EMANE)
            is_emane_running = self.node.session.emane.emanerunning(self.node)
            if all([should_retry, is_emane_node, is_emane_running]):
                count += 1
            else:
                raise RuntimeError("node device failed to exist")
Esempio n. 18
0
 def parse_interface(self, node, device_id, interface):
     """
     Each interface can have multiple 'address' elements.
     """
     if_name = interface.getAttribute('name')
     network = self.find_interface_network_object(interface)
     if not network:
         msg = 'skipping node \'%s\' interface \'%s\': ' \
               'unknown network' % (node.name, if_name)
         logger.warn(msg)
         assert False  # XXX for testing
     mac, ipv4, ipv6, hostname = self.parse_addresses(interface)
     if mac:
         hwaddr = MacAddress.from_string(mac[0])
     else:
         hwaddr = None
     ifindex = node.newnetif(network, addrlist=ipv4 + ipv6, hwaddr=hwaddr, ifindex=None, ifname=if_name)
     # TODO: 'hostname' addresses are unused
     msg = 'node \'%s\' interface \'%s\' connected ' \
           'to network \'%s\'' % (node.name, if_name, network.name)
     logger.info(msg)
     # set link parameters for wired links
     if nodeutils.is_node(network, (NodeTypes.HUB, NodeTypes.PEER_TO_PEER, NodeTypes.SWITCH)):
         netif = node.netif(ifindex)
         self.set_wired_link_parameters(network, netif, device_id)
Esempio n. 19
0
 def ptpcheck(ifc):
     """
     Helper to detect whether interface is connected to a notional
     point-to-point link.
     """
     if nodeutils.is_node(ifc.net, NodeTypes.PEER_TO_PEER):
         return "  ipv6 ospf6 network point-to-point\n"
     return ""
Esempio n. 20
0
    def getNetworkName(self, scenario_plan, network_object):
        """
        Determine the name to use for this network element

        :param ScenarioPlan scenario_plan:
        :param network_object:
        :return:
        """
        if nodeutils.is_node(network_object, (NodeTypes.PEER_TO_PEER, NodeTypes.TUNNEL)):
            name = "net%s" % scenario_plan.last_network_id
            scenario_plan.last_network_id += 1
        elif network_object.name:
            name = str(network_object.name)  # could use net.brname for bridges?
        elif nodeutils.is_node(network_object, (NodeTypes.SWITCH, NodeTypes.HUB)):
            name = "lan%s" % network_object.objid
        else:
            name = ''
        return name
Esempio n. 21
0
    def setup(self):
        """
        Populate self._objs with EmaneNodes; perform distributed setup;
        associate models with EmaneNodes from self.config. Returns
        Emane.(SUCCESS, NOT_NEEDED, NOT_READY) in order to delay session
        instantiation.
        """
        logger.debug("emane setup")

        # TODO: drive this from the session object
        with self.session._objects_lock:
            for node in self.session.objects.itervalues():
                if nodeutils.is_node(node, NodeTypes.EMANE):
                    logger.debug("adding emane node: id(%s) name(%s)", node.objid, node.name)
                    self.add_node(node)

            if not self._emane_nodes:
                logger.debug("no emane nodes in session")
                return EmaneManager.NOT_NEEDED

        # control network bridge required for EMANE 0.9.2
        # - needs to be configured before checkdistributed() for distributed
        # - needs to exist when eventservice binds to it (initeventservice)
        if self.session.master:
            otadev = self.get_config("otamanagerdevice")
            netidx = self.session.get_control_net_index(otadev)
            logger.debug("emane ota manager device: index(%s) otadev(%s)", netidx, otadev)
            if netidx < 0:
                logger.error("EMANE cannot start, check core config. invalid OTA device provided: %s", otadev)
                return EmaneManager.NOT_READY

            ctrlnet = self.session.add_remove_control_net(net_index=netidx, remove=False, conf_required=False)
            self.distributedctrlnet(ctrlnet)
            eventdev = self.get_config("eventservicedevice")
            logger.debug("emane event service device: eventdev(%s)", eventdev)
            if eventdev != otadev:
                netidx = self.session.get_control_net_index(eventdev)
                logger.debug("emane event service device index: %s", netidx)
                if netidx < 0:
                    logger.error("EMANE cannot start, check core config. invalid event service device: %s", eventdev)
                    return EmaneManager.NOT_READY

                ctrlnet = self.session.add_remove_control_net(net_index=netidx, remove=False, conf_required=False)
                self.distributedctrlnet(ctrlnet)

        if self.checkdistributed():
            # we are slave, but haven't received a platformid yet
            platform_id_start = "platform_id_start"
            default_values = self.emane_config.default_values()
            value = self.get_config(platform_id_start)
            if value == default_values[platform_id_start]:
                return EmaneManager.NOT_READY

        self.check_node_models()
        return EmaneManager.SUCCESS
Esempio n. 22
0
def get_endpoint(network_object, interface_object):
    """
    Create an Endpoint object given the network and the interface of interest
    """
    ep = None
    l2devport = None

    # skip if either are none
    if not network_object or not interface_object:
        return ep

    # if ifcObj references an interface of a node and is part of this network
    if interface_object.net.objid == network_object.objid and hasattr(interface_object,
                                                                      'node') and interface_object.node:
        params = interface_object.getparams()
        if nodeutils.is_node(interface_object.net, (NodeTypes.HUB, NodeTypes.SWITCH)):
            l2devport = "%s/e%d" % (interface_object.net.name, interface_object.net.getifindex(interface_object))
        ep = Endpoint(network_object,
                      interface_object,
                      type=MembType.INTERFACE,
                      id="%s/%s" % (interface_object.node.name, interface_object.name),
                      l2devport=l2devport,
                      params=params)

    # else if ifcObj references another node and is connected to this network
    elif hasattr(interface_object, "othernet"):
        if interface_object.othernet.objid == network_object.objid:
            # #hack used for upstream parameters for link between switches
            # #(see LxBrNet.linknet())
            interface_object.swapparams('_params_up')
            params = interface_object.getparams()
            interface_object.swapparams('_params_up')
            owner = interface_object.net
            l2devport = "%s/e%d" % (
                interface_object.othernet.name, interface_object.othernet.getifindex(interface_object))

            # Create the endpoint.
            # XXX the interface index might not match what is shown in the gui. For switches and hubs,
            # The gui assigns its index but doesn't pass it to the daemon and vice versa.
            # The gui stores it's index in the IMN file, which it reads and writes without daemon intervention.
            # Fix this!
            ep = Endpoint(owner,
                          interface_object,
                          type=MembType.INTERFACE,
                          id="%s/%s/e%d" % (network_object.name, owner.name, owner.getifindex(interface_object)),
                          l2devport=l2devport,
                          params=params)
        # else this node has an interface that belongs to another network
        # i.e. a switch/hub interface connected to another switch/hub and CORE has the other switch/hub
        # as the containing network
        else:
            ep = Endpoint(network_object, interface_object, type=None, id=None, l2devport=None, params=None)

    return ep
Esempio n. 23
0
    def _link_nodes(self, node_one_id, node_two_id):
        """
        Convenience method for retrieving nodes within link data.

        :param int node_one_id: node one id
        :param int node_two_id: node two id
        :return: nodes, network nodes if present, and tunnel if present
        :rtype: tuple
        """
        logger.debug("link message between node1(%s) and node2(%s)",
                     node_one_id, node_two_id)

        # values to fill
        net_one = None
        net_two = None

        # retrieve node one
        node_one = self.get_object(node_one_id)
        node_two = self.get_object(node_two_id)

        # both node ids are provided
        tunnel = self.broker.gettunnel(node_one_id, node_two_id)
        logger.debug("tunnel between nodes: %s", tunnel)
        if nodeutils.is_node(tunnel, NodeTypes.TAP_BRIDGE):
            net_one = tunnel
            if tunnel.remotenum == node_one_id:
                node_one = None
            else:
                node_two = None
        # physical node connected via gre tap tunnel
        elif tunnel:
            if tunnel.remotenum == node_one_id:
                node_one = None
            else:
                node_two = None

        if is_net_node(node_one):
            if not net_one:
                net_one = node_one
            else:
                net_two = node_one
            node_one = None

        if is_net_node(node_two):
            if not net_one:
                net_one = node_two
            else:
                net_two = node_two
            node_two = None

        logger.debug(
            "link node types n1(%s) n2(%s) net1(%s) net2(%s) tunnel(%s)",
            node_one, node_two, net_one, net_two, tunnel)
        return node_one, node_two, net_one, net_two, tunnel
Esempio n. 24
0
    def get_node_count(self):
        """
        Returns the number of CoreNodes and CoreNets, except for those
        that are not considered in the GUI's node count.
        """

        with self._objects_lock:
            count = len(
                filter(
                    lambda x: not nodeutils.is_node(x, (
                        NodeTypes.PEER_TO_PEER, NodeTypes.CONTROL_NET)),
                    self.objects))

            # on Linux, GreTapBridges are auto-created, not part of GUI's node count
            count -= len(
                filter(
                    lambda (x): nodeutils.is_node(x, NodeTypes.TAP_BRIDGE) and
                    not nodeutils.is_node(x, NodeTypes.TUNNEL), self.objects))

        return count
Esempio n. 25
0
 def rj45check(ifc):
     """
     Helper to detect whether interface is connected an external RJ45
     link.
     """
     if ifc.net:
         for peerifc in ifc.net.netifs():
             if peerifc == ifc:
                 continue
             if nodeutils.is_node(peerifc, NodeTypes.RJ45):
                 return True
     return False
Esempio n. 26
0
    def getNetworkName(self, scenario_plan, network_object):
        """
        Determine the name to use for this network element

        :param ScenarioPlan scenario_plan:
        :param network_object:
        :return:
        """
        if nodeutils.is_node(network_object,
                             (NodeTypes.PEER_TO_PEER, NodeTypes.TUNNEL)):
            name = "net%s" % scenario_plan.last_network_id
            scenario_plan.last_network_id += 1
        elif network_object.name:
            name = str(
                network_object.name)  # could use net.brname for bridges?
        elif nodeutils.is_node(network_object,
                               (NodeTypes.SWITCH, NodeTypes.HUB)):
            name = "lan%s" % network_object.objid
        else:
            name = ''
        return name
Esempio n. 27
0
    def newnetif(self,
                 net=None,
                 addrlist=None,
                 hwaddr=None,
                 ifindex=None,
                 ifname=None):
        """
        Create a new network interface.

        :param net: network to associate with
        :param list addrlist: addresses to add on the interface
        :param core.misc.ipaddress.MacAddress hwaddr: hardware address to set for interface
        :param int ifindex: index of interface to create
        :param str ifname: name for interface
        :return: interface index
        :rtype: int
        """
        self.lock.acquire()
        try:
            # TODO: see if you can move this to emane specific code
            if nodeutils.is_node(net, NodeTypes.EMANE):
                ifindex = self.newtuntap(ifindex=ifindex,
                                         ifname=ifname,
                                         net=net)
                # TUN/TAP is not ready for addressing yet; the device may
                #   take some time to appear, and installing it into a
                #   namespace after it has been bound removes addressing;
                #   save addresses with the interface now
                self.attachnet(ifindex, net)
                netif = self.netif(ifindex)
                netif.sethwaddr(hwaddr)
                for addr in utils.maketuple(addrlist):
                    netif.addaddr(addr)
                return ifindex
            else:
                ifindex = self.newveth(ifindex=ifindex, ifname=ifname, net=net)

            if net is not None:
                self.attachnet(ifindex, net)

            if hwaddr:
                self.sethwaddr(ifindex, hwaddr)

            if addrlist:
                for addr in utils.maketuple(addrlist):
                    self.addaddr(ifindex, addr)

            self.ifup(ifindex)
            return ifindex
        finally:
            self.lock.release()
Esempio n. 28
0
    def write_network(self, node):
        # ignore p2p and other nodes that are not part of the api
        if not node.apitype:
            return

        # ignore nodes tied to a different network
        if nodeutils.is_node(node, (NodeTypes.SWITCH, NodeTypes.HUB)):
            for netif in node.netifs(sort=True):
                othernet = getattr(netif, "othernet", None)
                if othernet and othernet.objid != node.objid:
                    logger.info("writer ignoring node(%s) othernet(%s)", node.name, othernet.name)
                    return

        network = NetworkElement(self.session, node)
        self.networks.append(network.element)
Esempio n. 29
0
    def write_network(self, node):
        # ignore p2p and other nodes that are not part of the api
        if not node.apitype:
            return

        # ignore nodes tied to a different network
        if nodeutils.is_node(node, (NodeTypes.SWITCH, NodeTypes.HUB)):
            for netif in node.netifs(sort=True):
                othernet = getattr(netif, "othernet", None)
                if othernet and othernet.objid != node.objid:
                    logger.info("writer ignoring node(%s) othernet(%s)",
                                node.name, othernet.name)
                    return

        network = NetworkElement(self.session, node)
        self.networks.append(network.element)
Esempio n. 30
0
    def generatequaggaifcconfig(cls, node, ifc):
        cfg = cls.mtucheck(ifc)
        # Uncomment the following line to use Address Family Translation for IPv4
        cfg += "  ipv6 ospf6 instance-id 65\n"
        if ifc.net is not None and nodeutils.is_node(ifc.net, (NodeTypes.WIRELESS_LAN, NodeTypes.EMANE)):
            return cfg + """\
  ipv6 ospf6 hello-interval 2
  ipv6 ospf6 dead-interval 6
  ipv6 ospf6 retransmit-interval 5
  ipv6 ospf6 network manet-designated-router
  ipv6 ospf6 diffhellos
  ipv6 ospf6 adjacencyconnectivity uniconnected
  ipv6 ospf6 lsafullness mincostlsa
"""
        else:
            return cfg
Esempio n. 31
0
    def get_l2_devices(self):
        l2_devices = []
        found_l2_devices = []
        found_endpoints = []
        if nodeutils.is_node(self.node, (NodeTypes.SWITCH, NodeTypes.HUB)):
            for endpoint in self.endpoints:
                if endpoint.type and endpoint.network.objid != self.node.objid:
                    downstream_l2_devices, downstream_endpoints = get_downstream_l2_devices(endpoint.network)
                    found_l2_devices.extend(downstream_l2_devices)
                    found_endpoints.extend(downstream_endpoints)

            for l2_device in found_l2_devices:
                pass

            self.endpoints.extend(found_endpoints)
        return l2_devices
Esempio n. 32
0
    def get_l2_devices(self):
        l2_devices = []
        found_l2_devices = []
        found_endpoints = []
        if nodeutils.is_node(self.node, (NodeTypes.SWITCH, NodeTypes.HUB)):
            for endpoint in self.endpoints:
                if endpoint.type and endpoint.network.objid != self.node.objid:
                    downstream_l2_devices, downstream_endpoints = get_downstream_l2_devices(
                        endpoint.network)
                    found_l2_devices.extend(downstream_l2_devices)
                    found_endpoints.extend(downstream_endpoints)

            for l2_device in found_l2_devices:
                pass

            self.endpoints.extend(found_endpoints)
        return l2_devices
Esempio n. 33
0
 def link_layer2_devices(self, device1, ifname1, device2, ifname2):
     """
     Link two layer-2 devices together.
     """
     devid1 = device1.getAttribute('id')
     dev1 = self.get_core_object(devid1)
     devid2 = device2.getAttribute('id')
     dev2 = self.get_core_object(devid2)
     assert dev1 and dev2  # XXX for testing
     if dev1 and dev2:
         # TODO: review this
         if nodeutils.is_node(dev2, NodeTypes.RJ45):
             # RJ45 nodes have different linknet()
             netif = dev2.linknet(dev1)
         else:
             netif = dev1.linknet(dev2)
         self.set_wired_link_parameters(dev1, netif, devid1, ifname1)
Esempio n. 34
0
 def link_layer2_devices(self, device1, ifname1, device2, ifname2):
     """
     Link two layer-2 devices together.
     """
     devid1 = device1.getAttribute('id')
     dev1 = self.get_core_object(devid1)
     devid2 = device2.getAttribute('id')
     dev2 = self.get_core_object(devid2)
     assert dev1 and dev2  # XXX for testing
     if dev1 and dev2:
         # TODO: review this
         if nodeutils.is_node(dev2, NodeTypes.RJ45):
             # RJ45 nodes have different linknet()
             netif = dev2.linknet(dev1)
         else:
             netif = dev1.linknet(dev2)
         self.set_wired_link_parameters(dev1, netif, devid1, ifname1)
Esempio n. 35
0
    def sendobjs(self):
        """
        Session has already started, and the SDT3D GUI later connects.
        Send all node and link objects for display. Otherwise, nodes and
        links will only be drawn when they have been updated (e.g. moved).

        :return: nothing
        """
        nets = []
        with self.session._objects_lock:
            for obj in self.session.objects.itervalues():
                if isinstance(obj, PyCoreNet):
                    nets.append(obj)
                if not isinstance(obj, PyCoreObj):
                    continue
                (x, y, z) = obj.getposition()
                if x is None or y is None:
                    continue
                self.updatenode(obj.objid, MessageFlags.ADD.value, x, y, z,
                                obj.name, obj.type, obj.icon)
            for nodenum in sorted(self.remotes.keys()):
                r = self.remotes[nodenum]
                x, y, z = r.pos
                self.updatenode(nodenum, MessageFlags.ADD.value, x, y, z,
                                r.name, r.type, r.icon)

            for net in nets:
                all_links = net.all_link_data(flags=MessageFlags.ADD.value)
                for link_data in all_links:
                    is_wireless = nodeutils.is_node(net, (NodeTypes.WIRELESS_LAN, NodeTypes.EMANE))
                    wireless_link = link_data.message_type == LinkTypes.WIRELESS.value
                    if is_wireless and link_data.node1_id == net.objid:
                        continue

                    self.updatelink(
                        link_data.node1_id,
                        link_data.node2_id,
                        MessageFlags.ADD.value,
                        wireless_link
                    )

            for n1num in sorted(self.remotes.keys()):
                r = self.remotes[n1num]
                for n2num, wireless_link in r.links:
                    self.updatelink(n1num, n2num, MessageFlags.ADD.value, wireless_link)
Esempio n. 36
0
File: sdt.py Progetto: gsomlo/core
    def sendobjs(self):
        """
        Session has already started, and the SDT3D GUI later connects.
        Send all node and link objects for display. Otherwise, nodes and
        links will only be drawn when they have been updated (e.g. moved).

        :return: nothing
        """
        nets = []
        with self.session._objects_lock:
            for obj in self.session.objects.itervalues():
                if isinstance(obj, PyCoreNet):
                    nets.append(obj)
                if not isinstance(obj, PyCoreObj):
                    continue
                (x, y, z) = obj.getposition()
                if x is None or y is None:
                    continue
                self.updatenode(obj.objid, MessageFlags.ADD.value, x, y, z,
                                obj.name, obj.type, obj.icon)
            for nodenum in sorted(self.remotes.keys()):
                r = self.remotes[nodenum]
                x, y, z = r.pos
                self.updatenode(nodenum, MessageFlags.ADD.value, x, y, z,
                                r.name, r.type, r.icon)

            for net in nets:
                all_links = net.all_link_data(flags=MessageFlags.ADD.value)
                for link_data in all_links:
                    is_wireless = nodeutils.is_node(net, (NodeTypes.WIRELESS_LAN, NodeTypes.EMANE))
                    wireless_link = link_data.message_type == LinkTypes.WIRELESS.value
                    if is_wireless and link_data.node1_id == net.objid:
                        continue

                    self.updatelink(
                        link_data.node1_id,
                        link_data.node2_id,
                        MessageFlags.ADD.value,
                        wireless_link
                    )

            for n1num in sorted(self.remotes.keys()):
                r = self.remotes[n1num]
                for n2num, wireless_link in r.links:
                    self.updatelink(n1num, n2num, MessageFlags.ADD.value, wireless_link)
Esempio n. 37
0
    def generate_config(cls, node, filename):
        if filename == cls.configs[0]:
            transport_commands = []
            for interface in node.netifs(sort=True):
                network_node = node.session.get_object(interface.net.objid)
                if nodeutils.is_node(network_node, NodeTypes.EMANE):
                    config = node.session.emane.get_configs(network_node.objid, network_node.model.name)
                    if config and emanexml.is_external(config):
                        nem_id = network_node.getnemid(interface)
                        command = "emanetransportd -r -l 0 -d ../transportdaemon%s.xml" % nem_id
                        transport_commands.append(command)
            transport_commands = "\n".join(transport_commands)
            return """
emanegentransportxml -o ../ ../platform%s.xml
%s
""" % (node.objid, transport_commands)
        else:
            raise ValueError
Esempio n. 38
0
    def write_nodes(self):
        self.networks = etree.SubElement(self.scenario, "networks")
        self.devices = etree.SubElement(self.scenario, "devices")

        links = []
        for node in self.session.objects.itervalues():
            # network node
            if isinstance(node, coreobj.PyCoreNet) and not nodeutils.is_node(
                    node, NodeTypes.CONTROL_NET):
                self.write_network(node)
            # device node
            elif isinstance(node, nodes.PyCoreNode):
                self.write_device(node)

            # add known links
            links.extend(node.all_link_data(0))

        return links
Esempio n. 39
0
    def generate_config(cls, node, filename):
        if filename == cls.configs[0]:
            transport_commands = []
            for interface in node.netifs(sort=True):
                network_node = node.session.get_object(interface.net.objid)
                if nodeutils.is_node(network_node, NodeTypes.EMANE):
                    config = node.session.emane.get_configs(
                        network_node.objid, network_node.model.name)
                    if config and emanexml.is_external(config):
                        nem_id = network_node.getnemid(interface)
                        command = "emanetransportd -r -l 0 -d ../transportdaemon%s.xml" % nem_id
                        transport_commands.append(command)
            transport_commands = "\n".join(transport_commands)
            return """
emanegentransportxml -o ../ ../platform%s.xml
%s
""" % (node.objid, transport_commands)
        else:
            raise ValueError
Esempio n. 40
0
File: vnode.py Progetto: gsomlo/core
    def newnetif(self, net=None, addrlist=None, hwaddr=None, ifindex=None, ifname=None):
        """
        Create a new network interface.

        :param net: network to associate with
        :param list addrlist: addresses to add on the interface
        :param core.misc.ipaddress.MacAddress hwaddr: hardware address to set for interface
        :param int ifindex: index of interface to create
        :param str ifname: name for interface
        :return: interface index
        :rtype: int
        """
        if not addrlist:
            addrlist = []

        with self.lock:
            # TODO: see if you can move this to emane specific code
            if nodeutils.is_node(net, NodeTypes.EMANE):
                ifindex = self.newtuntap(ifindex=ifindex, ifname=ifname, net=net)
                # TUN/TAP is not ready for addressing yet; the device may
                #   take some time to appear, and installing it into a
                #   namespace after it has been bound removes addressing;
                #   save addresses with the interface now
                self.attachnet(ifindex, net)
                netif = self.netif(ifindex)
                netif.sethwaddr(hwaddr)
                for address in utils.make_tuple(addrlist):
                    netif.addaddr(address)
                return ifindex
            else:
                ifindex = self.newveth(ifindex=ifindex, ifname=ifname, net=net)

            if net is not None:
                self.attachnet(ifindex, net)

            if hwaddr:
                self.sethwaddr(ifindex, hwaddr)

            for address in utils.make_tuple(addrlist):
                self.addaddr(ifindex, address)

            self.ifup(ifindex)
            return ifindex
Esempio n. 41
0
    def write_nodes(self):
        self.networks = etree.SubElement(self.scenario, "networks")
        self.devices = etree.SubElement(self.scenario, "devices")

        links = []
        for node in self.session.objects.itervalues():
            logger.info("writer adding node(%s)", node.name)

            # network node
            if isinstance(node, coreobj.PyCoreNet) and not nodeutils.is_node(node, NodeTypes.CONTROL_NET):
                self.write_network(node)
            # device node
            elif isinstance(node, nodes.PyCoreNode):
                self.write_device(node)

            # add known links
            links.extend(node.all_link_data(0))

        return links
Esempio n. 42
0
    def addInterfaces(self, device_object):
        """
        Add interfaces to a device element.
        """
        idx = 0
        for interface_object in device_object.netifs(sort=True):
            if interface_object.net and nodeutils.is_node(
                    interface_object.net, NodeTypes.CONTROL_NET):
                continue
            if isinstance(device_object, nodes.PyCoreNode):
                interface_element = InterfaceElement(self.scenPlan, self,
                                                     device_object,
                                                     interface_object)
            else:  # isinstance(node, (nodes.HubNode nodes.SwitchNode)):
                interface_element = InterfaceElement(self.scenPlan, self,
                                                     device_object,
                                                     interface_object, idx)
            idx += 1

            netmodel = None
            if interface_object.net:
                if hasattr(interface_object.net, "model"):
                    netmodel = interface_object.net.model
            if interface_object.mtu and interface_object.mtu != 1500:
                interface_element.setAttribute("mtu",
                                               "%s" % interface_object.mtu)

            # The interfaces returned for Switches and Hubs are the interfaces of the nodes connected to them.
            # The addresses are for those interfaces. Don't include them here.
            if isinstance(device_object, nodes.PyCoreNode):
                # could use ifcObj.params, transport_type
                interface_element.addAddresses(interface_object)
                # per-interface models
                # XXX Remove???
                if netmodel and netmodel.name[:6] == "emane_":
                    cfg = self.coreSession.emane.getifcconfig(
                        device_object.objid, netmodel.name, None,
                        interface_object)
                    if cfg:
                        interface_element.addModels(((netmodel, cfg), ))

            self.interfaces.append(interface_element)
Esempio n. 43
0
    def addNetMembers(self, network_object):
        """
        Add members to a network XML element.
        """

        for ep in self.endpoints:
            if ep.type:
                MemberElement(self.scenPlan, self, referenced_type=ep.type, referenced_id=ep.id)

                if ep.l2devport:
                    MemberElement(self.scenPlan,
                                  self,
                                  referenced_type=MembType.INTERFACE,
                                  referenced_id="%s/%s" % (self.id, ep.l2devport))

        # XXX Revisit this
        # Create implied members given the network type
        if nodeutils.is_node(network_object, NodeTypes.TUNNEL):
            MemberElement(self.scenPlan, self, referenced_type=MembType.TUNNEL,
                          referenced_id="%s/%s" % (network_object.name, network_object.name))
Esempio n. 44
0
File: sdt.py Progetto: gsomlo/core
    def wlancheck(self, nodenum):
        """
        Helper returns True if a node number corresponds to a WlanNode or EmaneNode.

        :param int nodenum: node id to check
        :return: True if node is wlan or emane, False otherwise
        :rtype: bool
        """
        if nodenum in self.remotes:
            type = self.remotes[nodenum].type
            if type in ("wlan", "emane"):
                return True
        else:
            try:
                n = self.session.get_object(nodenum)
            except KeyError:
                return False
            if nodeutils.is_node(n, (NodeTypes.WIRELESS_LAN, NodeTypes.EMANE)):
                return True
        return False
Esempio n. 45
0
File: sdt.py Progetto: yrs1/core
    def wlancheck(self, nodenum):
        """
        Helper returns True if a node number corresponds to a WlanNode or EmaneNode.

        :param int nodenum: node id to check
        :return: True if node is wlan or emane, False otherwise
        :rtype: bool
        """
        if nodenum in self.remotes:
            node_type = self.remotes[nodenum].type
            if node_type in ("wlan", "emane"):
                return True
        else:
            try:
                n = self.session.get_object(nodenum)
            except KeyError:
                return False
            if nodeutils.is_node(n, (NodeTypes.WIRELESS_LAN, NodeTypes.EMANE)):
                return True
        return False
Esempio n. 46
0
def get_endpoint(node, interface):
    l2devport = None
    othernet = getattr(interface, "othernet", None)

    # reference interface of node that is part of this network
    if interface.net.objid == node.objid and interface.node:
        params = interface.getparams()
        if nodeutils.is_node(interface.net, (NodeTypes.HUB, NodeTypes.SWITCH)):
            l2devport = "%s/e%s" % (interface.net.name, interface.netindex)
        endpoint_id = "%s/%s" % (interface.node.name, interface.name)
        endpoint = Endpoint(
            node,
            interface,
            "interface",
            endpoint_id,
            l2devport,
            params
        )
    # references another node connected to this network
    elif othernet and othernet.objid == node.objid:
        interface.swapparams("_params_up")
        params = interface.getparams()
        interface.swapparams("_params_up")
        l2devport = "%s/e%s" % (othernet.name, interface.netindex)
        endpoint_id = "%s/%s/%s" % (node.name, interface.node.name, interface.netindex)
        endpoint = Endpoint(
            interface.net,
            interface,
            "interface",
            endpoint_id,
            l2devport,
            params
        )
    else:
        endpoint = Endpoint(
            node,
            interface,
        )

    return endpoint
Esempio n. 47
0
    def waitfordevicenode(self):
        """
        Check for presence of a node device - tap device may not appear right away waits.

        :return: nothing
        """
        def nodedevexists():
            cmd = (constants.IP_BIN, "link", "show", self.name)
            return self.node.cmd(cmd)

        count = 0
        while True:
            try:
                self.waitfor(nodedevexists)
                break
            except RuntimeError as e:
                # check if this is an EMANE interface; if so, continue
                # waiting if EMANE is still running
                # TODO: remove emane code
                if count < 5 and nodeutils.is_node(self.net, NodeTypes.EMANE) and \
                        self.node.session.emane.emanerunning(self.node):
                    count += 1
                else:
                    raise e
Esempio n. 48
0
 def add_virtual_host(self, parent, obj):
     assert isinstance(obj, nodes.PyCoreNode)
     el = self.add_host(parent, obj.name)
     device = self.find_device(self.root.base_element, obj.name)
     if device is None:
         logger.warn('corresponding XML device not found for %s' % obj.name)
         return
     self.add_mapping(device, 'testHost', el.getAttribute('id'))
     self.add_type(el, 'virtual')
     for netif in obj.netifs():
         for address in netif.addrlist:
             addr, slash, prefixlen = address.partition('/')
             if ipaddress.is_ipv4_address(addr):
                 addr_type = 'IPv4'
             elif ipaddress.is_ipv6_address(addr):
                 addr_type = 'IPv6'
             else:
                 raise NotImplementedError
             self.add_address(el, addr_type, address, netif.name)
         if nodeutils.is_node(netif.net, NodeTypes.EMANE):
             nem = self.add_emane_interface(parent, el, netif)
             interface = self.find_interface(device, netif.name)
             self.add_mapping(interface, 'nem', nem.getAttribute('id'))
     return el
Esempio n. 49
0
 def add_virtual_host(self, parent, obj):
     assert isinstance(obj, nodes.PyCoreNode)
     el = self.add_host(parent, obj.name)
     device = self.find_device(self.root.base_element, obj.name)
     if device is None:
         logger.warn('corresponding XML device not found for %s' % obj.name)
         return
     self.add_mapping(device, 'testHost', el.getAttribute('id'))
     self.add_type(el, 'virtual')
     for netif in obj.netifs():
         for address in netif.addrlist:
             addr, slash, prefixlen = address.partition('/')
             if ipaddress.is_ipv4_address(addr):
                 addr_type = 'IPv4'
             elif ipaddress.is_ipv6_address(addr):
                 addr_type = 'IPv6'
             else:
                 raise NotImplementedError
             self.add_address(el, addr_type, address, netif.name)
         if nodeutils.is_node(netif.net, NodeTypes.EMANE):
             nem = self.add_emane_interface(parent, el, netif)
             interface = self.find_interface(device, netif.name)
             self.add_mapping(interface, 'nem', nem.getAttribute('id'))
     return el
Esempio n. 50
0
 def add_configs(self):
     if nodeutils.is_node(self.node, NodeTypes.PEER_TO_PEER):
         self.add_peer_to_peer_config()
     elif nodeutils.is_node(self.node, (NodeTypes.SWITCH, NodeTypes.HUB, NodeTypes.TUNNEL)):
         self.add_switch_hub_tunnel_config()
Esempio n. 51
0
def get_endpoint(network_object, interface_object):
    """
    Create an Endpoint object given the network and the interface of interest
    """
    ep = None
    l2devport = None

    # skip if either are none
    if not network_object or not interface_object:
        return ep

    # if ifcObj references an interface of a node and is part of this network
    if interface_object.net.objid == network_object.objid and hasattr(
            interface_object, 'node') and interface_object.node:
        params = interface_object.getparams()
        if nodeutils.is_node(interface_object.net,
                             (NodeTypes.HUB, NodeTypes.SWITCH)):
            l2devport = "%s/e%d" % (
                interface_object.net.name,
                interface_object.net.getifindex(interface_object))
        ep = Endpoint(network_object,
                      interface_object,
                      type=MembType.INTERFACE,
                      id="%s/%s" %
                      (interface_object.node.name, interface_object.name),
                      l2devport=l2devport,
                      params=params)

    # else if ifcObj references another node and is connected to this network
    elif hasattr(interface_object, "othernet"):
        if interface_object.othernet.objid == network_object.objid:
            # #hack used for upstream parameters for link between switches
            # #(see LxBrNet.linknet())
            interface_object.swapparams('_params_up')
            params = interface_object.getparams()
            interface_object.swapparams('_params_up')
            owner = interface_object.net
            l2devport = "%s/e%d" % (
                interface_object.othernet.name,
                interface_object.othernet.getifindex(interface_object))

            # Create the endpoint.
            # XXX the interface index might not match what is shown in the gui. For switches and hubs,
            # The gui assigns its index but doesn't pass it to the daemon and vice versa.
            # The gui stores it's index in the IMN file, which it reads and writes without daemon intervention.
            # Fix this!
            ep = Endpoint(owner,
                          interface_object,
                          type=MembType.INTERFACE,
                          id="%s/%s/e%d" %
                          (network_object.name, owner.name,
                           owner.getifindex(interface_object)),
                          l2devport=l2devport,
                          params=params)
        # else this node has an interface that belongs to another network
        # i.e. a switch/hub interface connected to another switch/hub and CORE has the other switch/hub
        # as the containing network
        else:
            ep = Endpoint(network_object,
                          interface_object,
                          type=None,
                          id=None,
                          l2devport=None,
                          params=None)

    return ep
Esempio n. 52
0
    def addChannels(self, network_object):
        """
        Add channels to a network XML element
        """

        if nodeutils.is_node(network_object,
                             (NodeTypes.WIRELESS_LAN, NodeTypes.EMANE)):
            modelconfigs = network_object.session.mobility.getmodels(
                network_object)
            modelconfigs += network_object.session.emane.getmodels(
                network_object)
            chan = None
            for model, conf in modelconfigs:
                # Handle mobility parameters below
                if model.config_type == RegisterTlvs.MOBILITY.value:
                    continue

                # Create the channel
                if chan is None:
                    name = "wireless"
                    chan = ChannelElement(self.scenPlan,
                                          self,
                                          network_object,
                                          channel_type=model.name,
                                          channel_name=name,
                                          channel_domain="CORE")

                # Add wireless model parameters
                for i, key in enumerate(model.getnames()):
                    value = conf[i]
                    if value is not None:
                        chan.addParameter(key, model.valueof(key, conf))

            for model, conf in modelconfigs:
                if model.config_type == RegisterTlvs.MOBILITY.value:
                    # Add wireless mobility parameters
                    mobility = XmlElement(self.scenPlan, chan, "CORE:mobility")
                    # Add a type child
                    type_element = self.createElement("type")
                    type_element.appendChild(self.createTextNode(model.name))
                    mobility.appendChild(type_element)
                    for i, key in enumerate(model.getnames()):
                        value = conf[i]
                        if value is not None:
                            mobility.addParameter(key, value)

            # Add members to the channel
            if chan is not None:
                chan.addChannelMembers(self.endpoints)
                self.appendChild(chan.base_element)
        elif nodeutils.is_node(network_object, NodeTypes.PEER_TO_PEER):
            if len(self.endpoints) < 2:
                if len(self.endpoints) == 1:
                    logger.warn('Pt2Pt network with only 1 endpoint: %s',
                                self.endpoints[0].id)
                else:
                    logger.warn(
                        'Pt2Pt network with no endpoints encountered in %s',
                        network_object.name)
                return
            name = "chan%d" % (0)
            chan = ChannelElement(self.scenPlan,
                                  self,
                                  network_object,
                                  channel_type=NetType.ETHERNET,
                                  channel_name=name)

            # Add interface parameters
            if self.endpoints[0].params != self.endpoints[1].params:
                logger.warn('Pt2Pt Endpoint  parameters do not match in %s',
                            network_object.name)
            for key, value in self.endpoints[0].params:
                # XXX lifted from original addnetem function. revisit this.
                # default netem parameters are 0 or None
                if value is None or value == 0:
                    continue
                if key == "has_netem" or key == "has_tbf":
                    continue
                chan.addParameter(key, value)

            # Add members to the channel
            chan.addChannelMembers(self.endpoints)
            self.appendChild(chan)

        elif nodeutils.is_node(
                network_object,
            (NodeTypes.SWITCH, NodeTypes.HUB, NodeTypes.TUNNEL)):
            cidx = 0
            channels = []
            for ep in self.endpoints:
                # Create one channel member per ep
                if ep.type:
                    name = "chan%d" % cidx
                    chan = ChannelElement(self.scenPlan,
                                          self,
                                          network_object,
                                          channel_type=NetType.ETHERNET,
                                          channel_name=name)

                    # Add interface parameters
                    for key, value in ep.params:
                        # XXX lifted from original addnetem function. revisit this.
                        # default netem parameters are 0 or None
                        if value is None or value == 0:
                            continue
                        if key == "has_netem" or key == "has_tbf":
                            continue
                        chan.addParameter(key, value)

                    # Add members to the channel
                    chan.addChannelMembers(ep)
                    channels.append(chan)
                    cidx += 1

            for chan in channels:
                self.appendChild(chan)
Esempio n. 53
0
    def create_link_element(self, link_data):
        link_element = etree.Element("link")
        add_attribute(link_element, "node_one", link_data.node1_id)
        add_attribute(link_element, "node_two", link_data.node2_id)

        # check for interface one
        if link_data.interface1_id is not None:
            interface_one = etree.Element("interface_one")
            node = self.session.get_object(link_data.node1_id)
            node_interface = node.netif(link_data.interface1_id)

            add_attribute(interface_one, "id", link_data.interface1_id)
            add_attribute(interface_one, "name", node_interface.name)
            add_attribute(interface_one, "mac", link_data.interface1_mac)
            add_attribute(interface_one, "ip4", link_data.interface1_ip4)
            add_attribute(interface_one, "ip4_mask", link_data.interface1_ip4_mask)
            add_attribute(interface_one, "ip6", link_data.interface1_ip6)
            add_attribute(interface_one, "ip6_mask", link_data.interface1_ip6_mask)

            # check if emane interface
            if nodeutils.is_node(node_interface.net, NodeTypes.EMANE):
                nem = node_interface.net.getnemid(node_interface)
                add_attribute(interface_one, "nem", nem)

            link_element.append(interface_one)

        # check for interface two
        if link_data.interface2_id is not None:
            interface_two = etree.Element("interface_two")
            node = self.session.get_object(link_data.node2_id)
            node_interface = node.netif(link_data.interface2_id)

            add_attribute(interface_two, "id", link_data.interface2_id)
            add_attribute(interface_two, "name", node_interface.name)
            add_attribute(interface_two, "mac", link_data.interface2_mac)
            add_attribute(interface_two, "ip4", link_data.interface2_ip4)
            add_attribute(interface_two, "ip4_mask", link_data.interface2_ip4_mask)
            add_attribute(interface_two, "ip6", link_data.interface2_ip6)
            add_attribute(interface_two, "ip6_mask", link_data.interface2_ip6_mask)

            # check if emane interface
            if nodeutils.is_node(node_interface.net, NodeTypes.EMANE):
                nem = node_interface.net.getnemid(node_interface)
                add_attribute(interface_two, "nem", nem)

            link_element.append(interface_two)

        # check for options
        options = etree.Element("options")
        add_attribute(options, "delay", link_data.delay)
        add_attribute(options, "bandwidth", link_data.bandwidth)
        add_attribute(options, "per", link_data.per)
        add_attribute(options, "dup", link_data.dup)
        add_attribute(options, "jitter", link_data.jitter)
        add_attribute(options, "mer", link_data.mer)
        add_attribute(options, "burst", link_data.burst)
        add_attribute(options, "mburst", link_data.mburst)
        add_attribute(options, "type", link_data.link_type)
        add_attribute(options, "gui_attributes", link_data.gui_attributes)
        add_attribute(options, "unidirectional", link_data.unidirectional)
        add_attribute(options, "emulation_id", link_data.emulation_id)
        add_attribute(options, "network_id", link_data.network_id)
        add_attribute(options, "key", link_data.key)
        add_attribute(options, "opaque", link_data.opaque)
        add_attribute(options, "session", link_data.session)
        if options.items():
            link_element.append(options)

        return link_element
Esempio n. 54
0
    def addChannels(self, network_object):
        """
        Add channels to a network XML element
        """

        if nodeutils.is_node(network_object, (NodeTypes.WIRELESS_LAN, NodeTypes.EMANE)):
            modelconfigs = network_object.session.mobility.get_models(network_object)
            modelconfigs += network_object.session.emane.get_models(network_object)
            chan = None

            for model, conf in modelconfigs:
                # Handle mobility parameters below
                if model.config_type == RegisterTlvs.MOBILITY.value:
                    continue

                # Create the channel
                if chan is None:
                    name = "wireless"
                    chan = ChannelElement(self.scenPlan, self, network_object,
                                          channel_type=model.name,
                                          channel_name=name,
                                          channel_domain="CORE")

                # Add wireless model parameters
                for key, value in conf.iteritems():
                    if value is not None:
                        chan.addParameter(key, value)

            for model, conf in modelconfigs:
                if model.config_type == RegisterTlvs.MOBILITY.value:
                    # Add wireless mobility parameters
                    mobility = XmlElement(self.scenPlan, chan, "CORE:mobility")
                    # Add a type child
                    type_element = self.createElement("type")
                    type_element.appendChild(self.createTextNode(model.name))
                    mobility.appendChild(type_element)

                    for key, value in conf.iteritems():
                        if value is not None:
                            mobility.addParameter(key, value)

            # Add members to the channel
            if chan is not None:
                chan.addChannelMembers(self.endpoints)
                self.appendChild(chan.base_element)
        elif nodeutils.is_node(network_object, NodeTypes.PEER_TO_PEER):
            if len(self.endpoints) < 2:
                if len(self.endpoints) == 1:
                    logger.warn('Pt2Pt network with only 1 endpoint: %s', self.endpoints[0].id)
                else:
                    logger.warn('Pt2Pt network with no endpoints encountered in %s', network_object.name)
                return
            name = "chan%d" % (0)
            chan = ChannelElement(self.scenPlan, self, network_object,
                                  channel_type=NetType.ETHERNET,
                                  channel_name=name)

            # Add interface parameters
            if self.endpoints[0].params != self.endpoints[1].params:
                logger.warn('Pt2Pt Endpoint  parameters do not match in %s', network_object.name)
            for key, value in self.endpoints[0].params:
                # XXX lifted from original addnetem function. revisit this.
                # default netem parameters are 0 or None
                if value is None or value == 0:
                    continue
                if key == "has_netem" or key == "has_tbf":
                    continue
                chan.addParameter(key, value)

            # Add members to the channel
            chan.addChannelMembers(self.endpoints)
            self.appendChild(chan)

        elif nodeutils.is_node(network_object, (NodeTypes.SWITCH, NodeTypes.HUB, NodeTypes.TUNNEL)):
            cidx = 0
            channels = []
            for ep in self.endpoints:
                # Create one channel member per ep
                if ep.type:
                    name = "chan%d" % cidx
                    chan = ChannelElement(self.scenPlan, self, network_object, channel_type=NetType.ETHERNET,
                                          channel_name=name)

                    # Add interface parameters
                    for key, value in ep.params:
                        # XXX lifted from original addnetem function. revisit this.
                        # default netem parameters are 0 or None
                        if value is None or value == 0:
                            continue
                        if key == "has_netem" or key == "has_tbf":
                            continue
                        chan.addParameter(key, value)

                    # Add members to the channel
                    chan.addChannelMembers(ep)
                    channels.append(chan)
                    cidx += 1

            for chan in channels:
                self.appendChild(chan)
Esempio n. 55
0
    def addnettunnel(self, node_id):
        """
        Add network tunnel between node and broker.

        :param int node_id: node id of network to add tunnel to
        :return: list of gre taps
        :rtype: list
        """
        try:
            net = self.session.get_object(node_id)
            logger.info("adding net tunnel for: id(%s) %s", node_id, net)
        except KeyError:
            raise KeyError("network node %s not found" % node_id)

        # add other nets here that do not require tunnels
        if nodeutils.is_node(net, NodeTypes.EMANE_NET):
            logger.warn("emane network does not require a tunnel")
            return None

        server_interface = getattr(net, "serverintf", None)
        if nodeutils.is_node(net, NodeTypes.CONTROL_NET) and server_interface is not None:
            logger.warn("control networks with server interfaces do not need a tunnel")
            return None

        servers = self.getserversbynode(node_id)
        if len(servers) < 2:
            logger.warn("not enough servers to create a tunnel: %s", servers)
            return None

        hosts = []
        for server in servers:
            if server.host is None:
                continue
            logger.info("adding server host for net tunnel: %s", server.host)
            hosts.append(server.host)

        if len(hosts) == 0:
            for session_client in self.session_clients:
                # get IP address from API message sender (master)
                if session_client.client_address != "":
                    address = session_client.client_address[0]
                    logger.info("adding session_client host: %s", address)
                    hosts.append(address)

        r = []
        for host in hosts:
            if self.myip:
                # we are the remote emulation server
                myip = self.myip
            else:
                # we are the session master
                myip = host
            key = self.tunnelkey(node_id, IpAddress.to_int(myip))
            if key in self.tunnels.keys():
                logger.info("tunnel already exists, returning existing tunnel: %s", key)
                gt = self.tunnels[key]
                r.append(gt)
                continue
            logger.info("adding tunnel for net %s to %s with key %s", node_id, host, key)
            gt = GreTap(node=None, name=None, session=self.session, remoteip=host, key=key)
            self.tunnels[key] = gt
            r.append(gt)
            # attaching to net will later allow gt to be destroyed
            # during net.shutdown()
            net.attach(gt)

        return r