initial pass on converting corens3 to use latest code and small cleanup
This commit is contained in:
parent
fc7fb0f76c
commit
f282f4ea15
7 changed files with 457 additions and 476 deletions
|
@ -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.
|
||||
|
||||
See http://www.nrl.navy.mil/itd/ncs/products/core and
|
||||
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__ = []
|
||||
|
||||
|
|
|
@ -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.
|
||||
'''
|
||||
"""
|
||||
|
||||
import sys, os, threading, time
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
|
||||
from core.netns.nodes import CoreNode
|
||||
from core.coreobj import PyCoreNet
|
||||
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.core
|
||||
import ns.internet
|
||||
import ns.lte
|
||||
import ns.mobility
|
||||
import ns.network
|
||||
import ns.internet
|
||||
import ns.tap_bridge
|
||||
import ns.wifi
|
||||
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):
|
||||
''' 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
|
||||
device will be used.
|
||||
'''
|
||||
"""
|
||||
|
||||
def __init__(self, *args, **kwds):
|
||||
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:
|
||||
kwds['objid'] = objid
|
||||
CoreNode.__init__(self, *args, **kwds)
|
||||
|
||||
def newnetif(self, net = None, addrlist = [], hwaddr = None,
|
||||
ifindex = None, ifname = None):
|
||||
''' Add a network interface. If we are attaching to a CoreNs3Net, this
|
||||
def newnetif(self, net=None, addrlist=None, hwaddr=None, ifindex=None, ifname=None):
|
||||
"""
|
||||
Add a network interface. If we are attaching to a CoreNs3Net, this
|
||||
will be a TunTap. Otherwise dispatch to CoreNode.newnetif().
|
||||
'''
|
||||
"""
|
||||
if not addrlist:
|
||||
addrlist = []
|
||||
|
||||
if not isinstance(net, CoreNs3Net):
|
||||
return CoreNode.newnetif(self, net, addrlist, hwaddr, ifindex,
|
||||
ifname)
|
||||
ifindex = self.newtuntap(ifindex = ifindex, ifname = ifname, net = net)
|
||||
return CoreNode.newnetif(self, net, addrlist, hwaddr, ifindex, ifname)
|
||||
ifindex = self.newtuntap(ifindex=ifindex, ifname=ifname, net=net)
|
||||
self.attachnet(ifindex, net)
|
||||
netif = self.netif(ifindex)
|
||||
netif.sethwaddr(hwaddr)
|
||||
for addr in maketuple(addrlist):
|
||||
netif.addaddr(addr)
|
||||
|
||||
|
||||
addrstr = netif.addrlist[0]
|
||||
(addr, mask) = addrstr.split('/')
|
||||
tap = net._tapdevs[netif]
|
||||
tap.SetAttribute("IpAddress",
|
||||
ns.network.Ipv4AddressValue(ns.network.Ipv4Address(addr)))
|
||||
tap.SetAttribute("Netmask",
|
||||
ns.network.Ipv4MaskValue(ns.network.Ipv4Mask("/" + mask)))
|
||||
tap.SetAttribute(
|
||||
"IpAddress",
|
||||
ns.network.Ipv4AddressValue(ns.network.Ipv4Address(addr))
|
||||
)
|
||||
tap.SetAttribute(
|
||||
"Netmask",
|
||||
ns.network.Ipv4MaskValue(ns.network.Ipv4Mask("/" + mask))
|
||||
)
|
||||
ns.core.Simulator.Schedule(ns.core.Time('0'), netif.install)
|
||||
return ifindex
|
||||
|
||||
|
||||
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:
|
||||
mm = self.GetObject(ns.mobility.MobilityModel.GetTypeId())
|
||||
pos = mm.GetPosition()
|
||||
return (pos.x, pos.y, pos.z)
|
||||
return pos.x, pos.y, pos.z
|
||||
except AttributeError:
|
||||
self.warn("ns-3 mobility model not found")
|
||||
return (0,0,0)
|
||||
return 0, 0, 0
|
||||
|
||||
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:
|
||||
mm = self.GetObject(ns.mobility.MobilityModel.GetTypeId())
|
||||
if z is None:
|
||||
|
@ -98,72 +106,83 @@ class CoreNs3Node(CoreNode, ns.network.Node):
|
|||
except AttributeError:
|
||||
self.warn("ns-3 mobility model not found, not setting position")
|
||||
|
||||
|
||||
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
|
||||
simulated worlds.
|
||||
'''
|
||||
apitype = coreapi.CORE_NODE_WLAN
|
||||
linktype = coreapi.CORE_LINK_WIRELESS
|
||||
type = "wlan" # icon used
|
||||
"""
|
||||
apitype = NodeTypes.WIRELESS_LAN.value
|
||||
linktype = LinkTypes.WIRELESS.value
|
||||
# icon used
|
||||
type = "wlan"
|
||||
|
||||
def __init__(self, session, objid = None, name = None, verbose = False,
|
||||
start = True, policy = None):
|
||||
def __init__(self, session, objid=None, name=None, start=True, policy=None):
|
||||
PyCoreNet.__init__(self, session, objid, name)
|
||||
self.tapbridge = ns.tap_bridge.TapBridgeHelper()
|
||||
self._ns3devs = {}
|
||||
self._tapdevs = {}
|
||||
|
||||
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.
|
||||
'''
|
||||
"""
|
||||
self._netif[netif] = netif
|
||||
self._linked[netif] = {}
|
||||
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.SetAttribute("DeviceName", ns.core.StringValue(netif.localname))
|
||||
tap.SetAttribute(
|
||||
"DeviceName",
|
||||
ns.core.StringValue(netif.localname)
|
||||
)
|
||||
self._ns3devs[netif] = ns3dev
|
||||
self._tapdevs[netif] = tap
|
||||
|
||||
|
||||
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
|
||||
self._ns3devs
|
||||
'''
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
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.
|
||||
'''
|
||||
"""
|
||||
for netif in node.netifs():
|
||||
if netif in self._ns3devs:
|
||||
return netif, self._ns3devs[netif]
|
||||
return None, None
|
||||
|
||||
def shutdown(self):
|
||||
''' Session.shutdown() will invoke this.
|
||||
'''
|
||||
"""
|
||||
Session.shutdown() will invoke this.
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
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.
|
||||
'''
|
||||
"""
|
||||
for netif in self.netifs():
|
||||
netif.poshook = self.setns3position
|
||||
|
||||
|
||||
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)
|
||||
|
||||
|
||||
class Ns3LteNet(CoreNs3Net):
|
||||
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)
|
||||
self.lte = ns.lte.LteHelper()
|
||||
# enhanced NodeB node list
|
||||
|
@ -172,23 +191,26 @@ class Ns3LteNet(CoreNs3Net):
|
|||
self.ulsubchannels = None
|
||||
|
||||
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().
|
||||
'''
|
||||
"""
|
||||
self.dlsubchannels = downlink
|
||||
self.ulsubchannels = uplink
|
||||
|
||||
|
||||
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)
|
||||
|
||||
|
||||
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.
|
||||
'''
|
||||
(tmp, nodebdev) = self.findns3dev(nodeb)
|
||||
(tmp, dev) = self.findns3dev(node)
|
||||
"""
|
||||
tmp, nodebdev = self.findns3dev(nodeb)
|
||||
tmp, dev = self.findns3dev(node)
|
||||
if nodebdev is None or dev is None:
|
||||
raise KeyError, "ns-3 device for node not found"
|
||||
self.lte.RegisterUeToTheEnb(dev, nodebdev)
|
||||
|
@ -196,10 +218,11 @@ class Ns3LteNet(CoreNs3Net):
|
|||
self.lte.AddMobility(dev.GetPhy(), mob)
|
||||
if mobb:
|
||||
self.lte.AddDownlinkChannelRealization(mobb, mob, dev.GetPhy())
|
||||
|
||||
|
||||
def getns3dev(self, node):
|
||||
''' Get the ns3 NetDevice using the LteHelper.
|
||||
'''
|
||||
"""
|
||||
Get the ns3 NetDevice using the LteHelper.
|
||||
"""
|
||||
if node in self.enbnodes:
|
||||
devtype = ns.lte.LteHelper.DEVICE_TYPE_ENODEB
|
||||
else:
|
||||
|
@ -211,40 +234,44 @@ class Ns3LteNet(CoreNs3Net):
|
|||
return devs.Get(0)
|
||||
|
||||
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.
|
||||
'''
|
||||
"""
|
||||
self._netif[netif] = netif
|
||||
self._linked[netif] = {}
|
||||
ns3dev = self.getns3dev(netif.node)
|
||||
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))
|
||||
tap = self.tapbridge.Install(netif.node, ns3dev)
|
||||
#tap.SetMode(ns.tap_bridge.TapBridge.USE_LOCAL)
|
||||
print "using TAP device %s for %s/%s" % \
|
||||
(netif.localname, netif.node.name, netif.name)
|
||||
check_call(['tunctl', '-t', netif.localname, '-n'])
|
||||
#check_call([IP_BIN, 'link', 'set', 'dev', netif.localname, \
|
||||
tap = self.tapbridge.Install(netif.node, ns3dev)
|
||||
# tap.SetMode(ns.tap_bridge.TapBridge.USE_LOCAL)
|
||||
logger.info("using TAP device %s for %s/%s", netif.localname, netif.node.name, netif.name)
|
||||
subprocess.check_call(['tunctl', '-t', netif.localname, '-n'])
|
||||
# check_call([IP_BIN, 'link', 'set', 'dev', netif.localname, \
|
||||
# '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))
|
||||
self._ns3devs[netif] = ns3dev
|
||||
self._tapdevs[netif] = tap
|
||||
|
||||
|
||||
class Ns3WifiNet(CoreNs3Net):
|
||||
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')
|
||||
CoreNs3Net.__init__(self, *args, **kwds)
|
||||
self.wifi = ns.wifi.WifiHelper().Default()
|
||||
self.wifi.SetStandard(ns.wifi.WIFI_PHY_STANDARD_80211a)
|
||||
self.wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager",
|
||||
"DataMode",
|
||||
ns.core.StringValue(rate),
|
||||
"NonUnicastMode",
|
||||
ns.core.StringValue(rate))
|
||||
self.wifi.SetRemoteStationManager(
|
||||
"ns3::ConstantRateWifiManager",
|
||||
"DataMode",
|
||||
ns.core.StringValue(rate),
|
||||
"NonUnicastMode",
|
||||
ns.core.StringValue(rate)
|
||||
)
|
||||
self.mac = ns.wifi.NqosWifiMacHelper.Default()
|
||||
self.mac.SetType("ns3::AdhocWifiMac")
|
||||
|
||||
|
@ -253,12 +280,13 @@ class Ns3WifiNet(CoreNs3Net):
|
|||
self.phy.SetChannel(channel.Create())
|
||||
|
||||
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)
|
||||
return devs.Get(0)
|
||||
|
||||
|
||||
|
||||
|
||||
class Ns3WimaxNet(CoreNs3Net):
|
||||
def __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
|
||||
# base station node list
|
||||
self.bsnodes = []
|
||||
|
||||
|
||||
def setbasestation(self, node):
|
||||
self.bsnodes.append(node)
|
||||
|
||||
|
||||
def getns3dev(self, node):
|
||||
if node in self.bsnodes:
|
||||
devtype = ns.wimax.WimaxHelper.DEVICE_TYPE_BASE_STATION
|
||||
|
@ -283,95 +311,105 @@ class Ns3WimaxNet(CoreNs3Net):
|
|||
# debug
|
||||
self.wimax.EnableAscii("wimax-device-%s" % node.name, devs)
|
||||
return devs.Get(0)
|
||||
|
||||
|
||||
@staticmethod
|
||||
def ipv4netifaddr(netif):
|
||||
for addr in netif.addrlist:
|
||||
if ':' in addr:
|
||||
continue # skip ipv6
|
||||
# skip ipv6
|
||||
continue
|
||||
ip = ns.network.Ipv4Address(addr.split('/')[0])
|
||||
mask = ns.network.Ipv4Mask('/' + addr.split('/')[1])
|
||||
return (ip, mask)
|
||||
return (None, None)
|
||||
|
||||
return ip, mask
|
||||
return None, None
|
||||
|
||||
def addflow(self, node1, node2, upclass, downclass):
|
||||
''' Add a Wimax service flow between two nodes.
|
||||
'''
|
||||
(netif1, ns3dev1) = self.findns3dev(node1)
|
||||
(netif2, ns3dev2) = self.findns3dev(node2)
|
||||
"""
|
||||
Add a Wimax service flow between two nodes.
|
||||
"""
|
||||
netif1, ns3dev1 = self.findns3dev(node1)
|
||||
netif2, ns3dev2 = self.findns3dev(node2)
|
||||
if not netif1 or not netif2:
|
||||
raise ValueError, "interface not found"
|
||||
(addr1, mask1) = self.ipv4netifaddr(netif1)
|
||||
(addr2, mask2) = self.ipv4netifaddr(netif2)
|
||||
clargs1 = (addr1, mask1, addr2, mask2) + downclass
|
||||
clargs2 = (addr2, mask2, addr1, mask1) + upclass
|
||||
addr1, mask1 = self.ipv4netifaddr(netif1)
|
||||
addr2, mask2 = self.ipv4netifaddr(netif2)
|
||||
clargs1 = (addr1, mask1, addr2, mask2) + downclass
|
||||
clargs2 = (addr2, mask2, addr1, mask1) + upclass
|
||||
clrec1 = ns.wimax.IpcsClassifierRecord(*clargs1)
|
||||
clrec2 = ns.wimax.IpcsClassifierRecord(*clargs2)
|
||||
ns3dev1.AddServiceFlow( \
|
||||
self.wimax.CreateServiceFlow(ns.wimax.ServiceFlow.SF_DIRECTION_DOWN,
|
||||
ns.wimax.ServiceFlow.SF_TYPE_RTPS, clrec1))
|
||||
ns3dev1.AddServiceFlow( \
|
||||
self.wimax.CreateServiceFlow(ns.wimax.ServiceFlow.SF_DIRECTION_UP,
|
||||
ns.wimax.ServiceFlow.SF_TYPE_RTPS, clrec2))
|
||||
ns3dev2.AddServiceFlow( \
|
||||
self.wimax.CreateServiceFlow(ns.wimax.ServiceFlow.SF_DIRECTION_DOWN,
|
||||
ns.wimax.ServiceFlow.SF_TYPE_RTPS, clrec2))
|
||||
ns3dev2.AddServiceFlow( \
|
||||
self.wimax.CreateServiceFlow(ns.wimax.ServiceFlow.SF_DIRECTION_UP,
|
||||
ns.wimax.ServiceFlow.SF_TYPE_RTPS, clrec1))
|
||||
ns3dev1.AddServiceFlow(self.wimax.CreateServiceFlow(
|
||||
ns.wimax.ServiceFlow.SF_DIRECTION_DOWN,
|
||||
ns.wimax.ServiceFlow.SF_TYPE_RTPS, clrec1)
|
||||
)
|
||||
ns3dev1.AddServiceFlow(self.wimax.CreateServiceFlow(
|
||||
ns.wimax.ServiceFlow.SF_DIRECTION_UP,
|
||||
ns.wimax.ServiceFlow.SF_TYPE_RTPS, clrec2)
|
||||
)
|
||||
ns3dev2.AddServiceFlow(self.wimax.CreateServiceFlow(
|
||||
ns.wimax.ServiceFlow.SF_DIRECTION_DOWN,
|
||||
ns.wimax.ServiceFlow.SF_TYPE_RTPS, clrec2)
|
||||
)
|
||||
ns3dev2.AddServiceFlow(self.wimax.CreateServiceFlow(
|
||||
ns.wimax.ServiceFlow.SF_DIRECTION_UP,
|
||||
ns.wimax.ServiceFlow.SF_TYPE_RTPS, clrec1)
|
||||
)
|
||||
|
||||
|
||||
class Ns3Session(Session):
|
||||
''' A Session that starts an ns-3 simulation thread.
|
||||
'''
|
||||
def __init__(self, persistent = False, duration=600):
|
||||
"""
|
||||
A Session that starts an ns-3 simulation thread.
|
||||
"""
|
||||
|
||||
def __init__(self, persistent=False, duration=600):
|
||||
self.duration = duration
|
||||
self.nodes = ns.network.NodeContainer()
|
||||
self.mobhelper = ns.mobility.MobilityHelper()
|
||||
Session.__init__(self, persistent = persistent)
|
||||
Session.__init__(self, persistent=persistent)
|
||||
|
||||
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():
|
||||
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:
|
||||
try:
|
||||
import visualizer
|
||||
except ImportError:
|
||||
print "visualizer is not available"
|
||||
logger.exception("visualizer is not available")
|
||||
ns.core.Simulator.Run()
|
||||
else:
|
||||
visualizer.start()
|
||||
else:
|
||||
ns.core.Simulator.Run()
|
||||
#self.evq.run() # event queue may have WayPointMobility events
|
||||
self.setstate(coreapi.CORE_EVENT_RUNTIME_STATE, info=True,
|
||||
sendevent=True)
|
||||
t = threading.Thread(target = runthread)
|
||||
|
||||
# self.evq.run() # event queue may have WayPointMobility events
|
||||
self.set_state(EventTypes.RUNTIME_STATE.value, send_event=True)
|
||||
t = threading.Thread(target=runthread)
|
||||
t.daemon = True
|
||||
t.start()
|
||||
return t
|
||||
|
||||
|
||||
def shutdown(self):
|
||||
# TODO: the following line tends to segfault ns-3 (and therefore
|
||||
# core-daemon)
|
||||
# TODO: the following line tends to segfault ns-3 (and therefore core-daemon)
|
||||
ns.core.Simulator.Destroy()
|
||||
Session.shutdown(self)
|
||||
|
||||
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.
|
||||
'''
|
||||
n = self.addobj(cls = CoreNs3Node, name=name)
|
||||
"""
|
||||
n = self.add_object(cls=CoreNs3Node, name=name)
|
||||
self.nodes.Add(n)
|
||||
return n
|
||||
|
||||
|
||||
def setupconstantmobility(self):
|
||||
''' Install a ConstantPositionMobilityModel.
|
||||
'''
|
||||
"""
|
||||
Install a ConstantPositionMobilityModel.
|
||||
"""
|
||||
palloc = ns.mobility.ListPositionAllocator()
|
||||
for i in xrange(self.nodes.GetN()):
|
||||
(x, y, z) = ((100.0 * i) + 50, 200.0, 0.0)
|
||||
|
@ -381,75 +419,85 @@ class Ns3Session(Session):
|
|||
self.mobhelper.SetPositionAllocator(palloc)
|
||||
self.mobhelper.SetMobilityModel("ns3::ConstantPositionMobilityModel")
|
||||
self.mobhelper.Install(self.nodes)
|
||||
|
||||
|
||||
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
|
||||
- time is the number of seconds to maintain the current speed
|
||||
and direction
|
||||
- speed is the maximum speed, with node speed randomly chosen
|
||||
from [0, speed]
|
||||
'''
|
||||
(x, y, z) = map(float, bounds)
|
||||
self.mobhelper.SetPositionAllocator("ns3::RandomBoxPositionAllocator",
|
||||
"""
|
||||
x, y, z = map(float, bounds)
|
||||
self.mobhelper.SetPositionAllocator(
|
||||
"ns3::RandomBoxPositionAllocator",
|
||||
"X",
|
||||
ns.core.StringValue("ns3::UniformRandomVariable[Min=0|Max=%s]" % x),
|
||||
"Y",
|
||||
ns.core.StringValue("ns3::UniformRandomVariable[Min=0|Max=%s]" % y),
|
||||
"Z",
|
||||
ns.core.StringValue("ns3::UniformRandomVariable[Min=0|Max=%s]" % z))
|
||||
self.mobhelper.SetMobilityModel("ns3::RandomWalk2dMobilityModel",
|
||||
"Mode", ns.core.StringValue("Time"),
|
||||
"Time", ns.core.StringValue("%ss" % time),
|
||||
"Speed",
|
||||
ns.core.StringValue("ns3::UniformRandomVariable[Min=0|Max=%s]" \
|
||||
% speed),
|
||||
"Bounds", ns.core.StringValue("0|%s|0|%s" % (x, y)))
|
||||
ns.core.StringValue("ns3::UniformRandomVariable[Min=0|Max=%s]" % z)
|
||||
)
|
||||
self.mobhelper.SetMobilityModel(
|
||||
"ns3::RandomWalk2dMobilityModel",
|
||||
"Mode", ns.core.StringValue("Time"),
|
||||
"Time", ns.core.StringValue("%ss" % time),
|
||||
"Speed",
|
||||
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)
|
||||
|
||||
|
||||
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.
|
||||
'''
|
||||
self.setstate(coreapi.CORE_EVENT_INSTANTIATION_STATE)
|
||||
"""
|
||||
self.set_state(EventTypes.INSTANTIATION_STATE.value)
|
||||
self.mobilitythread = threading.Thread(
|
||||
target=self.ns3mobilitythread,
|
||||
args=(refresh_ms,))
|
||||
target=self.ns3mobilitythread,
|
||||
args=(refresh_ms,))
|
||||
self.mobilitythread.daemon = True
|
||||
self.mobilitythread.start()
|
||||
|
||||
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.
|
||||
'''
|
||||
valid_states = (coreapi.CORE_EVENT_RUNTIME_STATE,
|
||||
coreapi.CORE_EVENT_INSTANTIATION_STATE)
|
||||
while self.getstate() in valid_states:
|
||||
"""
|
||||
valid_states = (
|
||||
EventTypes.RUNTIME_STATE.value,
|
||||
EventTypes.INSTANTIATION_STATE.value
|
||||
)
|
||||
while self.state in valid_states:
|
||||
for i in xrange(self.nodes.GetN()):
|
||||
node = self.nodes.Get(i)
|
||||
(x, y, z) = node.getns3position()
|
||||
x, y, z = node.getns3position()
|
||||
if (x, y, z) == node.position.get():
|
||||
continue
|
||||
# from WayPointMobility.setnodeposition(node, x, y, z)
|
||||
node.position.set(x, y, z)
|
||||
msg = node.tonodemsg(flags=0)
|
||||
self.broadcastraw(None, msg)
|
||||
node_data = node.data(flags=0)
|
||||
self.broadcast_node(node_data)
|
||||
self.sdt.updatenode(node.objid, flags=0, x=x, y=y, z=z)
|
||||
time.sleep(0.001 * refresh_ms)
|
||||
|
||||
def setupmobilitytracing(self, net, filename, nodes, verbose=False):
|
||||
''' Start a tracing thread using the ASCII output from the ns3
|
||||
def setupmobilitytracing(self, net, filename, nodes):
|
||||
"""
|
||||
Start a tracing thread using the ASCII output from the ns3
|
||||
mobility helper.
|
||||
'''
|
||||
net.mobility = WayPointMobility(session=self, objid=net.objid,
|
||||
verbose=verbose, values=None)
|
||||
"""
|
||||
net.mobility = WayPointMobility(session=self, object_id=net.objid, values=None)
|
||||
net.mobility.setendtime()
|
||||
net.mobility.refresh_ms = 300
|
||||
net.mobility.empty_queue_stop = False
|
||||
of = ns.network.OutputStreamWrapper(filename, filemode=777)
|
||||
self.mobhelper.EnableAsciiAll(of)
|
||||
self.mobilitytracethread = threading.Thread(target=self.mobilitytrace,
|
||||
args=(net, filename, nodes, verbose))
|
||||
self.mobilitytracethread = threading.Thread(
|
||||
target=self.mobilitytrace,
|
||||
args=(net, filename, nodes)
|
||||
)
|
||||
self.mobilitytracethread.daemon = True
|
||||
self.mobilitytracethread.start()
|
||||
|
||||
|
@ -457,47 +505,46 @@ class Ns3Session(Session):
|
|||
nodemap = {}
|
||||
# move nodes to initial positions
|
||||
for node in nodes:
|
||||
(x,y,z) = node.getns3position()
|
||||
x, y, z = node.getns3position()
|
||||
net.mobility.setnodeposition(node, x, y, z)
|
||||
nodemap[node.GetId()] = node
|
||||
|
||||
if verbose:
|
||||
self.info("mobilitytrace opening '%s'" % filename)
|
||||
logger.info("mobilitytrace opening '%s'", filename)
|
||||
|
||||
f = None
|
||||
try:
|
||||
f = open(filename)
|
||||
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
|
||||
f.seek(0, 2)
|
||||
|
||||
sleep = 0.001
|
||||
items = dict(map(lambda x: x.split('='), line.split()))
|
||||
if verbose:
|
||||
self.info("trace: %s %s %s" % \
|
||||
(items['node'], items['pos'], items['vel']))
|
||||
(x, y, z) = map(float, items['pos'].split(':'))
|
||||
vel = map(float, items['vel'].split(':'))
|
||||
node = nodemap[int(items['node'])]
|
||||
net.mobility.addwaypoint(time=0, nodenum=node.objid,
|
||||
x=x, y=y, z=z, speed=vel)
|
||||
if kickstart:
|
||||
kickstart = False
|
||||
self.evq.add_event(0, net.mobility.start)
|
||||
self.evq.run()
|
||||
else:
|
||||
if net.mobility.state != net.mobility.STATE_RUNNING:
|
||||
net.mobility.state = net.mobility.STATE_RUNNING
|
||||
self.evq.add_event(0, net.mobility.runround)
|
||||
|
||||
f.close()
|
||||
|
||||
|
||||
kickstart = True
|
||||
while True:
|
||||
if self.state != EventTypes.RUNTIME_STATE.value:
|
||||
break
|
||||
line = f.readline()
|
||||
if not line:
|
||||
time.sleep(sleep)
|
||||
if sleep < 1.0:
|
||||
sleep += 0.001
|
||||
continue
|
||||
sleep = 0.001
|
||||
items = dict(map(lambda x: x.split('='), line.split()))
|
||||
logger.info("trace: %s %s %s", items['node'], items['pos'], items['vel'])
|
||||
x, y, z = map(float, items['pos'].split(':'))
|
||||
vel = map(float, items['vel'].split(':'))
|
||||
node = nodemap[int(items['node'])]
|
||||
net.mobility.addwaypoint(time=0, nodenum=node.objid,
|
||||
x=x, y=y, z=z, speed=vel)
|
||||
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()
|
||||
|
|
|
@ -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.
|
||||
*** Note that this script is not currently functional, see notes below. ***
|
||||
- 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.mobility
|
||||
|
||||
from core import logger
|
||||
from core.misc import ipaddress
|
||||
from corens3.obj import Ns3LteNet
|
||||
from corens3.obj import Ns3Session
|
||||
|
||||
|
||||
def ltesession(opt):
|
||||
''' Run a test LTE session.
|
||||
'''
|
||||
"""
|
||||
Run a test LTE session.
|
||||
"""
|
||||
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))
|
||||
if opt.verbose:
|
||||
ascii = ns.network.AsciiTraceHelper()
|
||||
stream = ascii.CreateFileStream('/tmp/ns3lte.tr')
|
||||
lte.lte.EnableAsciiAll(stream)
|
||||
#ns.core.LogComponentEnable("EnbNetDevice", ns.core.LOG_LEVEL_INFO)
|
||||
#ns.core.LogComponentEnable("UeNetDevice", ns.core.LOG_LEVEL_INFO)
|
||||
#lte.lte.EnableLogComponents()
|
||||
# ns.core.LogComponentEnable("EnbNetDevice", ns.core.LOG_LEVEL_INFO)
|
||||
# ns.core.LogComponentEnable("UeNetDevice", ns.core.LOG_LEVEL_INFO)
|
||||
# lte.lte.EnableLogComponents()
|
||||
|
||||
prefix = ipaddr.IPv4Prefix("10.0.0.0/16")
|
||||
prefix = ipaddress.Ipv4Prefix("10.0.0.0/16")
|
||||
mobb = None
|
||||
nodes = []
|
||||
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.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:
|
||||
lte.setnodeb(node) # first node is nodeb
|
||||
# first node is nodeb
|
||||
lte.setnodeb(node)
|
||||
mobb = mob
|
||||
node.newnetif(lte, ["%s/%s" % (prefix.addr(i), prefix.prefixlen)])
|
||||
nodes.append(node)
|
||||
|
@ -63,48 +49,50 @@ def ltesession(opt):
|
|||
lte.lte.AddMobility(ns3dev.GetPhy(), mob)
|
||||
if i > 1:
|
||||
lte.linknodeb(node, nodes[0], mob, mobb)
|
||||
|
||||
|
||||
session.thread = session.run(vis=opt.visualize)
|
||||
return session
|
||||
|
||||
|
||||
|
||||
def main():
|
||||
''' Main routine when running from command-line.
|
||||
'''
|
||||
"""
|
||||
Main routine when running from command-line.
|
||||
"""
|
||||
usagestr = "usage: %prog [-h] [options] [args]"
|
||||
parser = optparse.OptionParser(usage = usagestr)
|
||||
parser.set_defaults(numnodes = 4, duration = 600, verbose = False, visualize=False)
|
||||
parser = optparse.OptionParser(usage=usagestr)
|
||||
parser.set_defaults(numnodes=4, duration=600, verbose=False, visualize=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("-z", "--visualize", dest = "visualize",
|
||||
action = "store_true", help = "enable visualizer")
|
||||
parser.add_option("-v", "--verbose", dest = "verbose",
|
||||
action = "store_true", help = "be more verbose")
|
||||
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("-z", "--visualize", dest="visualize",
|
||||
action="store_true", help="enable visualizer")
|
||||
parser.add_option("-v", "--verbose", dest="verbose",
|
||||
action="store_true", help="be more verbose")
|
||||
|
||||
def usage(msg = None, err = 0):
|
||||
def usage(msg=None, err=0):
|
||||
sys.stdout.write("\n")
|
||||
if msg:
|
||||
sys.stdout.write(msg + "\n\n")
|
||||
parser.print_help()
|
||||
sys.exit(err)
|
||||
|
||||
(opt, args) = parser.parse_args()
|
||||
opt, args = parser.parse_args()
|
||||
|
||||
if opt.numnodes < 2:
|
||||
usage("invalid numnodes: %s" % opt.numnodes)
|
||||
|
||||
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)
|
||||
|
||||
|
||||
def cleanup():
|
||||
print "shutting down session"
|
||||
logger.info("shutting down session")
|
||||
session.shutdown()
|
||||
print "joining simulator thread (please kill it)"
|
||||
session.thread.join()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
session = main()
|
||||
|
|
|
@ -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.
|
||||
|
||||
How to run this:
|
||||
|
@ -20,38 +13,32 @@ To run with the CORE GUI:
|
|||
pushd ~/ns-allinone-3.16/ns-3.16
|
||||
sudo ./waf shell
|
||||
core-daemon
|
||||
|
||||
|
||||
# in another terminal
|
||||
core-daemon -e ./ns3wifi.py
|
||||
# in a third terminal
|
||||
core
|
||||
# now select the running session
|
||||
|
||||
'''
|
||||
"""
|
||||
|
||||
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
|
||||
import optparse
|
||||
import sys
|
||||
|
||||
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):
|
||||
''' 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.
|
||||
'''
|
||||
"""
|
||||
global server
|
||||
try:
|
||||
server.addsession(session)
|
||||
|
@ -59,64 +46,68 @@ def add_to_server(session):
|
|||
except NameError:
|
||||
return False
|
||||
|
||||
|
||||
def wifisession(opt):
|
||||
''' Run a test wifi session.
|
||||
'''
|
||||
"""
|
||||
Run a test wifi session.
|
||||
"""
|
||||
session = Ns3Session(persistent=True, duration=opt.duration)
|
||||
session.name = "ns3wifi"
|
||||
session.filename = session.name + ".py"
|
||||
session.node_count = str(opt.numnodes + 1)
|
||||
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.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 = []
|
||||
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)])
|
||||
nodes.append(node)
|
||||
session.setupconstantmobility()
|
||||
wifi.usecorepositions()
|
||||
# PHY tracing
|
||||
#wifi.phy.EnableAsciiAll("ns3wifi")
|
||||
# wifi.phy.EnableAsciiAll("ns3wifi")
|
||||
session.thread = session.run(vis=False)
|
||||
return session
|
||||
|
||||
|
||||
|
||||
def main():
|
||||
''' Main routine when running from command-line.
|
||||
'''
|
||||
"""
|
||||
Main routine when running from command-line.
|
||||
"""
|
||||
usagestr = "usage: %prog [-h] [options] [args]"
|
||||
parser = optparse.OptionParser(usage = usagestr)
|
||||
parser.set_defaults(numnodes = 10, duration = 600, verbose = False)
|
||||
parser = optparse.OptionParser(usage=usagestr)
|
||||
parser.set_defaults(numnodes=10, duration=600, verbose=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("-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")
|
||||
|
||||
def usage(msg = None, err = 0):
|
||||
def usage(msg=None, err=0):
|
||||
sys.stdout.write("\n")
|
||||
if msg:
|
||||
sys.stdout.write(msg + "\n\n")
|
||||
parser.print_help()
|
||||
sys.exit(err)
|
||||
|
||||
(opt, args) = parser.parse_args()
|
||||
opt, args = parser.parse_args()
|
||||
|
||||
if opt.numnodes < 2:
|
||||
usage("invalid numnodes: %s" % opt.numnodes)
|
||||
|
||||
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)
|
||||
|
||||
|
||||
if __name__ == "__main__" or __name__ == "__builtin__":
|
||||
session = main()
|
||||
print "\nsession =", session
|
||||
logger.info("\nsession =%s", session)
|
||||
|
|
|
@ -1,12 +1,5 @@
|
|||
#!/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>
|
||||
#
|
||||
'''
|
||||
ns3wifirandomwalk.py - This script demonstrates using CORE with the ns-3 Wifi
|
||||
"""
|
||||
ns3wifirandomwalk.py - This script demonstrates using CORE with the ns-3 Wifi
|
||||
model and random walk mobility.
|
||||
Patterned after the ns-3 example 'main-random-walk.cc'.
|
||||
|
||||
|
@ -16,72 +9,63 @@ How to run this:
|
|||
sudo ./waf shell
|
||||
popd
|
||||
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.network
|
||||
from core.api import coreapi
|
||||
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):
|
||||
''' 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.
|
||||
'''
|
||||
"""
|
||||
global server
|
||||
try:
|
||||
server.addsession(session)
|
||||
return True
|
||||
except NameError:
|
||||
return False
|
||||
|
||||
|
||||
|
||||
def wifisession(opt):
|
||||
''' Run a random walk wifi session.
|
||||
'''
|
||||
"""
|
||||
Run a random walk wifi session.
|
||||
"""
|
||||
session = Ns3Session(persistent=True, duration=opt.duration)
|
||||
session.name = "ns3wifirandomwalk"
|
||||
session.filename = session.name + ".py"
|
||||
session.node_count = str(opt.numnodes + 1)
|
||||
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)
|
||||
# for improved connectivity
|
||||
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"
|
||||
nodes = []
|
||||
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)])
|
||||
nodes.append(node)
|
||||
session.services.addservicestonode(node, "router", services_str,
|
||||
opt.verbose)
|
||||
session.services.addservicestonode(node, "router", services_str)
|
||||
session.services.bootnodeservices(node)
|
||||
session.setuprandomwalkmobility(bounds=(1000.0, 750.0, 0))
|
||||
|
||||
# PHY tracing
|
||||
#wifi.phy.EnableAsciiAll("ns3wifirandomwalk")
|
||||
# wifi.phy.EnableAsciiAll("ns3wifirandomwalk")
|
||||
|
||||
# mobility tracing
|
||||
#session.setupmobilitytracing(wifi, "ns3wifirandomwalk.mob.tr",
|
||||
# session.setupmobilitytracing(wifi, "ns3wifirandomwalk.mob.tr",
|
||||
# nodes, verbose=True)
|
||||
session.startns3mobility(refresh_ms=150)
|
||||
|
||||
|
@ -89,43 +73,44 @@ def wifisession(opt):
|
|||
# session.instantiate() ?
|
||||
session.thread = session.run(vis=opt.viz)
|
||||
return session
|
||||
|
||||
|
||||
|
||||
def main():
|
||||
''' Main routine when running from command-line.
|
||||
'''
|
||||
"""
|
||||
Main routine when running from command-line.
|
||||
"""
|
||||
usagestr = "usage: %prog [-h] [options] [args]"
|
||||
parser = optparse.OptionParser(usage = usagestr)
|
||||
parser.set_defaults(numnodes = 5, duration = 600, verbose = False, viz = False)
|
||||
opt = { 'numnodes' : 5, 'duration': 600, 'verbose' :False, 'viz': False }
|
||||
parser = optparse.OptionParser(usage=usagestr)
|
||||
parser.set_defaults(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,
|
||||
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):
|
||||
def usage(msg=None, err=0):
|
||||
sys.stdout.write("\n")
|
||||
if msg:
|
||||
sys.stdout.write(msg + "\n\n")
|
||||
parser.print_help()
|
||||
sys.exit(err)
|
||||
|
||||
(opt, args) = parser.parse_args()
|
||||
opt, args = parser.parse_args()
|
||||
|
||||
if opt.numnodes < 2:
|
||||
usage("invalid numnodes: %s" % opt.numnodes)
|
||||
|
||||
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)
|
||||
|
||||
|
||||
if __name__ == "__main__" or __name__ == "__builtin__":
|
||||
session = main()
|
||||
print "\nsession =", session
|
||||
logger.info("\nsession =%s", session)
|
||||
|
|
|
@ -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.
|
||||
*** Note that this script is not currently functional, see notes below. ***
|
||||
Current issues:
|
||||
|
@ -14,41 +7,33 @@ Current issues:
|
|||
- base station causes segfault if it sends packet; due to missing service flows
|
||||
(but AddFlow() is not available for bs devices)
|
||||
- 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):
|
||||
''' Run a test wimax session.
|
||||
'''
|
||||
"""
|
||||
Run a test wimax session.
|
||||
"""
|
||||
session = Ns3Session(persistent=True, duration=opt.duration)
|
||||
wimax = session.addobj(cls=Ns3WimaxNet, name="wlan1")
|
||||
#wimax.wimax.EnableLogComponents()
|
||||
wimax = session.add_object(cls=Ns3WimaxNet, name="wlan1")
|
||||
# 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
|
||||
# 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)
|
||||
nodes = []
|
||||
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:
|
||||
wimax.setbasestation(node)
|
||||
node.newnetif(wimax, ["%s/%s" % (prefix.addr(i), prefix.prefixlen)])
|
||||
|
@ -58,35 +43,37 @@ def wimaxsession(opt):
|
|||
session.setupconstantmobility()
|
||||
session.thread = session.run(vis=False)
|
||||
return session
|
||||
|
||||
|
||||
|
||||
def main():
|
||||
''' Main routine when running from command-line.
|
||||
'''
|
||||
"""
|
||||
Main routine when running from command-line.
|
||||
"""
|
||||
usagestr = "usage: %prog [-h] [options] [args]"
|
||||
parser = optparse.OptionParser(usage = usagestr)
|
||||
parser.set_defaults(numnodes = 3, duration = 600, verbose = False)
|
||||
parser = optparse.OptionParser(usage=usagestr)
|
||||
parser.set_defaults(numnodes=3, duration=600, verbose=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("-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")
|
||||
|
||||
def usage(msg = None, err = 0):
|
||||
def usage(msg=None, err=0):
|
||||
sys.stdout.write("\n")
|
||||
if msg:
|
||||
sys.stdout.write(msg + "\n\n")
|
||||
parser.print_help()
|
||||
sys.exit(err)
|
||||
|
||||
(opt, args) = parser.parse_args()
|
||||
opt, args = parser.parse_args()
|
||||
|
||||
if opt.numnodes < 2:
|
||||
usage("invalid numnodes: %s" % opt.numnodes)
|
||||
|
||||
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)
|
||||
|
||||
|
|
|
@ -1,19 +1,15 @@
|
|||
# Copyright (c)2012 the Boeing Company.
|
||||
# See the LICENSE file included in this directory.
|
||||
from setuptools import setup
|
||||
|
||||
import os, glob
|
||||
from distutils.core import setup
|
||||
from corens3.constants import COREDPY_VERSION
|
||||
|
||||
setup(name = "corens3-python",
|
||||
version = COREDPY_VERSION,
|
||||
packages = [
|
||||
setup(
|
||||
name="corens3-python",
|
||||
version="5.0.0",
|
||||
packages=[
|
||||
"corens3",
|
||||
],
|
||||
description = "Python ns-3 components of CORE",
|
||||
url = "http://www.nrl.navy.mil/itd/ncs/products/core",
|
||||
author = "Boeing Research & Technology",
|
||||
author_email = "core-dev@pf.itd.nrl.navy.mil",
|
||||
license = "GPLv2",
|
||||
long_description="Python scripts and modules for building virtual " \
|
||||
"simulated networks.")
|
||||
],
|
||||
description="Python ns-3 components of CORE",
|
||||
url="http://www.nrl.navy.mil/itd/ncs/products/core",
|
||||
author="Boeing Research & Technology",
|
||||
author_email="core-dev@pf.itd.nrl.navy.mil",
|
||||
license="GPLv2",
|
||||
long_description="Python scripts and modules for building virtual simulated networks."
|
||||
)
|
||||
|
|
Loading…
Reference in a new issue