initial pass on converting corens3 to use latest code and small cleanup

This commit is contained in:
Blake J. Harnden 2017-08-17 13:29:19 -07:00
parent fc7fb0f76c
commit f282f4ea15
7 changed files with 457 additions and 476 deletions

View file

@ -1,22 +1,9 @@
# Copyright (c)2011-2012 the Boeing Company. """
# See the LICENSE file included in this directory. corens3
"""corens3 Python package containing CORE components for use
Python package containing CORE components for use
with the ns-3 simulator. with the ns-3 simulator.
See http://www.nrl.navy.mil/itd/ncs/products/core and See http://www.nrl.navy.mil/itd/ncs/products/core and
http://code.google.com/p/coreemu/ for more information on CORE. http://code.google.com/p/coreemu/ for more information on CORE.
Pieces can be imported individually, for example
import corens3
or everything listed in __all__ can be imported using
from corens3 import *
""" """
__all__ = []

View file

@ -1,95 +1,103 @@
# """
# CORE
# Copyright (c)2011-2013 the Boeing Company.
# See the LICENSE file included in this directory.
#
# author: Jeff Ahrenholz <jeffrey.m.ahrenholz@boeing.com>
#
'''
ns3.py: defines classes for running emulations with ns-3 simulated networks. ns3.py: defines classes for running emulations with ns-3 simulated networks.
''' """
import sys, os, threading, time import subprocess
import threading
import time
from core.netns.nodes import CoreNode import ns.core
from core.coreobj import PyCoreNet import ns.internet
from core.session import Session
from core.misc import ipaddr
from core.constants import *
from core.misc.utils import maketuple, check_call
from core.api import coreapi
from core.mobility import WayPointMobility
try:
import ns.core
except Exception, e:
print "Could not locate the ns-3 Python bindings!"
print "Try running again from within the ns-3 './waf shell'\n"
raise Exception, e
import ns.lte import ns.lte
import ns.mobility import ns.mobility
import ns.network import ns.network
import ns.internet
import ns.tap_bridge import ns.tap_bridge
import ns.wifi import ns.wifi
import ns.wimax import ns.wimax
from core import constants
from core import logger
from core.coreobj import PyCoreNet
from core.enumerations import EventTypes
from core.enumerations import LinkTypes
from core.enumerations import NodeTypes
from core.misc.utils import maketuple
from core.mobility import WayPointMobility
from core.netns.nodes import CoreNode
from core.session import Session
ns.core.GlobalValue.Bind(
"SimulatorImplementationType",
ns.core.StringValue("ns3::RealtimeSimulatorImpl")
)
ns.core.GlobalValue.Bind(
"ChecksumEnabled",
ns.core.BooleanValue("true")
)
ns.core.GlobalValue.Bind("SimulatorImplementationType",
ns.core.StringValue("ns3::RealtimeSimulatorImpl"))
ns.core.GlobalValue.Bind("ChecksumEnabled", ns.core.BooleanValue("true"))
class CoreNs3Node(CoreNode, ns.network.Node): class CoreNs3Node(CoreNode, ns.network.Node):
''' The CoreNs3Node is both a CoreNode backed by a network namespace and """
The CoreNs3Node is both a CoreNode backed by a network namespace and
an ns-3 Node simulator object. When linked to simulated networks, the TunTap an ns-3 Node simulator object. When linked to simulated networks, the TunTap
device will be used. device will be used.
''' """
def __init__(self, *args, **kwds): def __init__(self, *args, **kwds):
ns.network.Node.__init__(self) ns.network.Node.__init__(self)
objid = self.GetId() + 1 # ns-3 ID starts at 0, CORE uses 1 # ns-3 ID starts at 0, CORE uses 1
objid = self.GetId() + 1
if 'objid' not in kwds: if 'objid' not in kwds:
kwds['objid'] = objid kwds['objid'] = objid
CoreNode.__init__(self, *args, **kwds) CoreNode.__init__(self, *args, **kwds)
def newnetif(self, net = None, addrlist = [], hwaddr = None, def newnetif(self, net=None, addrlist=None, hwaddr=None, ifindex=None, ifname=None):
ifindex = None, ifname = None): """
''' Add a network interface. If we are attaching to a CoreNs3Net, this Add a network interface. If we are attaching to a CoreNs3Net, this
will be a TunTap. Otherwise dispatch to CoreNode.newnetif(). will be a TunTap. Otherwise dispatch to CoreNode.newnetif().
''' """
if not addrlist:
addrlist = []
if not isinstance(net, CoreNs3Net): if not isinstance(net, CoreNs3Net):
return CoreNode.newnetif(self, net, addrlist, hwaddr, ifindex, return CoreNode.newnetif(self, net, addrlist, hwaddr, ifindex, ifname)
ifname) ifindex = self.newtuntap(ifindex=ifindex, ifname=ifname, net=net)
ifindex = self.newtuntap(ifindex = ifindex, ifname = ifname, net = net)
self.attachnet(ifindex, net) self.attachnet(ifindex, net)
netif = self.netif(ifindex) netif = self.netif(ifindex)
netif.sethwaddr(hwaddr) netif.sethwaddr(hwaddr)
for addr in maketuple(addrlist): for addr in maketuple(addrlist):
netif.addaddr(addr) netif.addaddr(addr)
addrstr = netif.addrlist[0] addrstr = netif.addrlist[0]
(addr, mask) = addrstr.split('/') (addr, mask) = addrstr.split('/')
tap = net._tapdevs[netif] tap = net._tapdevs[netif]
tap.SetAttribute("IpAddress", tap.SetAttribute(
ns.network.Ipv4AddressValue(ns.network.Ipv4Address(addr))) "IpAddress",
tap.SetAttribute("Netmask", ns.network.Ipv4AddressValue(ns.network.Ipv4Address(addr))
ns.network.Ipv4MaskValue(ns.network.Ipv4Mask("/" + mask))) )
tap.SetAttribute(
"Netmask",
ns.network.Ipv4MaskValue(ns.network.Ipv4Mask("/" + mask))
)
ns.core.Simulator.Schedule(ns.core.Time('0'), netif.install) ns.core.Simulator.Schedule(ns.core.Time('0'), netif.install)
return ifindex return ifindex
def getns3position(self): def getns3position(self):
''' Return the ns-3 (x, y, z) position of a node. """
''' Return the ns-3 (x, y, z) position of a node.
"""
try: try:
mm = self.GetObject(ns.mobility.MobilityModel.GetTypeId()) mm = self.GetObject(ns.mobility.MobilityModel.GetTypeId())
pos = mm.GetPosition() pos = mm.GetPosition()
return (pos.x, pos.y, pos.z) return pos.x, pos.y, pos.z
except AttributeError: except AttributeError:
self.warn("ns-3 mobility model not found") self.warn("ns-3 mobility model not found")
return (0,0,0) return 0, 0, 0
def setns3position(self, x, y, z): def setns3position(self, x, y, z):
''' Set the ns-3 (x, y, z) position of a node. """
''' Set the ns-3 (x, y, z) position of a node.
"""
try: try:
mm = self.GetObject(ns.mobility.MobilityModel.GetTypeId()) mm = self.GetObject(ns.mobility.MobilityModel.GetTypeId())
if z is None: if z is None:
@ -98,72 +106,83 @@ class CoreNs3Node(CoreNode, ns.network.Node):
except AttributeError: except AttributeError:
self.warn("ns-3 mobility model not found, not setting position") self.warn("ns-3 mobility model not found, not setting position")
class CoreNs3Net(PyCoreNet): class CoreNs3Net(PyCoreNet):
''' The CoreNs3Net is a helper PyCoreNet object. Networks are represented """
The CoreNs3Net is a helper PyCoreNet object. Networks are represented
entirely in simulation with the TunTap device bridging the emulated and entirely in simulation with the TunTap device bridging the emulated and
simulated worlds. simulated worlds.
''' """
apitype = coreapi.CORE_NODE_WLAN apitype = NodeTypes.WIRELESS_LAN.value
linktype = coreapi.CORE_LINK_WIRELESS linktype = LinkTypes.WIRELESS.value
type = "wlan" # icon used # icon used
type = "wlan"
def __init__(self, session, objid = None, name = None, verbose = False, def __init__(self, session, objid=None, name=None, start=True, policy=None):
start = True, policy = None):
PyCoreNet.__init__(self, session, objid, name) PyCoreNet.__init__(self, session, objid, name)
self.tapbridge = ns.tap_bridge.TapBridgeHelper() self.tapbridge = ns.tap_bridge.TapBridgeHelper()
self._ns3devs = {} self._ns3devs = {}
self._tapdevs = {} self._tapdevs = {}
def attach(self, netif): def attach(self, netif):
''' Invoked from netif.attach(). Create a TAP device using the TapBridge """
Invoked from netif.attach(). Create a TAP device using the TapBridge
object. Call getns3dev() to get model-specific device. object. Call getns3dev() to get model-specific device.
''' """
self._netif[netif] = netif self._netif[netif] = netif
self._linked[netif] = {} self._linked[netif] = {}
ns3dev = self.getns3dev(netif.node) ns3dev = self.getns3dev(netif.node)
tap = self.tapbridge.Install(netif.node, ns3dev) tap = self.tapbridge.Install(netif.node, ns3dev)
tap.SetMode(ns.tap_bridge.TapBridge.CONFIGURE_LOCAL) tap.SetMode(ns.tap_bridge.TapBridge.CONFIGURE_LOCAL)
tap.SetAttribute("DeviceName", ns.core.StringValue(netif.localname)) tap.SetAttribute(
"DeviceName",
ns.core.StringValue(netif.localname)
)
self._ns3devs[netif] = ns3dev self._ns3devs[netif] = ns3dev
self._tapdevs[netif] = tap self._tapdevs[netif] = tap
def getns3dev(self, node): def getns3dev(self, node):
''' Implement depending on network helper. Install this network onto """
Implement depending on network helper. Install this network onto
the given node and return the device. Register the ns3 device into the given node and return the device. Register the ns3 device into
self._ns3devs self._ns3devs
''' """
raise NotImplementedError raise NotImplementedError
def findns3dev(self, node): def findns3dev(self, node):
''' Given a node, return the interface and ns3 device associated with """
Given a node, return the interface and ns3 device associated with
this network. this network.
''' """
for netif in node.netifs(): for netif in node.netifs():
if netif in self._ns3devs: if netif in self._ns3devs:
return netif, self._ns3devs[netif] return netif, self._ns3devs[netif]
return None, None return None, None
def shutdown(self): def shutdown(self):
''' Session.shutdown() will invoke this. """
''' Session.shutdown() will invoke this.
"""
pass pass
def usecorepositions(self): def usecorepositions(self):
''' Set position callbacks for interfaces on this net so the CORE GUI """
Set position callbacks for interfaces on this net so the CORE GUI
can update the ns-3 node position when moved with the mouse. can update the ns-3 node position when moved with the mouse.
''' """
for netif in self.netifs(): for netif in self.netifs():
netif.poshook = self.setns3position netif.poshook = self.setns3position
def setns3position(self, netif, x, y, z): def setns3position(self, netif, x, y, z):
#print "setns3position: %s (%s, %s, %s)" % (netif.node.name, x, y, z) logger.info("setns3position: %s (%s, %s, %s)", netif.node.name, x, y, z)
netif.node.setns3position(x, y, z) netif.node.setns3position(x, y, z)
class Ns3LteNet(CoreNs3Net): class Ns3LteNet(CoreNs3Net):
def __init__(self, *args, **kwds): def __init__(self, *args, **kwds):
''' Uses a LteHelper to create an ns-3 based LTE network. """
''' Uses a LteHelper to create an ns-3 based LTE network.
"""
CoreNs3Net.__init__(self, *args, **kwds) CoreNs3Net.__init__(self, *args, **kwds)
self.lte = ns.lte.LteHelper() self.lte = ns.lte.LteHelper()
# enhanced NodeB node list # enhanced NodeB node list
@ -172,23 +191,26 @@ class Ns3LteNet(CoreNs3Net):
self.ulsubchannels = None self.ulsubchannels = None
def setsubchannels(self, downlink, uplink): def setsubchannels(self, downlink, uplink):
''' Set the downlink/uplink subchannels, which are a list of ints. """
Set the downlink/uplink subchannels, which are a list of ints.
These should be set prior to using CoreNs3Node.newnetif(). These should be set prior to using CoreNs3Node.newnetif().
''' """
self.dlsubchannels = downlink self.dlsubchannels = downlink
self.ulsubchannels = uplink self.ulsubchannels = uplink
def setnodeb(self, node): def setnodeb(self, node):
''' Mark the given node as a nodeb (base transceiver station) """
''' Mark the given node as a nodeb (base transceiver station)
"""
self.enbnodes.append(node) self.enbnodes.append(node)
def linknodeb(self, node, nodeb, mob, mobb): def linknodeb(self, node, nodeb, mob, mobb):
''' Register user equipment with a nodeb. """
Register user equipment with a nodeb.
Optionally install mobility model while we have the ns-3 devs handy. Optionally install mobility model while we have the ns-3 devs handy.
''' """
(tmp, nodebdev) = self.findns3dev(nodeb) tmp, nodebdev = self.findns3dev(nodeb)
(tmp, dev) = self.findns3dev(node) tmp, dev = self.findns3dev(node)
if nodebdev is None or dev is None: if nodebdev is None or dev is None:
raise KeyError, "ns-3 device for node not found" raise KeyError, "ns-3 device for node not found"
self.lte.RegisterUeToTheEnb(dev, nodebdev) self.lte.RegisterUeToTheEnb(dev, nodebdev)
@ -196,10 +218,11 @@ class Ns3LteNet(CoreNs3Net):
self.lte.AddMobility(dev.GetPhy(), mob) self.lte.AddMobility(dev.GetPhy(), mob)
if mobb: if mobb:
self.lte.AddDownlinkChannelRealization(mobb, mob, dev.GetPhy()) self.lte.AddDownlinkChannelRealization(mobb, mob, dev.GetPhy())
def getns3dev(self, node): def getns3dev(self, node):
''' Get the ns3 NetDevice using the LteHelper. """
''' Get the ns3 NetDevice using the LteHelper.
"""
if node in self.enbnodes: if node in self.enbnodes:
devtype = ns.lte.LteHelper.DEVICE_TYPE_ENODEB devtype = ns.lte.LteHelper.DEVICE_TYPE_ENODEB
else: else:
@ -211,40 +234,44 @@ class Ns3LteNet(CoreNs3Net):
return devs.Get(0) return devs.Get(0)
def attach(self, netif): def attach(self, netif):
''' Invoked from netif.attach(). Create a TAP device using the TapBridge """
Invoked from netif.attach(). Create a TAP device using the TapBridge
object. Call getns3dev() to get model-specific device. object. Call getns3dev() to get model-specific device.
''' """
self._netif[netif] = netif self._netif[netif] = netif
self._linked[netif] = {} self._linked[netif] = {}
ns3dev = self.getns3dev(netif.node) ns3dev = self.getns3dev(netif.node)
self.tapbridge.SetAttribute("Mode", ns.core.StringValue("UseLocal")) self.tapbridge.SetAttribute("Mode", ns.core.StringValue("UseLocal"))
#self.tapbridge.SetAttribute("Mode", # self.tapbridge.SetAttribute("Mode",
# ns.core.IntegerValue(ns.tap_bridge.TapBridge.USE_LOCAL)) # ns.core.IntegerValue(ns.tap_bridge.TapBridge.USE_LOCAL))
tap = self.tapbridge.Install(netif.node, ns3dev) tap = self.tapbridge.Install(netif.node, ns3dev)
#tap.SetMode(ns.tap_bridge.TapBridge.USE_LOCAL) # tap.SetMode(ns.tap_bridge.TapBridge.USE_LOCAL)
print "using TAP device %s for %s/%s" % \ logger.info("using TAP device %s for %s/%s", netif.localname, netif.node.name, netif.name)
(netif.localname, netif.node.name, netif.name) subprocess.check_call(['tunctl', '-t', netif.localname, '-n'])
check_call(['tunctl', '-t', netif.localname, '-n']) # check_call([IP_BIN, 'link', 'set', 'dev', netif.localname, \
#check_call([IP_BIN, 'link', 'set', 'dev', netif.localname, \
# 'address', '%s' % netif.hwaddr]) # 'address', '%s' % netif.hwaddr])
check_call([IP_BIN, 'link', 'set', netif.localname, 'up']) subprocess.check_call([constants.IP_BIN, 'link', 'set', netif.localname, 'up'])
tap.SetAttribute("DeviceName", ns.core.StringValue(netif.localname)) tap.SetAttribute("DeviceName", ns.core.StringValue(netif.localname))
self._ns3devs[netif] = ns3dev self._ns3devs[netif] = ns3dev
self._tapdevs[netif] = tap self._tapdevs[netif] = tap
class Ns3WifiNet(CoreNs3Net): class Ns3WifiNet(CoreNs3Net):
def __init__(self, *args, **kwds): def __init__(self, *args, **kwds):
''' Uses a WifiHelper to create an ns-3 based Wifi network. """
''' Uses a WifiHelper to create an ns-3 based Wifi network.
"""
rate = kwds.pop('rate', 'OfdmRate54Mbps') rate = kwds.pop('rate', 'OfdmRate54Mbps')
CoreNs3Net.__init__(self, *args, **kwds) CoreNs3Net.__init__(self, *args, **kwds)
self.wifi = ns.wifi.WifiHelper().Default() self.wifi = ns.wifi.WifiHelper().Default()
self.wifi.SetStandard(ns.wifi.WIFI_PHY_STANDARD_80211a) self.wifi.SetStandard(ns.wifi.WIFI_PHY_STANDARD_80211a)
self.wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager", self.wifi.SetRemoteStationManager(
"DataMode", "ns3::ConstantRateWifiManager",
ns.core.StringValue(rate), "DataMode",
"NonUnicastMode", ns.core.StringValue(rate),
ns.core.StringValue(rate)) "NonUnicastMode",
ns.core.StringValue(rate)
)
self.mac = ns.wifi.NqosWifiMacHelper.Default() self.mac = ns.wifi.NqosWifiMacHelper.Default()
self.mac.SetType("ns3::AdhocWifiMac") self.mac.SetType("ns3::AdhocWifiMac")
@ -253,12 +280,13 @@ class Ns3WifiNet(CoreNs3Net):
self.phy.SetChannel(channel.Create()) self.phy.SetChannel(channel.Create())
def getns3dev(self, node): def getns3dev(self, node):
''' Get the ns3 NetDevice using the WifiHelper. """
''' Get the ns3 NetDevice using the WifiHelper.
"""
devs = self.wifi.Install(self.phy, self.mac, node) devs = self.wifi.Install(self.phy, self.mac, node)
return devs.Get(0) return devs.Get(0)
class Ns3WimaxNet(CoreNs3Net): class Ns3WimaxNet(CoreNs3Net):
def __init__(self, *args, **kwds): def __init__(self, *args, **kwds):
CoreNs3Net.__init__(self, *args, **kwds) CoreNs3Net.__init__(self, *args, **kwds)
@ -267,10 +295,10 @@ class Ns3WimaxNet(CoreNs3Net):
self.phy = ns.wimax.WimaxHelper.SIMPLE_PHY_TYPE_OFDM self.phy = ns.wimax.WimaxHelper.SIMPLE_PHY_TYPE_OFDM
# base station node list # base station node list
self.bsnodes = [] self.bsnodes = []
def setbasestation(self, node): def setbasestation(self, node):
self.bsnodes.append(node) self.bsnodes.append(node)
def getns3dev(self, node): def getns3dev(self, node):
if node in self.bsnodes: if node in self.bsnodes:
devtype = ns.wimax.WimaxHelper.DEVICE_TYPE_BASE_STATION devtype = ns.wimax.WimaxHelper.DEVICE_TYPE_BASE_STATION
@ -283,95 +311,105 @@ class Ns3WimaxNet(CoreNs3Net):
# debug # debug
self.wimax.EnableAscii("wimax-device-%s" % node.name, devs) self.wimax.EnableAscii("wimax-device-%s" % node.name, devs)
return devs.Get(0) return devs.Get(0)
@staticmethod @staticmethod
def ipv4netifaddr(netif): def ipv4netifaddr(netif):
for addr in netif.addrlist: for addr in netif.addrlist:
if ':' in addr: if ':' in addr:
continue # skip ipv6 # skip ipv6
continue
ip = ns.network.Ipv4Address(addr.split('/')[0]) ip = ns.network.Ipv4Address(addr.split('/')[0])
mask = ns.network.Ipv4Mask('/' + addr.split('/')[1]) mask = ns.network.Ipv4Mask('/' + addr.split('/')[1])
return (ip, mask) return ip, mask
return (None, None) return None, None
def addflow(self, node1, node2, upclass, downclass): def addflow(self, node1, node2, upclass, downclass):
''' Add a Wimax service flow between two nodes. """
''' Add a Wimax service flow between two nodes.
(netif1, ns3dev1) = self.findns3dev(node1) """
(netif2, ns3dev2) = self.findns3dev(node2) netif1, ns3dev1 = self.findns3dev(node1)
netif2, ns3dev2 = self.findns3dev(node2)
if not netif1 or not netif2: if not netif1 or not netif2:
raise ValueError, "interface not found" raise ValueError, "interface not found"
(addr1, mask1) = self.ipv4netifaddr(netif1) addr1, mask1 = self.ipv4netifaddr(netif1)
(addr2, mask2) = self.ipv4netifaddr(netif2) addr2, mask2 = self.ipv4netifaddr(netif2)
clargs1 = (addr1, mask1, addr2, mask2) + downclass clargs1 = (addr1, mask1, addr2, mask2) + downclass
clargs2 = (addr2, mask2, addr1, mask1) + upclass clargs2 = (addr2, mask2, addr1, mask1) + upclass
clrec1 = ns.wimax.IpcsClassifierRecord(*clargs1) clrec1 = ns.wimax.IpcsClassifierRecord(*clargs1)
clrec2 = ns.wimax.IpcsClassifierRecord(*clargs2) clrec2 = ns.wimax.IpcsClassifierRecord(*clargs2)
ns3dev1.AddServiceFlow( \ ns3dev1.AddServiceFlow(self.wimax.CreateServiceFlow(
self.wimax.CreateServiceFlow(ns.wimax.ServiceFlow.SF_DIRECTION_DOWN, ns.wimax.ServiceFlow.SF_DIRECTION_DOWN,
ns.wimax.ServiceFlow.SF_TYPE_RTPS, clrec1)) ns.wimax.ServiceFlow.SF_TYPE_RTPS, clrec1)
ns3dev1.AddServiceFlow( \ )
self.wimax.CreateServiceFlow(ns.wimax.ServiceFlow.SF_DIRECTION_UP, ns3dev1.AddServiceFlow(self.wimax.CreateServiceFlow(
ns.wimax.ServiceFlow.SF_TYPE_RTPS, clrec2)) ns.wimax.ServiceFlow.SF_DIRECTION_UP,
ns3dev2.AddServiceFlow( \ ns.wimax.ServiceFlow.SF_TYPE_RTPS, clrec2)
self.wimax.CreateServiceFlow(ns.wimax.ServiceFlow.SF_DIRECTION_DOWN, )
ns.wimax.ServiceFlow.SF_TYPE_RTPS, clrec2)) ns3dev2.AddServiceFlow(self.wimax.CreateServiceFlow(
ns3dev2.AddServiceFlow( \ ns.wimax.ServiceFlow.SF_DIRECTION_DOWN,
self.wimax.CreateServiceFlow(ns.wimax.ServiceFlow.SF_DIRECTION_UP, ns.wimax.ServiceFlow.SF_TYPE_RTPS, clrec2)
ns.wimax.ServiceFlow.SF_TYPE_RTPS, clrec1)) )
ns3dev2.AddServiceFlow(self.wimax.CreateServiceFlow(
ns.wimax.ServiceFlow.SF_DIRECTION_UP,
ns.wimax.ServiceFlow.SF_TYPE_RTPS, clrec1)
)
class Ns3Session(Session): class Ns3Session(Session):
''' A Session that starts an ns-3 simulation thread. """
''' A Session that starts an ns-3 simulation thread.
def __init__(self, persistent = False, duration=600): """
def __init__(self, persistent=False, duration=600):
self.duration = duration self.duration = duration
self.nodes = ns.network.NodeContainer() self.nodes = ns.network.NodeContainer()
self.mobhelper = ns.mobility.MobilityHelper() self.mobhelper = ns.mobility.MobilityHelper()
Session.__init__(self, persistent = persistent) Session.__init__(self, persistent=persistent)
def run(self, vis=False): def run(self, vis=False):
''' Run the ns-3 simulation and return the simulator thread. """
''' Run the ns-3 simulation and return the simulator thread.
"""
def runthread(): def runthread():
ns.core.Simulator.Stop(ns.core.Seconds(self.duration)) ns.core.Simulator.Stop(ns.core.Seconds(self.duration))
print "running ns-3 simulation for %d seconds" % self.duration logger.info("running ns-3 simulation for %d seconds", self.duration)
if vis: if vis:
try: try:
import visualizer import visualizer
except ImportError: except ImportError:
print "visualizer is not available" logger.exception("visualizer is not available")
ns.core.Simulator.Run() ns.core.Simulator.Run()
else: else:
visualizer.start() visualizer.start()
else: else:
ns.core.Simulator.Run() ns.core.Simulator.Run()
#self.evq.run() # event queue may have WayPointMobility events
self.setstate(coreapi.CORE_EVENT_RUNTIME_STATE, info=True, # self.evq.run() # event queue may have WayPointMobility events
sendevent=True) self.set_state(EventTypes.RUNTIME_STATE.value, send_event=True)
t = threading.Thread(target = runthread) t = threading.Thread(target=runthread)
t.daemon = True t.daemon = True
t.start() t.start()
return t return t
def shutdown(self): def shutdown(self):
# TODO: the following line tends to segfault ns-3 (and therefore # TODO: the following line tends to segfault ns-3 (and therefore core-daemon)
# core-daemon)
ns.core.Simulator.Destroy() ns.core.Simulator.Destroy()
Session.shutdown(self) Session.shutdown(self)
def addnode(self, name): def addnode(self, name):
''' A convenience helper for Session.addobj(), for adding CoreNs3Nodes """
A convenience helper for Session.addobj(), for adding CoreNs3Nodes
to this session. Keeps a NodeContainer for later use. to this session. Keeps a NodeContainer for later use.
''' """
n = self.addobj(cls = CoreNs3Node, name=name) n = self.add_object(cls=CoreNs3Node, name=name)
self.nodes.Add(n) self.nodes.Add(n)
return n return n
def setupconstantmobility(self): def setupconstantmobility(self):
''' Install a ConstantPositionMobilityModel. """
''' Install a ConstantPositionMobilityModel.
"""
palloc = ns.mobility.ListPositionAllocator() palloc = ns.mobility.ListPositionAllocator()
for i in xrange(self.nodes.GetN()): for i in xrange(self.nodes.GetN()):
(x, y, z) = ((100.0 * i) + 50, 200.0, 0.0) (x, y, z) = ((100.0 * i) + 50, 200.0, 0.0)
@ -381,75 +419,85 @@ class Ns3Session(Session):
self.mobhelper.SetPositionAllocator(palloc) self.mobhelper.SetPositionAllocator(palloc)
self.mobhelper.SetMobilityModel("ns3::ConstantPositionMobilityModel") self.mobhelper.SetMobilityModel("ns3::ConstantPositionMobilityModel")
self.mobhelper.Install(self.nodes) self.mobhelper.Install(self.nodes)
def setuprandomwalkmobility(self, bounds, time=10, speed=25.0): def setuprandomwalkmobility(self, bounds, time=10, speed=25.0):
''' Set up the random walk mobility model within a bounding box. """
Set up the random walk mobility model within a bounding box.
- bounds is the max (x, y, z) boundary - bounds is the max (x, y, z) boundary
- time is the number of seconds to maintain the current speed - time is the number of seconds to maintain the current speed
and direction and direction
- speed is the maximum speed, with node speed randomly chosen - speed is the maximum speed, with node speed randomly chosen
from [0, speed] from [0, speed]
''' """
(x, y, z) = map(float, bounds) x, y, z = map(float, bounds)
self.mobhelper.SetPositionAllocator("ns3::RandomBoxPositionAllocator", self.mobhelper.SetPositionAllocator(
"ns3::RandomBoxPositionAllocator",
"X", "X",
ns.core.StringValue("ns3::UniformRandomVariable[Min=0|Max=%s]" % x), ns.core.StringValue("ns3::UniformRandomVariable[Min=0|Max=%s]" % x),
"Y", "Y",
ns.core.StringValue("ns3::UniformRandomVariable[Min=0|Max=%s]" % y), ns.core.StringValue("ns3::UniformRandomVariable[Min=0|Max=%s]" % y),
"Z", "Z",
ns.core.StringValue("ns3::UniformRandomVariable[Min=0|Max=%s]" % z)) ns.core.StringValue("ns3::UniformRandomVariable[Min=0|Max=%s]" % z)
self.mobhelper.SetMobilityModel("ns3::RandomWalk2dMobilityModel", )
"Mode", ns.core.StringValue("Time"), self.mobhelper.SetMobilityModel(
"Time", ns.core.StringValue("%ss" % time), "ns3::RandomWalk2dMobilityModel",
"Speed", "Mode", ns.core.StringValue("Time"),
ns.core.StringValue("ns3::UniformRandomVariable[Min=0|Max=%s]" \ "Time", ns.core.StringValue("%ss" % time),
% speed), "Speed",
"Bounds", ns.core.StringValue("0|%s|0|%s" % (x, y))) ns.core.StringValue("ns3::UniformRandomVariable[Min=0|Max=%s]" % speed),
"Bounds", ns.core.StringValue("0|%s|0|%s" % (x, y))
)
self.mobhelper.Install(self.nodes) self.mobhelper.Install(self.nodes)
def startns3mobility(self, refresh_ms=300): def startns3mobility(self, refresh_ms=300):
''' Start a thread that updates CORE nodes based on their ns-3 """
Start a thread that updates CORE nodes based on their ns-3
positions. positions.
''' """
self.setstate(coreapi.CORE_EVENT_INSTANTIATION_STATE) self.set_state(EventTypes.INSTANTIATION_STATE.value)
self.mobilitythread = threading.Thread( self.mobilitythread = threading.Thread(
target=self.ns3mobilitythread, target=self.ns3mobilitythread,
args=(refresh_ms,)) args=(refresh_ms,))
self.mobilitythread.daemon = True self.mobilitythread.daemon = True
self.mobilitythread.start() self.mobilitythread.start()
def ns3mobilitythread(self, refresh_ms): def ns3mobilitythread(self, refresh_ms):
''' Thread target that updates CORE nodes every refresh_ms based on """
Thread target that updates CORE nodes every refresh_ms based on
their ns-3 positions. their ns-3 positions.
''' """
valid_states = (coreapi.CORE_EVENT_RUNTIME_STATE, valid_states = (
coreapi.CORE_EVENT_INSTANTIATION_STATE) EventTypes.RUNTIME_STATE.value,
while self.getstate() in valid_states: EventTypes.INSTANTIATION_STATE.value
)
while self.state in valid_states:
for i in xrange(self.nodes.GetN()): for i in xrange(self.nodes.GetN()):
node = self.nodes.Get(i) node = self.nodes.Get(i)
(x, y, z) = node.getns3position() x, y, z = node.getns3position()
if (x, y, z) == node.position.get(): if (x, y, z) == node.position.get():
continue continue
# from WayPointMobility.setnodeposition(node, x, y, z) # from WayPointMobility.setnodeposition(node, x, y, z)
node.position.set(x, y, z) node.position.set(x, y, z)
msg = node.tonodemsg(flags=0) node_data = node.data(flags=0)
self.broadcastraw(None, msg) self.broadcast_node(node_data)
self.sdt.updatenode(node.objid, flags=0, x=x, y=y, z=z) self.sdt.updatenode(node.objid, flags=0, x=x, y=y, z=z)
time.sleep(0.001 * refresh_ms) time.sleep(0.001 * refresh_ms)
def setupmobilitytracing(self, net, filename, nodes, verbose=False): def setupmobilitytracing(self, net, filename, nodes):
''' Start a tracing thread using the ASCII output from the ns3 """
Start a tracing thread using the ASCII output from the ns3
mobility helper. mobility helper.
''' """
net.mobility = WayPointMobility(session=self, objid=net.objid, net.mobility = WayPointMobility(session=self, object_id=net.objid, values=None)
verbose=verbose, values=None)
net.mobility.setendtime() net.mobility.setendtime()
net.mobility.refresh_ms = 300 net.mobility.refresh_ms = 300
net.mobility.empty_queue_stop = False net.mobility.empty_queue_stop = False
of = ns.network.OutputStreamWrapper(filename, filemode=777) of = ns.network.OutputStreamWrapper(filename, filemode=777)
self.mobhelper.EnableAsciiAll(of) self.mobhelper.EnableAsciiAll(of)
self.mobilitytracethread = threading.Thread(target=self.mobilitytrace, self.mobilitytracethread = threading.Thread(
args=(net, filename, nodes, verbose)) target=self.mobilitytrace,
args=(net, filename, nodes)
)
self.mobilitytracethread.daemon = True self.mobilitytracethread.daemon = True
self.mobilitytracethread.start() self.mobilitytracethread.start()
@ -457,47 +505,46 @@ class Ns3Session(Session):
nodemap = {} nodemap = {}
# move nodes to initial positions # move nodes to initial positions
for node in nodes: for node in nodes:
(x,y,z) = node.getns3position() x, y, z = node.getns3position()
net.mobility.setnodeposition(node, x, y, z) net.mobility.setnodeposition(node, x, y, z)
nodemap[node.GetId()] = node nodemap[node.GetId()] = node
if verbose: logger.info("mobilitytrace opening '%s'", filename)
self.info("mobilitytrace opening '%s'" % filename)
f = None
try: try:
f = open(filename) f = open(filename)
f.seek(0,2) f.seek(0, 2)
except Exception, e:
self.warn("mobilitytrace error opening '%s': %s" % (filename, e))
sleep = 0.001
kickstart = True
while True:
if self.getstate() != coreapi.CORE_EVENT_RUNTIME_STATE:
break
line = f.readline()
if not line:
time.sleep(sleep)
if sleep < 1.0:
sleep += 0.001
continue
sleep = 0.001 sleep = 0.001
items = dict(map(lambda x: x.split('='), line.split())) kickstart = True
if verbose: while True:
self.info("trace: %s %s %s" % \ if self.state != EventTypes.RUNTIME_STATE.value:
(items['node'], items['pos'], items['vel'])) break
(x, y, z) = map(float, items['pos'].split(':')) line = f.readline()
vel = map(float, items['vel'].split(':')) if not line:
node = nodemap[int(items['node'])] time.sleep(sleep)
net.mobility.addwaypoint(time=0, nodenum=node.objid, if sleep < 1.0:
x=x, y=y, z=z, speed=vel) sleep += 0.001
if kickstart: continue
kickstart = False sleep = 0.001
self.evq.add_event(0, net.mobility.start) items = dict(map(lambda x: x.split('='), line.split()))
self.evq.run() logger.info("trace: %s %s %s", items['node'], items['pos'], items['vel'])
else: x, y, z = map(float, items['pos'].split(':'))
if net.mobility.state != net.mobility.STATE_RUNNING: vel = map(float, items['vel'].split(':'))
net.mobility.state = net.mobility.STATE_RUNNING node = nodemap[int(items['node'])]
self.evq.add_event(0, net.mobility.runround) net.mobility.addwaypoint(time=0, nodenum=node.objid,
x=x, y=y, z=z, speed=vel)
f.close() if kickstart:
kickstart = False
self.event_loop.add_event(0, net.mobility.start)
self.event_loop.run()
else:
if net.mobility.state != net.mobility.STATE_RUNNING:
net.mobility.state = net.mobility.STATE_RUNNING
self.event_loop.add_event(0, net.mobility.runround)
except IOError:
logger.exception("mobilitytrace error opening '%s': %s", filename)
finally:
if f:
f.close()

View file

@ -1,60 +1,46 @@
#!/usr/bin/python """
# Copyright (c)2011-2012 the Boeing Company.
# See the LICENSE file included in this distribution.
#
# author: Jeff Ahrenholz <jeffrey.m.ahrenholz@boeing.com>
#
'''
ns3lte.py - This script demonstrates using CORE with the ns-3 LTE model. ns3lte.py - This script demonstrates using CORE with the ns-3 LTE model.
*** Note that this script is not currently functional, see notes below. *** *** Note that this script is not currently functional, see notes below. ***
- issues connecting TapBridge with LteNetDevice - issues connecting TapBridge with LteNetDevice
"""
''' import optparse
import sys
import os, sys, time, optparse, datetime, math
try:
from core import pycore
except ImportError:
# hack for Fedora autoconf that uses the following pythondir:
if "/usr/lib/python2.6/site-packages" in sys.path:
sys.path.append("/usr/local/lib/python2.6/site-packages")
if "/usr/lib64/python2.6/site-packages" in sys.path:
sys.path.append("/usr/local/lib64/python2.6/site-packages")
if "/usr/lib/python2.7/site-packages" in sys.path:
sys.path.append("/usr/local/lib/python2.7/site-packages")
if "/usr/lib64/python2.7/site-packages" in sys.path:
sys.path.append("/usr/local/lib64/python2.7/site-packages")
from core import pycore
from core.misc import ipaddr
from corens3.obj import Ns3Session, Ns3LteNet
import ns.core import ns.core
import ns.mobility import ns.mobility
from core import logger
from core.misc import ipaddress
from corens3.obj import Ns3LteNet
from corens3.obj import Ns3Session
def ltesession(opt): def ltesession(opt):
''' Run a test LTE session. """
''' Run a test LTE session.
"""
session = Ns3Session(persistent=True, duration=opt.duration) session = Ns3Session(persistent=True, duration=opt.duration)
lte = session.addobj(cls=Ns3LteNet, name="wlan1") lte = session.add_object(cls=Ns3LteNet, name="wlan1")
lte.setsubchannels(range(25), range(50, 100)) lte.setsubchannels(range(25), range(50, 100))
if opt.verbose: if opt.verbose:
ascii = ns.network.AsciiTraceHelper() ascii = ns.network.AsciiTraceHelper()
stream = ascii.CreateFileStream('/tmp/ns3lte.tr') stream = ascii.CreateFileStream('/tmp/ns3lte.tr')
lte.lte.EnableAsciiAll(stream) lte.lte.EnableAsciiAll(stream)
#ns.core.LogComponentEnable("EnbNetDevice", ns.core.LOG_LEVEL_INFO) # ns.core.LogComponentEnable("EnbNetDevice", ns.core.LOG_LEVEL_INFO)
#ns.core.LogComponentEnable("UeNetDevice", ns.core.LOG_LEVEL_INFO) # ns.core.LogComponentEnable("UeNetDevice", ns.core.LOG_LEVEL_INFO)
#lte.lte.EnableLogComponents() # lte.lte.EnableLogComponents()
prefix = ipaddr.IPv4Prefix("10.0.0.0/16") prefix = ipaddress.Ipv4Prefix("10.0.0.0/16")
mobb = None mobb = None
nodes = [] nodes = []
for i in xrange(1, opt.numnodes + 1): for i in xrange(1, opt.numnodes + 1):
node = session.addnode(name = "n%d" % i) node = session.addnode(name="n%d" % i)
mob = ns.mobility.ConstantPositionMobilityModel() mob = ns.mobility.ConstantPositionMobilityModel()
mob.SetPosition( ns.core.Vector3D(10.0 * i, 0.0, 0.0) ) mob.SetPosition(ns.core.Vector3D(10.0 * i, 0.0, 0.0))
if i == 1: if i == 1:
lte.setnodeb(node) # first node is nodeb # first node is nodeb
lte.setnodeb(node)
mobb = mob mobb = mob
node.newnetif(lte, ["%s/%s" % (prefix.addr(i), prefix.prefixlen)]) node.newnetif(lte, ["%s/%s" % (prefix.addr(i), prefix.prefixlen)])
nodes.append(node) nodes.append(node)
@ -63,48 +49,50 @@ def ltesession(opt):
lte.lte.AddMobility(ns3dev.GetPhy(), mob) lte.lte.AddMobility(ns3dev.GetPhy(), mob)
if i > 1: if i > 1:
lte.linknodeb(node, nodes[0], mob, mobb) lte.linknodeb(node, nodes[0], mob, mobb)
session.thread = session.run(vis=opt.visualize) session.thread = session.run(vis=opt.visualize)
return session return session
def main(): def main():
''' Main routine when running from command-line. """
''' Main routine when running from command-line.
"""
usagestr = "usage: %prog [-h] [options] [args]" usagestr = "usage: %prog [-h] [options] [args]"
parser = optparse.OptionParser(usage = usagestr) parser = optparse.OptionParser(usage=usagestr)
parser.set_defaults(numnodes = 4, duration = 600, verbose = False, visualize=False) parser.set_defaults(numnodes=4, duration=600, verbose=False, visualize=False)
parser.add_option("-d", "--duration", dest = "duration", type = int, parser.add_option("-d", "--duration", dest="duration", type=int,
help = "number of seconds to run the simulation") help="number of seconds to run the simulation")
parser.add_option("-n", "--numnodes", dest = "numnodes", type = int, parser.add_option("-n", "--numnodes", dest="numnodes", type=int,
help = "number of nodes") help="number of nodes")
parser.add_option("-z", "--visualize", dest = "visualize", parser.add_option("-z", "--visualize", dest="visualize",
action = "store_true", help = "enable visualizer") action="store_true", help="enable visualizer")
parser.add_option("-v", "--verbose", dest = "verbose", parser.add_option("-v", "--verbose", dest="verbose",
action = "store_true", help = "be more verbose") action="store_true", help="be more verbose")
def usage(msg = None, err = 0): def usage(msg=None, err=0):
sys.stdout.write("\n") sys.stdout.write("\n")
if msg: if msg:
sys.stdout.write(msg + "\n\n") sys.stdout.write(msg + "\n\n")
parser.print_help() parser.print_help()
sys.exit(err) sys.exit(err)
(opt, args) = parser.parse_args() opt, args = parser.parse_args()
if opt.numnodes < 2: if opt.numnodes < 2:
usage("invalid numnodes: %s" % opt.numnodes) usage("invalid numnodes: %s" % opt.numnodes)
for a in args: for a in args:
sys.stderr.write("ignoring command line argument: '%s'\n" % a) logger.warn("ignoring command line argument: '%s'", a)
return ltesession(opt) return ltesession(opt)
def cleanup(): def cleanup():
print "shutting down session" logger.info("shutting down session")
session.shutdown() session.shutdown()
print "joining simulator thread (please kill it)"
session.thread.join()
if __name__ == "__main__": if __name__ == "__main__":
session = main() session = main()

View file

@ -1,11 +1,4 @@
#!/usr/bin/python -i """
# Copyright (c)2011-2013 the Boeing Company.
# See the LICENSE file included in this distribution.
#
# author: Jeff Ahrenholz <jeffrey.m.ahrenholz@boeing.com>
#
'''
ns3wifi.py - This script demonstrates using CORE with the ns-3 Wifi model. ns3wifi.py - This script demonstrates using CORE with the ns-3 Wifi model.
How to run this: How to run this:
@ -20,38 +13,32 @@ To run with the CORE GUI:
pushd ~/ns-allinone-3.16/ns-3.16 pushd ~/ns-allinone-3.16/ns-3.16
sudo ./waf shell sudo ./waf shell
core-daemon core-daemon
# in another terminal # in another terminal
core-daemon -e ./ns3wifi.py core-daemon -e ./ns3wifi.py
# in a third terminal # in a third terminal
core core
# now select the running session # now select the running session
''' """
import os, sys, time, optparse, datetime, math import optparse
try: import sys
from core import pycore
except ImportError:
# hack for Fedora autoconf that uses the following pythondir:
if "/usr/lib/python2.6/site-packages" in sys.path:
sys.path.append("/usr/local/lib/python2.6/site-packages")
if "/usr/lib64/python2.6/site-packages" in sys.path:
sys.path.append("/usr/local/lib64/python2.6/site-packages")
if "/usr/lib/python2.7/site-packages" in sys.path:
sys.path.append("/usr/local/lib/python2.7/site-packages")
if "/usr/lib64/python2.7/site-packages" in sys.path:
sys.path.append("/usr/local/lib64/python2.7/site-packages")
from core import pycore
import ns.core import ns.core
from core.misc import ipaddr
from corens3.obj import Ns3Session, Ns3WifiNet from core import logger
from core.misc import ipaddress
from corens3.obj import Ns3Session
from corens3.obj import Ns3WifiNet
def add_to_server(session): def add_to_server(session):
''' Add this session to the server's list if this script is executed from """
Add this session to the server's list if this script is executed from
the core-daemon server. the core-daemon server.
''' """
global server global server
try: try:
server.addsession(session) server.addsession(session)
@ -59,64 +46,68 @@ def add_to_server(session):
except NameError: except NameError:
return False return False
def wifisession(opt): def wifisession(opt):
''' Run a test wifi session. """
''' Run a test wifi session.
"""
session = Ns3Session(persistent=True, duration=opt.duration) session = Ns3Session(persistent=True, duration=opt.duration)
session.name = "ns3wifi" session.name = "ns3wifi"
session.filename = session.name + ".py" session.filename = session.name + ".py"
session.node_count = str(opt.numnodes + 1) session.node_count = str(opt.numnodes + 1)
add_to_server(session) add_to_server(session)
wifi = session.addobj(cls=Ns3WifiNet, name="wlan1") wifi = session.add_object(cls=Ns3WifiNet, name="wlan1")
wifi.setposition(30, 30, 0) wifi.setposition(30, 30, 0)
wifi.phy.Set("RxGain", ns.core.DoubleValue(18.0)) wifi.phy.Set("RxGain", ns.core.DoubleValue(18.0))
prefix = ipaddr.IPv4Prefix("10.0.0.0/16") prefix = ipaddress.Ipv4Prefix("10.0.0.0/16")
nodes = [] nodes = []
for i in xrange(1, opt.numnodes + 1): for i in xrange(1, opt.numnodes + 1):
node = session.addnode(name = "n%d" % i) node = session.addnode(name="n%d" % i)
node.newnetif(wifi, ["%s/%s" % (prefix.addr(i), prefix.prefixlen)]) node.newnetif(wifi, ["%s/%s" % (prefix.addr(i), prefix.prefixlen)])
nodes.append(node) nodes.append(node)
session.setupconstantmobility() session.setupconstantmobility()
wifi.usecorepositions() wifi.usecorepositions()
# PHY tracing # PHY tracing
#wifi.phy.EnableAsciiAll("ns3wifi") # wifi.phy.EnableAsciiAll("ns3wifi")
session.thread = session.run(vis=False) session.thread = session.run(vis=False)
return session return session
def main(): def main():
''' Main routine when running from command-line. """
''' Main routine when running from command-line.
"""
usagestr = "usage: %prog [-h] [options] [args]" usagestr = "usage: %prog [-h] [options] [args]"
parser = optparse.OptionParser(usage = usagestr) parser = optparse.OptionParser(usage=usagestr)
parser.set_defaults(numnodes = 10, duration = 600, verbose = False) parser.set_defaults(numnodes=10, duration=600, verbose=False)
parser.add_option("-d", "--duration", dest = "duration", type = int, parser.add_option("-d", "--duration", dest="duration", type=int,
help = "number of seconds to run the simulation") help="number of seconds to run the simulation")
parser.add_option("-n", "--numnodes", dest = "numnodes", type = int, parser.add_option("-n", "--numnodes", dest="numnodes", type=int,
help = "number of nodes") help="number of nodes")
parser.add_option("-v", "--verbose", dest = "verbose", parser.add_option("-v", "--verbose", dest="verbose",
action = "store_true", help = "be more verbose") action="store_true", help="be more verbose")
def usage(msg = None, err = 0): def usage(msg=None, err=0):
sys.stdout.write("\n") sys.stdout.write("\n")
if msg: if msg:
sys.stdout.write(msg + "\n\n") sys.stdout.write(msg + "\n\n")
parser.print_help() parser.print_help()
sys.exit(err) sys.exit(err)
(opt, args) = parser.parse_args() opt, args = parser.parse_args()
if opt.numnodes < 2: if opt.numnodes < 2:
usage("invalid numnodes: %s" % opt.numnodes) usage("invalid numnodes: %s" % opt.numnodes)
for a in args: for a in args:
sys.stderr.write("ignoring command line argument: '%s'\n" % a) logger.warn("ignoring command line argument: '%s'", a)
return wifisession(opt) return wifisession(opt)
if __name__ == "__main__" or __name__ == "__builtin__": if __name__ == "__main__" or __name__ == "__builtin__":
session = main() session = main()
print "\nsession =", session logger.info("\nsession =%s", session)

View file

@ -1,12 +1,5 @@
#!/usr/bin/python -i """
ns3wifirandomwalk.py - This script demonstrates using CORE with the ns-3 Wifi
# Copyright (c)2011-2013 the Boeing Company.
# See the LICENSE file included in this distribution.
#
# author: Jeff Ahrenholz <jeffrey.m.ahrenholz@boeing.com>
#
'''
ns3wifirandomwalk.py - This script demonstrates using CORE with the ns-3 Wifi
model and random walk mobility. model and random walk mobility.
Patterned after the ns-3 example 'main-random-walk.cc'. Patterned after the ns-3 example 'main-random-walk.cc'.
@ -16,72 +9,63 @@ How to run this:
sudo ./waf shell sudo ./waf shell
popd popd
python -i ns3wifirandomwalk.py python -i ns3wifirandomwalk.py
"""
''' import optparse
import sys
import os, sys, time, optparse, datetime, math, threading
try:
from core import pycore
except ImportError:
# hack for Fedora autoconf that uses the following pythondir:
if "/usr/lib/python2.6/site-packages" in sys.path:
sys.path.append("/usr/local/lib/python2.6/site-packages")
if "/usr/lib64/python2.6/site-packages" in sys.path:
sys.path.append("/usr/local/lib64/python2.6/site-packages")
if "/usr/lib/python2.7/site-packages" in sys.path:
sys.path.append("/usr/local/lib/python2.7/site-packages")
if "/usr/lib64/python2.7/site-packages" in sys.path:
sys.path.append("/usr/local/lib64/python2.7/site-packages")
from core import pycore
import ns.core import ns.core
import ns.network import ns.network
from core.api import coreapi
from core.misc import ipaddr from core import logger
from corens3.obj import Ns3Session, Ns3WifiNet from core.misc import ipaddress
from corens3.obj import Ns3Session
from corens3.obj import Ns3WifiNet
def add_to_server(session): def add_to_server(session):
''' Add this session to the server's list if this script is executed from """
Add this session to the server's list if this script is executed from
the core-daemon server. the core-daemon server.
''' """
global server global server
try: try:
server.addsession(session) server.addsession(session)
return True return True
except NameError: except NameError:
return False return False
def wifisession(opt): def wifisession(opt):
''' Run a random walk wifi session. """
''' Run a random walk wifi session.
"""
session = Ns3Session(persistent=True, duration=opt.duration) session = Ns3Session(persistent=True, duration=opt.duration)
session.name = "ns3wifirandomwalk" session.name = "ns3wifirandomwalk"
session.filename = session.name + ".py" session.filename = session.name + ".py"
session.node_count = str(opt.numnodes + 1) session.node_count = str(opt.numnodes + 1)
add_to_server(session) add_to_server(session)
wifi = session.addobj(cls=Ns3WifiNet, name="wlan1", rate="OfdmRate12Mbps") wifi = session.add_object(cls=Ns3WifiNet, name="wlan1", rate="OfdmRate12Mbps")
wifi.setposition(30, 30, 0) wifi.setposition(30, 30, 0)
# for improved connectivity # for improved connectivity
wifi.phy.Set("RxGain", ns.core.DoubleValue(18.0)) wifi.phy.Set("RxGain", ns.core.DoubleValue(18.0))
prefix = ipaddr.IPv4Prefix("10.0.0.0/16") prefix = ipaddress.Ipv4Prefix("10.0.0.0/16")
services_str = "zebra|OSPFv3MDR|IPForward" services_str = "zebra|OSPFv3MDR|IPForward"
nodes = [] nodes = []
for i in xrange(1, opt.numnodes + 1): for i in xrange(1, opt.numnodes + 1):
node = session.addnode(name = "n%d" % i) node = session.addnode(name="n%d" % i)
node.newnetif(wifi, ["%s/%s" % (prefix.addr(i), prefix.prefixlen)]) node.newnetif(wifi, ["%s/%s" % (prefix.addr(i), prefix.prefixlen)])
nodes.append(node) nodes.append(node)
session.services.addservicestonode(node, "router", services_str, session.services.addservicestonode(node, "router", services_str)
opt.verbose)
session.services.bootnodeservices(node) session.services.bootnodeservices(node)
session.setuprandomwalkmobility(bounds=(1000.0, 750.0, 0)) session.setuprandomwalkmobility(bounds=(1000.0, 750.0, 0))
# PHY tracing # PHY tracing
#wifi.phy.EnableAsciiAll("ns3wifirandomwalk") # wifi.phy.EnableAsciiAll("ns3wifirandomwalk")
# mobility tracing # mobility tracing
#session.setupmobilitytracing(wifi, "ns3wifirandomwalk.mob.tr", # session.setupmobilitytracing(wifi, "ns3wifirandomwalk.mob.tr",
# nodes, verbose=True) # nodes, verbose=True)
session.startns3mobility(refresh_ms=150) session.startns3mobility(refresh_ms=150)
@ -89,43 +73,44 @@ def wifisession(opt):
# session.instantiate() ? # session.instantiate() ?
session.thread = session.run(vis=opt.viz) session.thread = session.run(vis=opt.viz)
return session return session
def main(): def main():
''' Main routine when running from command-line. """
''' Main routine when running from command-line.
"""
usagestr = "usage: %prog [-h] [options] [args]" usagestr = "usage: %prog [-h] [options] [args]"
parser = optparse.OptionParser(usage = usagestr) parser = optparse.OptionParser(usage=usagestr)
parser.set_defaults(numnodes = 5, duration = 600, verbose = False, viz = False) parser.set_defaults(numnodes=5, duration=600, verbose=False, viz=False)
opt = { 'numnodes' : 5, 'duration': 600, 'verbose' :False, 'viz': False } opt = {'numnodes': 5, 'duration': 600, 'verbose': False, 'viz': False}
parser.add_option("-d", "--duration", dest="duration", type=int,
help="number of seconds to run the simulation")
parser.add_option("-n", "--numnodes", dest="numnodes", type=int,
help="number of nodes")
parser.add_option("-v", "--verbose", dest="verbose",
action="store_true", help="be more verbose")
parser.add_option("-V", "--visualize", dest="viz",
action="store_true", help="enable PyViz ns-3 visualizer")
parser.add_option("-d", "--duration", dest = "duration", type = int, def usage(msg=None, err=0):
help = "number of seconds to run the simulation")
parser.add_option("-n", "--numnodes", dest = "numnodes", type = int,
help = "number of nodes")
parser.add_option("-v", "--verbose", dest = "verbose",
action = "store_true", help = "be more verbose")
parser.add_option("-V", "--visualize", dest = "viz",
action = "store_true", help = "enable PyViz ns-3 visualizer")
def usage(msg = None, err = 0):
sys.stdout.write("\n") sys.stdout.write("\n")
if msg: if msg:
sys.stdout.write(msg + "\n\n") sys.stdout.write(msg + "\n\n")
parser.print_help() parser.print_help()
sys.exit(err) sys.exit(err)
(opt, args) = parser.parse_args() opt, args = parser.parse_args()
if opt.numnodes < 2: if opt.numnodes < 2:
usage("invalid numnodes: %s" % opt.numnodes) usage("invalid numnodes: %s" % opt.numnodes)
for a in args: for a in args:
sys.stderr.write("ignoring command line argument: '%s'\n" % a) logger.warn("ignoring command line argument: '%s'", a)
return wifisession(opt) return wifisession(opt)
if __name__ == "__main__" or __name__ == "__builtin__": if __name__ == "__main__" or __name__ == "__builtin__":
session = main() session = main()
print "\nsession =", session logger.info("\nsession =%s", session)

View file

@ -1,11 +1,4 @@
#!/usr/bin/python -i """
# Copyright (c)2011-2012 the Boeing Company.
# See the LICENSE file included in this distribution.
#
# author: Jeff Ahrenholz <jeffrey.m.ahrenholz@boeing.com>
#
'''
ns3wimax.py - This script demonstrates using CORE with the ns-3 Wimax model. ns3wimax.py - This script demonstrates using CORE with the ns-3 Wimax model.
*** Note that this script is not currently functional, see notes below. *** *** Note that this script is not currently functional, see notes below. ***
Current issues: Current issues:
@ -14,41 +7,33 @@ Current issues:
- base station causes segfault if it sends packet; due to missing service flows - base station causes segfault if it sends packet; due to missing service flows
(but AddFlow() is not available for bs devices) (but AddFlow() is not available for bs devices)
- no packets are sent between nodes - no connection? - no packets are sent between nodes - no connection?
''' """
import optparse
import sys
from core import logger
from core.misc import ipaddress
from corens3.obj import Ns3Session
from corens3.obj import Ns3WimaxNet
import os, sys, time, optparse, datetime, math
try:
from core import pycore
except ImportError:
# hack for Fedora autoconf that uses the following pythondir:
if "/usr/lib/python2.6/site-packages" in sys.path:
sys.path.append("/usr/local/lib/python2.6/site-packages")
if "/usr/lib64/python2.6/site-packages" in sys.path:
sys.path.append("/usr/local/lib64/python2.6/site-packages")
if "/usr/lib/python2.7/site-packages" in sys.path:
sys.path.append("/usr/local/lib/python2.7/site-packages")
if "/usr/lib64/python2.7/site-packages" in sys.path:
sys.path.append("/usr/local/lib64/python2.7/site-packages")
from core import pycore
from core.misc import ipaddr
from corens3.obj import Ns3Session, Ns3WimaxNet
def wimaxsession(opt): def wimaxsession(opt):
''' Run a test wimax session. """
''' Run a test wimax session.
"""
session = Ns3Session(persistent=True, duration=opt.duration) session = Ns3Session(persistent=True, duration=opt.duration)
wimax = session.addobj(cls=Ns3WimaxNet, name="wlan1") wimax = session.add_object(cls=Ns3WimaxNet, name="wlan1")
#wimax.wimax.EnableLogComponents() # wimax.wimax.EnableLogComponents()
prefix = ipaddr.IPv4Prefix("10.0.0.0/16") prefix = ipaddress.Ipv4Prefix("10.0.0.0/16")
# create one classifier for ICMP (protocol 1) traffic # create one classifier for ICMP (protocol 1) traffic
# src port low/high, dst port low/high, protocol, priority # src port low/high, dst port low/high, protocol, priority
#classifier = (0, 65000, 0, 65000, 1, 1) # classifier = (0, 65000, 0, 65000, 1, 1)
classifier = (0, 65000, 0, 65000, 17, 1) classifier = (0, 65000, 0, 65000, 17, 1)
nodes = [] nodes = []
for i in xrange(1, opt.numnodes + 1): for i in xrange(1, opt.numnodes + 1):
node = session.addnode(name = "n%d" % i) node = session.addnode(name="n%d" % i)
if i == 1: if i == 1:
wimax.setbasestation(node) wimax.setbasestation(node)
node.newnetif(wimax, ["%s/%s" % (prefix.addr(i), prefix.prefixlen)]) node.newnetif(wimax, ["%s/%s" % (prefix.addr(i), prefix.prefixlen)])
@ -58,35 +43,37 @@ def wimaxsession(opt):
session.setupconstantmobility() session.setupconstantmobility()
session.thread = session.run(vis=False) session.thread = session.run(vis=False)
return session return session
def main(): def main():
''' Main routine when running from command-line. """
''' Main routine when running from command-line.
"""
usagestr = "usage: %prog [-h] [options] [args]" usagestr = "usage: %prog [-h] [options] [args]"
parser = optparse.OptionParser(usage = usagestr) parser = optparse.OptionParser(usage=usagestr)
parser.set_defaults(numnodes = 3, duration = 600, verbose = False) parser.set_defaults(numnodes=3, duration=600, verbose=False)
parser.add_option("-d", "--duration", dest = "duration", type = int, parser.add_option("-d", "--duration", dest="duration", type=int,
help = "number of seconds to run the simulation") help="number of seconds to run the simulation")
parser.add_option("-n", "--numnodes", dest = "numnodes", type = int, parser.add_option("-n", "--numnodes", dest="numnodes", type=int,
help = "number of nodes") help="number of nodes")
parser.add_option("-v", "--verbose", dest = "verbose", parser.add_option("-v", "--verbose", dest="verbose",
action = "store_true", help = "be more verbose") action="store_true", help="be more verbose")
def usage(msg = None, err = 0): def usage(msg=None, err=0):
sys.stdout.write("\n") sys.stdout.write("\n")
if msg: if msg:
sys.stdout.write(msg + "\n\n") sys.stdout.write(msg + "\n\n")
parser.print_help() parser.print_help()
sys.exit(err) sys.exit(err)
(opt, args) = parser.parse_args() opt, args = parser.parse_args()
if opt.numnodes < 2: if opt.numnodes < 2:
usage("invalid numnodes: %s" % opt.numnodes) usage("invalid numnodes: %s" % opt.numnodes)
for a in args: for a in args:
sys.stderr.write("ignoring command line argument: '%s'\n" % a) logger.warn("ignoring command line argument: '%s'", a)
return wimaxsession(opt) return wimaxsession(opt)

View file

@ -1,19 +1,15 @@
# Copyright (c)2012 the Boeing Company. from setuptools import setup
# See the LICENSE file included in this directory.
import os, glob setup(
from distutils.core import setup name="corens3-python",
from corens3.constants import COREDPY_VERSION version="5.0.0",
packages=[
setup(name = "corens3-python",
version = COREDPY_VERSION,
packages = [
"corens3", "corens3",
], ],
description = "Python ns-3 components of CORE", description="Python ns-3 components of CORE",
url = "http://www.nrl.navy.mil/itd/ncs/products/core", url="http://www.nrl.navy.mil/itd/ncs/products/core",
author = "Boeing Research & Technology", author="Boeing Research & Technology",
author_email = "core-dev@pf.itd.nrl.navy.mil", author_email="core-dev@pf.itd.nrl.navy.mil",
license = "GPLv2", license="GPLv2",
long_description="Python scripts and modules for building virtual " \ long_description="Python scripts and modules for building virtual simulated networks."
"simulated networks.") )