Documentos de Académico
Documentos de Profesional
Documentos de Cultura
Mathieu Lacage
mathieu.lacage@sophia.inria.fr
INRIA
Tuesday 7th:
14h00-16h00: Overview of ns-3 features
16h00-16h30: Pause
16h30-17h30: An end-to-end tour of a simulation
17h30-18h00: Experimentation
Wednesday 8th:
09h00-10h00: Setup
...
The basics
APIs
We use Doxygen:
last stable release:
http://www.nsnam.org/doxygen-release/index.html
development tree: http://www.nsnam.org/doxygen/index.html
Getting started I
Windows
cygwin
python
mercurial
Getting started II
Download and build development version:
hg clone http://code.nsnam.org/ns-3-allinone
cd ns-3-allinone
./download.py
./build.py
cd ns-3-dev
./waf distclean
./waf configure
./waf
Useful options:
./waf -d optimized configure
-j# where # is number of cores
./waf --help shows you other options
Running programs:
build/VARIANT:
Programs compile against build/VARIANT/ns3/*.h
Programs link against shared library build/VARIANT/libns3.so
Programs are built as build/VARIANT/PATH/program-name
Using ./waf --shell
./waf --shell
./build/debug/samples/main-simulator
Simulation basics
Scheduling events
In samples/main-simulation.cc:
The Testcase
Udp send
Node0 Node1 Node4
One csma link
csma
10.1.1.1
csma
10.1.1.2
adhoc
10.1.2.1
adhoc
10.1.2.4 One wifi infrastructure network
Two ip subnetworks
adhoc adhoc One udp traffic generator
10.1.2.2 10.1.2.3
Topology
Models Configuration Execution
Definition Examples
Output
Modify scenario, or perform independent replication Analysis
Node
NetDevice
High-level wrappers
Address types
No smart pointers
Queues
Aimed at scripting
Socket
Ipv4 helper
core
Packets
Packet tags
Packet headers
Smart pointers Callbacks Pcap file writing
Dynamic type system Tracing
Attributes Logging
Random Variables
Topology construction
NodeContainer csmaNodes;
csmaNodes.Create (2);
...
NetDeviceContainer csmaDevices;
CsmaHelper csma;
csma.SetChannelAttribute ("DataRate",
StringValue ("5Mbps"));
csma.SetChannelAttribute ("Delay",
StringValue ("2ms"));
csmaDevices = csma.Install (csmaNodes);
Application Application
Application Application
Socket-like
API
Protocol Protocol
Stack Stack
NetDevice NetDevice
NetDevice NetDevice
Node Node
Channel
Channel
Important remarks
Example containers:
NodeContainer
NetDeviceContainer
Ipv4AddressContainer
Example helper classes:
InternetStackHelper
WifiHelper
MobilityHelper
OlsrHelper
etc. Each model provides a helper class
Wifi implementation
Send(packet, dest, proto) ForwardUp
WifiNetDevice
Enqueue(packet, to)
ForwardUp
Receive
StartTransmission
Listener
MacLow "takes care of RTS/CTS/DATA/ACK transactions"
ReceiveOk/ReceiveError
SendPacket
Listener
WifiPhy
Send StartReceivePacket
WifiChannel
Mobility models I
mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel");
mobility.Install (wifiNodes);
Mobility models II
The MobilityModel base class:
SetPosition, GetPosition: 3d x,y,z vector
GetVelocity: 3d x,y,z vector
ConstantPositionMobilityModel: node is at a fixed location; does
not move on its own
ConstantVelocityMobilityModel: node moves with a fixed
velocity vector
ConstantAccelerationMobilityModel: node moves with a fixed
acceleration vector
RandomWaypointMobilityModel:
Node pauses for a certain random time
Node selects a random waypoint and speed
Node starts walking towards the waypoint
When waypoint is reached, goto first state
GlobalRouteManager::PopulateRoutingTables ();
OnOffApplication Application
::Send
UdpSocketImpl UdpSocket
::Send
UdpL4Protocol UdpSocketFactory
::Send
Ipv4L3Protocol Ipv4
::Send
ArpIpv4Interface
::Send
CsmaNetDevice NetDevice
NSC Architecture
Architecture
liblinux2.6.14.so
libfreebsd5.3.so
NSC
NSC TCP
TCP Socket API
NSC
modelTCP
model Network
Network
model
send packet Stack
StackTCP
Cradle
Cradle(shared lib)
(sharedVirtualised
lib)
Virtualised Virtualised
Resources
Resources
IP Resources
Simulation API
Network
simulator Network Stack
(ns-2) connect,
send, Cradle (shared lib)
packet received,
timer, read
NSC implementation
Nsc accuracy
Accuracy
Have shown NSC to be very accurate able to produce
packet traces that are almost identical to traces measured
from a test network
Ipv4 Routing
Applications:
All subclass ns3::Application
Are managed by a Node
Represent a process on an actual system
Talk to network stacks through one or more sockets
ns-3 Sockets
Object attributes
Traditionally, in C++:
Config::SetAttribute ("/NodeList/5/DeviceList/0/Phy/TxGain",
StringValue ("10"));
Load and Save all values from and to a raw text or xml file:
ConfigStore config;
config.ConfigureDefaults ();
...
config.ConfigureAttributes ();
NodeListPriv Node
/NodeList/[0-n] /DeviceList/[0-n]
PointToPointNetDevice CsmaNetDevice
Tracing
Tracing requirements
Tracing overview
Source Source
Source Source
High-level tracing
Mid-level tracing
void
DevTxTrace (std::string context,
Ptr<const Packet> p, Mac48Address address)
{
std::cout << " TX to=" << address << " p: " << *p << std::endl;
}
Config::Connect ("/NodeList/*/DeviceList/*/Mac/MacTx",
MakeCallback (&DevTxTrace));
Random variables
Specify a random start time:
onoff.SetAttribute ("OnTime", StringValue ("Uniform:1.0:2.0"));
Ns-3 simulations use a fixed seed (1) and run number (1) by default:
--RngSeed, --RngRun
NS GLOBAL VALUE=RngRun=2
Default was random seeding prior to 3.4
To run independent replications of the same scenario:
Dont change the seed ever
Increment the run number for each simulation
Pause !!
The Testcase
Udp send
Node0 Node1 Node4
One csma link
csma
10.1.1.1
csma
10.1.1.2
adhoc
10.1.2.1
adhoc
10.1.2.4 One wifi infrastructure network
Two ip subnetworks
adhoc adhoc One udp traffic generator
10.1.2.2 10.1.2.3
We do:
Ptr<Node> node0 = CreateObject<Node> ();
Why not:
Or:
Node node0 = Node ();
Memory Management
It is hard in C++:
No garbage collector
Easy to forget to delete an object
Pointer cycles
Ensure coherency and uniformity
So, we use:
Reference counting: track number of pointers to an object
(Ref+Unref)
Smart pointers: Ptr<>, Create<> and, CreateObject<>
Sometimes, explicit Dispose to break cycles
Object aggregation
Node MobilityModel
A circular singly linked-list
AggregateObject is a constant-time
operation
GetObject is a O(n) operation
Aggregate contains only one object of
Node MobilityModel
each type
Ipv4
Application Transmission I
User writes:
Ptr<Application> app = ...;
app->Start (Seconds (1.0));
Application::Start:
Application Transmission II
Socket::CreateSocket:
Ptr<SocketFactory> socketFactory;
socketFactory = node->GetObject<SocketFactory> (tid);
s = socketFactory->CreateSocket ();
OnOffApplication::StartSending:
m_sendEvent = Simulator::Schedule(nextTime,
&OnOffApplication::SendPacket, this);
OnOffApplication::SendPacket:
Ptr<SocketFactory> factory =
node->GetObject<FooSocketFactory> ();
Ptr<Socket> socket = factory->CreateSocket ();
socket->...
How to implement a new protocol Foo:
Create FooSocketFactory, a subclass of SocketFactory
Aggregate FooSocketFactory to a Node during topology
construction (for UDP, done by InternetStackHelper::Install)
From FooSocketFactory::CreateSocket, create instances of type
FooSocket, a subclass of Socket
Data Zero Area Size Used start Used Size Virtual Zero Area
Used
Count Size Initial StartD irty Start Dirty Size Unused Area Dirty Area Unused Area
BufferData
Used
Data Zero Area Size Used start Used Size Virtual Zero Area
Buffer
UDP Transmission I
UdpHeader udpHeader;
...
udpHeader.SetDestinationPort (dport);
udpHeader.SetSourcePort (sport);
packet->AddHeader (udpHeader);
Ptr<Ipv4L3Protocol> ipv4 =
m_node->GetObject<Ipv4L3Protocol> ();
ipv4->Send (packet, saddr, daddr, PROT_NUMBER);
IPv4 Transmission I
Ipv4L3Protocol::Send:
Ipv4Header ipHeader;
...
ipHeader.SetSource (source);
ipHeader.SetDestination (destination);
ipHeader.SetProtocol (protocol);
ipHeader.SetPayloadSize (packet->GetSize ());
...
ipHeader.SetTtl (...);
...
Lookup (ipHeader, packet,
MakeCallback (&Ipv4L3Protocol::SendRealOut, this));
IPv4 Transmission II
packet->AddHeader (ipHeader);
Ptr<Ipv4Interface> outInterface =
GetInterface (route.GetInterface ());
outInterface->Send (packet, ipHeader.GetDestination ())
Down, in ArpIpv4Interface:
The implementation:
void
MyHeader::Serialize (Buffer::Iterator start) const
{
start.WriteHtonU16 (m_data);
}
uint32_t
MyHeader::Deserialize (Buffer::Iterator start)
{
m_data = start.ReadNtohU16 ();
return 2;
}
Arp
ArpL3Protocol::Lookup:
Try to find a matching live entry
If needed, send an ARP request on NetDevice::Send
Wait for reply
ArpL3Protocol::Receive:
If request for us, send reply
If reply, check if request pending, update cache entry, flush packets
from cache entry
CsmaNetDevice Transmission
CsmaNetDevice::Send:
Add ethernet header and trailer
Queue packet in tx queue
Perform backoff if medium is busy
When medium is idle, start transmission (delay is
bytes*8/throughput)
When transmission completes, request packet forwarding on medium
CsmaChannel::TransmitEnd:
Apply propagation delay on transmission
Distribute packet to all devices on the medium for reception
CsmaNetDevice::Receive:
Remove ethernet header and trailer
Filter unwanted packets
Apply packet error model
Call device receive callback
Mathieu Lacage (INRIA) An ns-3 tutorial Tunis09-04 94 / 1
Diving In: an End To End Tour of a Packet
IPv4 Reception
Ipv4L3Protocol::Receive:
Remove IPv4 header, verify checksum
Forward packet to matching raw IPv4 sockets
If needed, forward packet down to outgoing interfaces
If needed, forward packet up the stack to matching layer 4 protocol
with Ipv4L3Protocol::GetProtocol
Wifi Transmission
WifiNetDevice::Send is fairly simple:
LlcSnapHeader llc;
llc.SetType (protocolNumber);
packet->AddHeader (llc);
m_txLogger (packet, realTo);
m_mac->Enqueue (packet, realTo);
WifiMacHeader hdr;
hdr.SetAddr1 (to);
hdr.SetAddr2 (GetAddress ());
hdr.SetAddr3 (from);
...
m_dca->Queue (packet, hdr);
DcaTxop::Queue:
Queue outgoing packet in WifiMacQueue
Use DCF (DcfManager and DcfState to obtain a tx opportunity
When the tx opportunity happens, DcaTxop::NotifyAccessGranted is
called:
Dequeue packet
Prepare the first fragment if needed
Enable RTS if needed
Call MacLow::StartTransmission
Wait for notifications about transmission success or failure from
MacLow
Eventually, start retransmissions, send more fragments
if (m_txParams.MustSendRts ())
SendRtsForPacket ();
else
SendDataPacket ();
WifiMacHeader hdr;
packet->RemoveHeader (hdr);
if (hdr.IsRts ())
...
else if (hdr.IsCts () &&
...
else if (hdr.IsAck () &&
...
else if (hdr.GetAddr1 () == m_self)
...
else if (hdr.GetAddr1 ().IsGroup ())
...
And notifies upper layers with its receive callback
Mathieu Lacage (INRIA) An ns-3 tutorial Tunis09-04 101 / 1
Diving In: an End To End Tour of a Packet
MacRxMiddle::Receive:
if (IsDuplicate (hdr, originator))
return;
Ptr<Packet> agregate = HandleFragments (packet, hdr, originato
if (agregate == 0)
return;
m_callback (agregate, hdr);
NqstaWifiMac::Receive:
UDP Reception
UdpHeader udpHeader;
packet->RemoveHeader (udpHeader);
Ipv4EndPointDemux::EndPoints endPoints =
m_endPoints->Lookup (destination,
udpHeader.GetDestinationPort (),
source,
udpHeader.GetSourcePort (), ...);
for (endPoint = endPoints.begin ();
endPoint != endPoints.end (); endPoint++)
{
(*endPoint)->ForwardUp (...);
}
Application Reception I
UdpSocketImpl::ForwardUp
PacketSink::HandleRead:
packet = socket->RecvFrom (from)
Application Reception II
UdpSocketImpl::Recv
if (m_deliveryQueue.empty() )
{
m_errno = ERROR_AGAIN;
return 0;
}
Ptr<Packet> p = m_deliveryQueue.front ();
if (p->GetSize () <= maxSize)
{
m_deliveryQueue.pop ();
m_rxAvailable -= p->GetSize ();
}
return p;
Pause !!
Experimentation
What is experimentation ?
Physical testbeds:
Cluster of ethernet networked machines
Set of laptops with wireless cards, on a desktop
Set of wireless motes in backpacks
Planetlab, ORBIT, Onelab, Emulab, ...
Simulation:
ns-2, ns-3, nctuns, omnetpp etc.
Emulation:
Coupling of simulation with physical testbeds or real world
Simulation vs testbeds
Simulation is:
Reproducible,
Easy to configure,
Easy to instrument,
Potentially unrealistic
Testbeds are:
Potentially more realistic than simulation,
More or less reproducible (often less),
Hard to configure,
Very hard to instrument
1 A great idea,
2 Thorough simulation,
3 Thorough testbed experimentation,
4 Small-scale deployment,
5 Large-scale deployment
Simulation
Bright Idea
Modelization Implementation
Real World
Experimentation Validation
Validation
Simulation:
cost of model validation
cost of model implementation
Cost of transition from simulation to testbed experimentation
Cost of transition from testbed experimentation to deployment
Real Machine
ns-3 simulation ns-3 simulation
Real Testbed
ns-3 simulation
Binary loader
The goal is to be able to load the same binary multiple times in the same
simulation process:
Uses a special ELF loader
Implements posix socket API using ns-3 sockets
Can debug all applications with a single debugger
Practical exercise
Look at examples/tap-wifi-dumbbell.cc
Build it, become root
Run ./waf --shell
Run ./build/debug/examples/tap-wifi-dumbbell
In another terminal, ping 10.1.1.1, ping 10.1.1.3, ping
10.1.3.1
Add a route to 10.1.3.0:
route add -net 10.1.3.0 netmask 255.255.255.0 dev thetap gw 10.1.1.2
ping 10.1.3.1
100000
80000
60000
40000
20000
0
1 1.5 2 2.5 3 3.5 4 4.5
All slides stolen from others presentations and tutorials (in no particular
order):
Tom Henderson
Gustavo Carneiro
Joseph Kopena
Sam Jansen
Extras
Callback objects I
Callback objects II
Class MyClass {
public:
double MyMethod (int x, float y) {
return double (x + y) / 2;
};
};
Callback<double, int, float> cb1;
MyClass myobj;
cb1 = MakeCallback(&MyClass::MyMethod, &myobj);
double result = cb1 (2,3);
Debugging support I
Debugging support II
Logging levels:
NS LOG ERROR (...): serious error messages only
NS LOG WARN (...): warning messages
NS LOG DEBUG (...): rare ad-hoc debug messages
NS LOG INFO (...): informational messages (eg. banners)
NS LOG FUNCTION (...):function tracing
NS LOG PARAM (...): parameters to functions
NS LOG LOGIC (...): control flow tracing within functions
Logging components
Logging messages organized by components
Usually one component is one .cc source file
NS LOG COMPONENT DEFINE (OlsrAgent);
Displaying log messages. Two ways:
Programatically: LogComponentEnable("OlsrAgent",
LOG LEVEL ALL);
From the environment: NS LOG=OlsrAgent ./my-program