outline - ce.aut.ac.irce.aut.ac.ir/~bakhshis/ns-2/ns-2 introduction.pdf · • share code,...
TRANSCRIPT
Outline• An introduction to ns-2
• What is ns-2• Fundamentals• Writing ns-2 codes• Wireless support• Traces support and visualization• Emulation• Related work
What is ns-2
• History• What does it support
Ns Goals
• Support networking research and education• Protocol design, traffic studies, etc• Protocol comparison
• Provide a collaborative environment• Freely distributed, open source
• Share code, protocols, models, etc• Allow easy comparison of similar protocols• Increase confidence in results
• More people look at models in more situations• Experts develop models
• Multiple levels of detail in one simulator
Multiple levels of detail in simulations
Consider two nodeson an Ethernet:
A B
simplequeuingmodel:
t=1, A enqueues pkt on LANt=1.01, LAN dequeues pkt
and triggers B
detailedCSMA/CDmodel:
t=1.0: A sends pkt to NICA’s NIC starts carrier sense
t=1.005: A’s NIC concludes cs,starts tx
t=1.006: B’s NIC begins reciving pktt=1.01: B’s NIC concludes pkt
B’s NIC passes pkt to app
Alternatives
• Experimentation• Private lab• Public testbed (e.g.
Planetlab)• Shared labs (e.g.
Utah Emulab)• Analysis• Other simulator
• Custom simulators• Other general
simulators
• Operational details, but• Limited scale• Expensive, limited
flexibility• Higher overhead
• Can provide understanding, but• Limited details
• Important niches• Limited re-use
History of ns-2• History
• Cornell REAL simulator -1989• VINT project (UCB, Xerox ,USC/ISI) – 1995• USC/ISI SAMAN/CONSER project – 1999• Ns-3 project now led by Tom Henderson
• Size• ~220K lines of codes
• 45% C++• 31% OTcl• 23% test suite/example/documents
• ~400 pages of manual• Very steep learning curve for a new user!
• The most popular non-commercial discrete event packet-level simulator• Used by 10000+ users from 1000+ institutes from 50+ countries• 300+ posts to [email protected] every month
ns-2 support
• Platform• FreeBSD, Linux, Solaris, Windows and Mac
• Release• Periodical release: ~6 months
• current release: ns-2.31, Mar 10, 2007
• Daily snapshot• Now has moved to sourceforge
• Validation• 100+ test suites and 100+ examples
What ns-2 can simulate
• Wired network• Traffic model and applications• Transport protocol• Routing and Queuing• QoS• LANs
• Wireless network• Ad hoc routing and mobile IP• Sensor network• Propagation model/Energy model• WLAN (802.11)• Satellite
• Error modules• Tracing, visualization, emulation, various utilities
Wired network• Application
• HTTP, web caching• telnet, FTP, RealAudio• CBR, on-off source
• Transport• UDP, TCP (almost all variants of TCP), RTP• SRM, PLM, LMS, PGM
• Routing• Unicast (DV, LM, etc) and multicast routing (PIM etc)• Hierarchical routing• Manual routing• Broadcasting• MPLS
• Queuing• RED, FIFO, FQ, SFQ, DRR, CBQ• Diffserv and IntServ• ECN
Wireless network• Ad-hoc network routing
• AODV, DSR, TORA, DSDV• Mobile IP• ARP• Radio propagation model
• Friss-space attenuation• Two-ray ground reflection model• Shadowing model
• Sensor network• Direct diffusion• SMAC
• WLAN• Ad-hoc mode• Infrastructure mode
• Satellite• Geostationary• LEO
• Energy model• Omni-directional antenna with unity gain
“Ns” Components
• Ns, the simulator itself• Nam, the network animator
• Visualize ns (or other) output• Nam editor: GUI interface to generate ns scripts
• NSE, the network emulator• Pre-processing:
• Traffic and topology generators• Post-processing:
• Simple trace analysis, often in Awk, Perl, or Tcl
Installation
• Getting the pieces• Tcl/TK 8.x
• http://dev.scriptics.com• OTcl, TclCL, ns-2, nam-1:
http://www.isi.edu/nsnam/dist• Other utilities
• http://www.isi.edu/nsnam/ns/ns-build.html• Tcl-debug, GT-ITM, xgraph, …
Getting Help
• ns-2 build questions• http://www.isi.edu/nsnam/ns/ns-build.html
• [email protected]• [email protected]• “subscribe ns-users” in body• Archive: http://www.isi.edu/nsnam/ns
Resources
• Tcl (Tool Command Language)• http://dev.scriptics.com/scripting
• OTcl (MIT Object Tcl)• ~otcl/doc/tutorial.html (in distribution)
• ns manual• Latex sources are included in distribution: ~ns/doc• http://www.isi.edu/nsnam/ns/ns-documentation.html
Cautions
• Abstraction of the real world is necessary for a simulator
• You must justify the usage of the simulator based on your research goals• What level of details do you need?• What are your models?
Question?
Outline• An introduction to ns-2
• What is ns-2• Fundamentals• Writing ns-2 codes• Wireless support• Traces support and visualization• Emulation• Related work
Prerequisite
• Some programming experience of object-oriented language (such as C++, Java)
Discrete Event Simulation• Model world as events
• Simulator has list of events• Scheduler: take next one, run it, until done• Each event happens in an instant of virtual
(simulated) time, but takes an arbitrary amount of real time
• Ns uses simple model: single thread of control => no locking or race conditions to worry about
Discrete Event Examples
Consider two nodeson an Ethernet:
A B
simplequeuingmodel:
t=1, A enqueues pkt on LANt=1.01, LAN dequeues pkt
and triggers B
detailedCSMA/CDmodel:
t=1.0: A sends pkt to NICA’s NIC starts carrier sense
t=1.005: A’s NIC concludes cs,starts tx
t=1.006: B’s NIC begins reciving pktt=1.01: B’s NIC concludes pkt
B’s NIC passes pkt to app
Ns Architecture• Object-oriented (C++, OTcl)
• Lots of code reuses (e.g. TCP + TCP variants)• Use TclCl to bind C++ and OTcl together
• Modular approach• Fine-grained object composition
• From the simulator to a single event
• Reusability• Maintenance• Performance (speed and memory)• Careful planning of modularity
TclOTcl
TclCL
ns-2C++
Event Scheduler
Network Components
C++ and OTcl Separation
• “data” / “control” separation• C++ for “data”:
• per packet processing, core of ns• fast to run, detailed, complete control
• OTcl for control:• Simulation scenario configurations• Periodic or triggered action• Manipulating existing C++ objects• fast to write and change
+ running vs. writing speed Learning and debugging (two languages)
Control vs. Data
• Create topology• Setup routing• Create transport
connection• Create traffic
• Details of links and nodes
• Details of a routing protocol
• Details of TCP implementation
• Details of a packet
OTcl C++
24
Creating a link
n0 n1
enqT_ queue_ deqT_
drophead_ drpT_
link_ ttl_
n1 entry_head_
tracing simplex link
duplex link
[ns_ duplex-link $n0 $n1 5Mb 2ms drop-tail]
Details in C++
Octl codes
Otcl and C++: The Duality
• OTcl (object variant of Tcl) and C++ share class hierarchy
• TclCL is glue library that makes it easy to share functions, variables, etc
C++
otcl
C++/OTclsplit objects
ns
user simulation scripts
Basic Tclvariables:set x 10puts “x is $x”
functions and expressions:set y [pow x 2]set y [expr x*x]
control flow:if {$x > 0} { return $x } else {
return [expr -$x] }while { $x > 0 } {
puts $xincr x –1
}
procedures:proc pow {x n} {
if {$n == 1} { return $x }set part [pow x [expr $n-1]]return [expr $x*$part]
}
Also lists, associative arrays, etc.
=> can use a real programming language to build network topologies, traffic models, etc.
Compare Otcl to C++
• Object oriented extension of Tcl• C++ constructor/destructor => OTclinit/destroy method
• C++ this => OTcl $self• OTcl methods always “virtual”• C++ static variable => OTcl class
variable• Multiple inheritance is supported
Basic otclClass Person# constructor:Person instproc init {age} {
$self instvar age_set age_ $age
}# method:Person instproc greet {} {
$self instvar age_puts “$age_ years old: How are you doing?”
}
# subclass:Class Kid -superclass PersonKid instproc greet {} {
$self instvar age_puts “$age_ years old kid: What’s up, dude?”
}
set a [new Person 45]set b [new Kid 15]$a greet$b greet
=> can easily make variations of existing things (TCP, TCP/Reno)
Octl tutorial
ftp://ftp.tns.lcs.mit.edu/pub/otcl/doc/tutorial.html
Using ns
Problem
Simulationmodel
Setup/run simulation
with ns
Resultanalysis
Modifyns
Hello World - Interactive ModeInteractive mode:swallow 71% ns% set ns [new Simulator]_o3% $ns at 1 “puts \“Hello
World!\””1% $ns at 1.5 “exit”2
% $ns runHello World!swallow 72%
Batch mode:simple.tcl
set ns [new Simulator]$ns at 1 “puts \“Hello
World!\””$ns at 1.5 “exit”$ns run
swallow 74% ns simple.tclHello World!swallow 75%
Let’s learn ns-2 by some examples first
• #Create a simulator object• set ns [new Simulator]
• #Open the nam trace file• set nf [open out.nam w]• $ns namtrace-all $nf
• #Define a 'finish' procedure• proc finish {} {• global ns nf• $ns flush-trace• #Close the trace file• close $nf• #Execute nam on the trace file• exec nam out.nam &• exit 0• }
• #Create two nodes• set n0 [$ns node]• set n1 [$ns node]
• #Create a duplex link between the nodes• $ns duplex-link $n0 $n1 1Mb 10ms DropTail
• #Create a UDP agent and attach it to node n0• set udp0 [new Agent/UDP]• $ns attach-agent $n0 $udp0
• # Create a CBR traffic source and attach it to udp0• set cbr0 [new Application/Traffic/CBR]• $cbr0 set packetSize_ 500• $cbr0 set interval_ 0.005• $cbr0 attach-agent $udp0
• #Create a Null agent (a traffic sink) and attach it to node n1• set null0 [new Agent/Null]• $ns attach-agent $n1 $null0
• #Connect the traffic source with the traffic sink• $ns connect $udp0 $null0
• #Schedule events for the CBR agent• $ns at 0.5 "$cbr0 start"• $ns at 4.5 "$cbr0 stop"• #Call the finish procedure after 5 seconds of simulation time• $ns at 5.0 "finish"
• #Run the simulation• $ns run
• #Create a simulator object• set ns [new Simulator]
• #Define different colors for data flows• $ns color 1 Blue• $ns color 2 Red
• #Open the nam trace file• set nf [open out.nam w]• $ns namtrace-all $nf
• #Define a 'finish' procedure• proc finish {} {• global ns nf• $ns flush-trace• #Close the trace file• close $nf• #Execute nam on the trace file• exec nam out.nam &• exit 0• }
• #Create four nodes• set n0 [$ns node]• set n1 [$ns node]• set n2 [$ns node]• set n3 [$ns node]
• #Create links between the nodes• $ns duplex-link $n0 $n2 1Mb 10ms DropTail• $ns duplex-link $n1 $n2 1Mb 10ms DropTail• $ns duplex-link $n3 $n2 1Mb 10ms SFQ
• $ns duplex-link-op $n0 $n2 orient right-down• $ns duplex-link-op $n1 $n2 orient right-up• $ns duplex-link-op $n2 $n3 orient right
• #Monitor the queue for the link between node 2 and node 3• $ns duplex-link-op $n2 $n3 queuePos 0.5
• #Create a UDP agent and attach it to node n0• set udp0 [new Agent/UDP]• $udp0 set class_ 1• $ns attach-agent $n0 $udp0
• # Create a CBR traffic source and attach it to udp0• set cbr0 [new Application/Traffic/CBR]• $cbr0 set packetSize_ 500• $cbr0 set interval_ 0.005• $cbr0 attach-agent $udp0
• #Create a UDP agent and attach it to node n1• set udp1 [new Agent/UDP]• $udp1 set class_ 2• $ns attach-agent $n1 $udp1
• # Create a CBR traffic source and attach it to udp1• set cbr1 [new Application/Traffic/CBR]• $cbr1 set packetSize_ 500• $cbr1 set interval_ 0.005• $cbr1 attach-agent $udp1
• #Create a Null agent (a traffic sink) and attach it to node n3• set null0 [new Agent/Null]• $ns attach-agent $n3 $null0
• #Connect the traffic sources with the traffic sink• $ns connect $udp0 $null0 • $ns connect $udp1 $null0
• #Schedule events for the CBR agents• $ns at 0.5 "$cbr0 start"• $ns at 1.0 "$cbr1 start"• $ns at 4.0 "$cbr1 stop"• $ns at 4.5 "$cbr0 stop"• #Call the finish procedure after 5 seconds of simulation time• $ns at 5.0 "finish"
• #Run the simulation• $ns run
• #Create a simulator object• set ns [new Simulator]
• #Tell the simulator to use dynamic routing• $ns rtproto DV
• #Open the nam trace file• set nf [open out.nam w]• $ns namtrace-all $nf
• #Define a 'finish' procedure• proc finish {} {• global ns nf• $ns flush-trace• #Close the trace file• close $nf• #Execute nam on the trace file• exec nam out.nam &• exit 0• }
• #Create seven nodes• for {set i 0} {$i < 7} {incr i} {• set n($i) [$ns node]• }
• #Create links between the nodes• for {set i 0} {$i < 7} {incr i} {• $ns duplex-link $n($i) $n([expr ($i+1)%7]) 1Mb 10ms DropTail• }
• #Create a UDP agent and attach it to node n(0)• set udp0 [new Agent/UDP]• $ns attach-agent $n(0) $udp0
• # Create a CBR traffic source and attach it to udp0• set cbr0 [new Application/Traffic/CBR]• $cbr0 set packetSize_ 500• $cbr0 set interval_ 0.005• $cbr0 attach-agent $udp0
• #Create a Null agent (a traffic sink) and attach it to node n(3)• set null0 [new Agent/Null]• $ns attach-agent $n(3) $null0
• #Connect the traffic source with the traffic sink• $ns connect $udp0 $null0
• #Schedule events for the CBR agent and the network dynamics• $ns at 0.5 "$cbr0 start"• $ns rtmodel-at 1.0 down $n(1) $n(2)• $ns rtmodel-at 2.0 up $n(1) $n(2)• $ns at 4.5 "$cbr0 stop"• #Call the finish procedure after 5 seconds of simulation time• $ns at 5.0 "finish"
• #Run the simulation• $ns run
OK, now what if I want to create a new protocol?
Ping protocol
• One node will be able to send a packet to another node which will return it immediately, so that the round-trip-time can be calculated
Header file• struct hdr_ping {
char ret; double send_time;};
• class PingAgent : public Agent { public: PingAgent(); int command(int argc, const char*const* argv);void recv(Packet*, Handler*); protected: int off_ping_;};
C++ codes• #include "ping.h"
• static class PingHeaderClass : public PacketHeaderClass {• public:• PingHeaderClass() : PacketHeaderClass("PacketHeader/Ping", • sizeof(hdr_ping)) {}• } class_pinghdr;
• static class PingClass : public TclClass {• public:• PingClass() : TclClass("Agent/Ping") {}• TclObject* create(int, const char*const*) {• return (new PingAgent());• }• } class_ping;
• PingAgent::PingAgent() : Agent(PT_PING) { bind("packetSize_", &size_);bind("off_ping_", &off_ping_); }
C++
otcl
C++/OTclsplit objects
ns
Otcl and C++: The Duality
• OTcl (object variant of Tcl) and C++ share class hierarchy
• TclCL is glue library that makes it easy to share functions, variables, etc
C++
otcl
C++/OTclsplit objects
ns
user simulation scripts
• int PingAgent::command(int argc, const char*const* argv){if (argc == 2) {
if (strcmp(argv[1], "send") == 0) {// Create a new packet Packet* pkt = allocpkt(); // Access the Ping header for the new packet: hdr_ping* hdr = (hdr_ping*)pkt->access(off_ping_); // Set the 'ret' field to 0, so the receiving node knows// that it has to generate an echo packet hdr->ret = 0; // Store the current time in the 'send_time' field hdr->send_time = Scheduler::instance().clock(); // Send the packet send(pkt, 0);// return TCL_OK, so the calling function knows that the // command has been processed return (TCL_OK); }}
// If the command hasn't been processed by PingAgent()::command, // call the command() function for the base class return (Agent::command(argc, argv)); }
void PingAgent::recv(Packet* pkt, Handler*) {
// Access the IP header for the received packet: hdr_ip* hdrip = (hdr_ip*)pkt->access(off_ip_); // Access the Ping header for the received packet: hdr_ping* hdr = (hdr_ping*)pkt->access(off_ping_); // Is the 'ret' field = 0 (i.e. the receiving node is being pinged)?if (hdr->ret == 0) {
// Send an 'echo'. First save the old packet's send_timedouble stime = hdr->send_time; // Discard the packet Packet::free(pkt); // Create a new packetPacket* pktret = allocpkt();
// Access the Ping header for the new packet:hdr_ping* hdrret = (hdr_ping*)pktret->access(off_ping_);
// Set the 'ret' field to 1, so the receiver won't send another // echo hdrret->ret = 1;// Set the send_time field to the correct valuehdrret->send_time = stime;// Send the packet send(pktret, 0);
} else {// A packet was received. Use tcl.eval to call the Tcl// interpreter with the ping results. // Note: In the Tcl code, a procedure 'Agent/Ping recv// {from rtt}' // has to be defined which allows the user to react to the // ping result. char out[100]; // Prepare the output to the Tcl interpreter. Calculate the // round trip timesprintf(out, "%s recv %d %3.1f", name(), hdrip->src_.addr_ >> Address::instance().NodeShift_[1], (Scheduler::instance().clock()-hdr->send_time) * 1000); Tcl& tcl = Tcl::instance(); tcl.eval(out); // Discard the packet Packet::free(pkt);
} }
Necessary changes (I): packet.henum packet_t {
PT_TCP,PT_UDP, ...... // insert new packet types here PT_TFRC, PT_TFRC_ACK, PT_PING,// packet protocol ID for our ping-agentPT_NTYPE // This MUST be the LAST one
};
Necessary changes (I)class p_info {
public: p_info() {name_[PT_TCP]= "tcp"; name_[PT_UDP]= "udp"; ...........name_[PT_TFRC]= "tcpFriend"; name_[PT_TFRC_ACK]= "tcpFriendCtl"; name_[PT_PING]="Ping";
name_[PT_NTYPE]= "undefined"; } .....
}
Necessary change (II): tcl/lib/ns-default.tcl
• Agent/Ping set packetSize_ 64
Necessary change (III): 'tcl/lib/ns-packet.tcl'
{ SRMEXT off_srm_ext_} { Ping off_ping_ }} {
set cl PacketHeader/[lindex $pair 0]
Necessary Changes (IV): Makefile
sessionhelper.o delaymodel.o srm-ssm.o \srm-topo.o \ping.o \$(LIB_DIR)int.Vec.o $(LIB_DIR)int.RVec.o \$(LIB_DIR)dmalloc_support.o \
OK, now how to write a tcl script to use the new Ping Agent you
just wrote?
Ping.tcl#Create a simulator objectset ns [new Simulator]#Open a trace fileset nf [open out.nam w]$ns namtrace-all $nf#Define a 'finish' procedureproc finish {} {
global ns nf$ns flush-traceclose $nfexec nam out.nam &exit 0
}
#Create three nodesset n0 [$ns node]set n1 [$ns node]set n2 [$ns node]#Connect the nodes with two links$ns duplex-link $n0 $n1 1Mb 10ms DropTail$ns duplex-link $n1 $n2 1Mb 10ms DropTail#Define a 'recv' function for the class 'Agent/Ping'Agent/Ping instproc recv {from rtt} {
$self instvar node_puts "node [$node_ id] received ping answer from \
$from with round-trip-time $rtt ms."}
#Create two ping agents and attach them to the nodes n0 and n2
set p0 [new Agent/Ping]$ns attach-agent $n0 $p0set p1 [new Agent/Ping]$ns attach-agent $n2 $p1#Connect the two agents$ns connect $p0 $p1#Schedule events$ns at 0.2 "$p0 send"$ns at 0.4 "$p1 send"$ns at 0.6 "$p0 send"$ns at 0.6 "$p1 send"$ns at 1.0 "finish"#Run the simulation$ns run
C++/OTcl Linkage
Root of ns-2 object hierarchy
bind(): link variable values between C++ and OTcl TclObject
command(): link OTcl methods to C++ implementations
TclClass Create and initialize TclObject’s
Tcl C++ methods to access Tcl interpreter
TclCommand Standalone global commands
EmbeddedTcl ns script initialization
TclObject
• Basic hierarchy in ns for split objects• Mirrored in both C++ and OTcl• Example
•• set set tcptcp [new Agent/TCP][new Agent/TCP]
•• $$tcptcp set set packetSizepacketSize_ 1024_ 1024
•• $$tcptcp advancebyadvanceby 50005000
TclObject: Hierarchy and Shadowing
TclObject
Agent
Agent/TCP
Agent/TCP OTclshadow object
_o123Agent/TCP C++
object
*tcp
TclObject
Agent
TcpAgent
OTcl classhierarchy
C++ classhierarchy
TclObject::bind()
• Link C++ member variables to OTclobject variables
• C++• TcpAgent::TcpAgent() {
• bind(“window_”, &wnd_);• … …
• }
• OTcl•• set set tcptcp [new Agent/TCP][new Agent/TCP]•• $$tcptcp set window_ 200set window_ 200
TclObject::command()
• Implement OTcl methods in C++• Trap point: OTcl method cmd{}
• Access the shadow object• Send all arguments after cmd{} call to
TclObject::command()
TclObject::command()
$tcp send TclObject::unknown{} $tcp cmd sendno suchprocedure
TcpAgent::command()
match “send”?
Invoke parent: return Agent::command()
process and return
Yes No
OTcl space
C++ space
TclObject::command()• OTcl
set tcp [new Agent/TCP]$tcp send 10
• C++int TcpAgent::command(int argc,
const char*const* argv) {if (argc == 3) {
if (strcmp(argv[1], “send”) == 0) {int newseq = atoi(argv[2]);……return(TCL_OK);
}}return (Agent::command(argc, argv);
}
TclObject: Creation and Deletion
• Global procedures: new{}, delete{}• Example
•• set set tcptcp [new Agent/TCP][new Agent/TCP]
•• ……
•• delete $delete $tcptcp
C++
OTcl
TclObject: Creation and Deletion
invoke parentconstructor
Agent/TCPconstructor
Parent(Agent)constructor
invoke parentconstructor
TclObjectconstructor
create C++object
AgentTCPconstructor
invoke parentconstructor
invoke parentconstructor
parent (Agent)constructor
do nothing,return
TclObject (C++)constructor
bind variablesand return
bind variablesand return
create OTclshadow object
complete initialization
complete initialization
which C++ object to create? – TclClass
TclClass
TclObject
Agent
Agent/TCP
TclObject
Agent
TcpAgent
NsObject ??
OTclC++ mirroringStatic class TcpClass : public TclClass {public:
TcpClass() : TclClass(“Agent/TCP”) {}TclObject* create(int, const char*const*) {
return (new TcpAgent());}
} class_tcp;
Static class TcpClass : public TclClass {public:
TcpClass() : TclClass(“Agent/TCP”) {}TclObject* create(int, const char*const*) {
return (new TcpAgent());}
} class_tcp;
NsObject• Other important objects:
• NsObject: has recv() method• Connector: has target() and drop()• BiConnector: uptarget() &
downtarget()• Class hierarchy
• NsObject• Connector
• PingAgent• BiConnector
• Mac802_11PHY
MAC
NETWORK
TRANSPORT
SESSION
PRESENTATION
APPLICATION
Class Tcl• Singleton class with a handle to Tcl interpreter
• Tcl& tcl = Tcl::instance();• Usage
• Invoke OTcl procedure• tcl.evalc(“callbackX”);
• Obtain OTcl evaluation results• clock_ = atof(tcl.result());
• Pass a result string to OTcl•tcl.resultf(“%g”, clock())
• Return success/failure code to OTcl• tcl.error(“command not found”);
Class TclTcl& tcl = Tcl::instance();if (argc == 2) {
if (strcmp(argv[1], “now”) == 0) {tcl.resultf(“%g”, clock());return TCL_OK;
}tcl.error(“command not found”);return TCL_ERROR;
} else if (argc == 3) {tcl.eval(argv[2]);clock_ = atof(tcl.result());return TCL_OK;
}
Class TclCommand
• How to implement an OTcl command “ns-random” in C++
class RandomCommand : public TclCommand {public:
RandomCommand() : TclCommand("ns-random") {}virtual int command(int argc, const char*const* argv);
};
int RandomCommand::command(int argc, const char*const* argv){
Tcl& tcl = Tcl::instance();if (argc == 1) {
sprintf(tcl.buffer(), "%u", Random::random());tcl.result(tcl.buffer());
}
Brief summary
• TclObject• Unified interpreted (OTcl) and compiled (C++)
class hierarchies• Seamless access (procedure call and variable
access) between OTcl and C++• TclClass
• Establish interpreted hierarchy• Shadowing objects
• Tcl: primitives to access Tcl interpreter
Question?
Ns programming
• Create the event scheduler• Turn on tracing• Create network• Setup routing• Insert errors• Create transport connection• Create traffic• Transmit application-level data
Creating Event Scheduler
• Create event scheduler• set ns [new Simulator]
• Schedule events• $ns at <time> <event>
• <event>: any legitimate ns/tcl commands• $ns at 5.0 “finish”
• Start scheduler• $ns run
Event Scheduler• Event: at-event and packet• List scheduler: default (FIFO)
• Heap: good for many events (O(log n) • Calendar queue
• A priority queue having N buckets each with width w. An item with priority p goes in bucket (p/w)%N
• Real-time scheduler• Synchronize with real-time• Network emulation
• set ns_ [new Simulator]• $ns_ use-scheduler Heap• $ns_ at 300.5 “$self halt”
Some scheduler-related commands
• Set now [$ns now]• $ns cancel <event>• $ns after <delay> <event>
• Execute <event> after <delay>• $ns dumpq
• Dump all events in the scheduler queue
Discrete Event Scheduler
time_, uid_, next_, handler_head_ ->
handler_ -> handle()
time_, uid_, next_, handler_insert
head_ ->
Tracing and Monitoring I
• Packet tracing:• On all links: $ns trace-all [open out.tr w]• On one specific link: $ns trace-queue $n0 $n1$tr
• <Event> <time> <from> <to> <pkt> <size> -- <fid> <src> <dst> <seq> <attr>
• + 1 0 2 cbr 210 ------- 0 0.0 3.1 0 0• - 1 0 2 cbr 210 ------- 0 0.0 3.1 0 0• r 1.00234 0 2 cbr 210 ------- 0 0.0 3.1 0 0
• Event tracing (support TCP currently)• Record “event” in trace file: $ns eventtrace-all• E 2.267203 0 4 TCP slow_start 0 210 1
Tracing and Monitoring II
• Queue monitor • set qmon [$ns monitor-queue $n0 $n1 $q_f $sample_interval]
• Get statistics for a queue $qmon set pdrops_
• Record to trace file as an optional
• Flow monitorset fmon [$ns_ makeflowmon Fid]$ns_ attach-fmon $sink $fmon$fmon set pdrops_
Tracing and Monitoring III
• Visualize trace in nam$ns namtrace-all [open test.nam w] $ns namtrace-queue $n0 $n1
• Variable tracing in namAgent/TCP set nam_tracevar_ true$tcp tracevar srtt_$tcp tracevar cwnd_
• Monitor agent variables in nam$ns add$ns add--agentagent--trace $trace $tcptcp$ns monitor$ns monitor--agentagent--trace $trace $tcptcp$srm0 $srm0 tracevartracevar cwndcwnd__…………$ns delete$ns delete--agentagent--trace $trace $tcptcp
Ns Internals
• Tcl commands translates into • series of object creation • plumbing of these objects
Creating Network• Nodes
set n0 [$ns node]set n1 [$ns node]
• Links and queuing$ns <link_type> $n0 $n1 <bandwidth>
<delay> <queue_type>• <link_type>: duplex-link, simplex-link• <queue_type>: DropTail, RED, CBQ, FQ, SFQ,
DRR, diffserv RED queues
Components of Nodeid_
Address of nodeMonotonically increasing by 1
neighbor_A list of neighbors
agent_A list of agents
nodetype_A node type identifier
A routing module
Unicast node
• Address classifier• Distribute incoming packets to the correct link
• Port classifier• Distribute incoming packets to the correct
agent• First element that handles incoming
packet at the node• unicast: entry_• multicast: switch_
Network Topology: Node
n0 n1
Addr Classifier
Port Classifier
classifier_
dmux_
entry_
Node entry
Unicast Node
Multicast Classifier
classifier_
dmux_
entry_
Node entry
Multicast Node
multiclassifier_
set n0 [ns_ node] Set ns_ [new Simulator –multicast on]Set n1 [ns_ node]
0 0
1
Node Addressing
• Two basic address styles available: flat and hierarchical
• Default flat address: 32 bits each for node and port id
• Default hier address: • 3 levels of hierarchy• 10 11 11 or 1 9 11 11 if mcast specified
• Different bit allocation possible for specific hier addresses
88
Hierarchical Node
n2
Nodeentry
Level 1Level 2
Level 3
Addressclassifier To Port
demux
ns_ node-config –addressing hier
Classifiers• Table of n slots• When a packet is received
• classify() identifies the slot to forward the packets• Address Classifiers
• Parse address in packet• Methods
• Install{}: • Elements{}• Clear{}
90
Network Topology: Link
n0 n1
enqT_ queue_ deqT_
drophead_ drpT_
link_ ttl_
n1 entry_head_
tracing simplex link
duplex link
[ns_ duplex-link $n0 $n1 5Mb 2ms drop-tail]
Connectors
• Connectors • Receive incoming packets, and transmit them to their target_
• Different types of connectors• Queue
• Holds a certain number of packets. Packets exceeding their queue-size are sent to the queue’s drop-target_
• LinkDelay• Model delay/bandwidth of the link
• TTLChecker• Decrements TTL on each packet, drops the packet if the TTL
becomes 0• DynaLink
• Transmit packets if the link is up, drop packet otherwise• Trace
Creating Network: LAN
$ns make-lan <node_list> <bandwidth> <delay> <ll_type> <ifq_type> <mac_type> <channel_type>
<ll_type>: LL<ifq_type>: Queue/DropTail,<mac_type>: MAC/802_3<channel_type>: Channel
Local area network• Link layer
• Queue: interface queue• LL: simulate a link layer protocol (e.g. ARQ)
• Mac layer• Must simulate some MAC protocol CS/CD/CA• Sending: follow a MAC protocol before transmitting packets to
Channel• Receiving: pass packets to link layer
• Physical layer• Channel
• Sending side: simulate the shared medium• Classifier/Mac
• Receiving side: delivering and optionally replicating packets to the receiving MAC objects
Routing module
• Routing agent• Exchange routing packets with neighbors
• Route logic• Use information gathered by routing agent (or
topology database) to perform route computation
• Classifier• Use computed routing table to perform packet
forwarding
Setup Routing
• Unicast$ns rtproto <type><type>: Static, Session, DV, cost, multi-path, Manual
• Multicast$ns multicast (right after [new Simulator])$ns mrtproto <type><type>: CtrMcast, DM, ST, BST
• Other types of routing supported: source routing, hierarchical routing
Examples
$ns rtproto Static ; default, use the Dijkstra’s all-pairs SPF algorithm$ns rtproto Session ; recompute route when topology changes$ns rtproto DV $n1 $n2 $n3 $ns rtproto LS $n1 $n2
set n1 [$ns Node] ; only enable $n1 to use multiPaths where applicable$n1 set multiPath_ 1 ; only DV routing can generate multipath routes
$ns cost $n1 $r1 2$ns cost $n2 $r2 2$ns cost $r1 $n2 3
Routing..
n0 n1
Addr Classifier
Port Classifier
classifier_
dmux_
entry_
Node entry 01 enqT_ queue_ deqT_
drophead_ drpT_
link_ ttl_
n1 entry_
head_
..Routing
n0 n1
Addr Classifier
Port Classifier
classifier_
dmux_
entry_
01
Addr Classifier
Port Classifier
classifier_
dmux_
entry_
10
Link n0-n1
Link n1-n0
Class RouteLogic
• Route configuration• rtproto{} -> configure{} -> compute-routes{}
• Query nexthop•[$ns get-routelogic] lookup $n1 $2
• Recompute route on topology change• [$ns get-routelogic] notify
Inserting Errors
• Creating Error Moduleset loss_module [new ErrorModel]$loss_module set rate_ 0.01$loss_module unit pkt$loss_module ranvar [new RandomVariable/Uniform]$loss_module drop-target [new Agent/Null]
• Inserting Error Module$ns lossmodel $loss_module $n0 $n1
Network Dynamics
• Link failures• Hooks in routing module to reflect routing
changes• Four models
$ns $ns rtmodelrtmodel Trace <Trace <config_fileconfig_file> $n0 $n1> $n0 $n1$ns $ns rtmodelrtmodel Exponential {<Exponential {<paramsparams>} $n0 $n1>} $n0 $n1$ns $ns rtmodelrtmodel Deterministic {<Deterministic {<paramsparams>} $n0 $n1>} $n0 $n1$ns $ns rtmodelrtmodel--at <time> up|down $n0 $n1at <time> up|down $n0 $n1
• Parameter list[<start>] <up_interval> <down_interval> [<finish>][<start>] <up_interval> <down_interval> [<finish>]
• UDPset udp [new Agent/UDP]set null [new Agent/Null]$ns attach-agent $n0 $udp$ns attach-agent $n1 $null$ns connect $udp $null
• CBRset src [new
Application/Traffic/CBR]• Exponential or Pareto
on-offset src [new
Application/Traffic/Exponential]set src [new
Application/Traffic/Pareto]$src attach-agent $udp
Creating Connection and Traffic I
Creating Connection and Traffic II
• TCPset tcp [new Agent/TCP]set tcpsink [new
Agent/TCPSink]$ns attach-agent $n0 $tcp$ns attach-agent $n1
$tcpsink$ns connect $tcp $tcpsink
• FTPset ftp [new Application/FTP]$ftp attach-agent $tcp• Telnetset telnet [new
Application/Telnet]$telnet attach-agent $tcp
Creating Traffic: Trace Driven
• Trace drivenset tfile [new Tracefile]$tfile filename <file>set src [new Application/Traffic/Trace]$src attach-tracefile $tfile<file>:
• inter-packet time (msec) and packet size (byte)
Transport
n0 n1
Addr Classifier
Port Classifier
classifier_
dmux_
entry_
Agent/TCP
agents_
Addr Classifier
Port Classifier
classifier_
dmux_
entry_
Agent/TCPSink
agents_
dst_=1.0 dst_=0.0
set tcp [new Agent/TCP]ns_ attach-agent $n0 $tcp
set tcpsink [new Agent/TCPSink]ns_ attach-agent $n1 $tcpsink
ns_ connect $tcp $tcpsink
0
0
1
0
Application
n0 n1
Addr Classifier
Port Classifier
classifier_
dmux_
entry_
Agent/TCP
agents_
Addr Classifier
Port Classifier
classifier_
dmux_
entry_
Agent/TCPSink
agents_
dst_=1.0 dst_=0.0Application/FTP
set ftp [new Application/FTP]$ftp attach-agent $tcp$ns at 1.2 “$ftp start”
0
0
1
0
Packet Flow
01
n0 n1
Addr Classifier
Port Classifier
entry_
0 Agent/TCP Addr Classifier
Port Classifier
entry_
10
Link n0-n1
Link n1-n0
0 Agent/TCPSink
dst_=1.0 dst_=0.0Application/FTP
Application objects I
• Exponential• packetSize_• burst_time_• idle_time_• rate_
• CBR• packetSize_• rate_• interval_• random_• maxpkts_
Application objects II• Pareto
• packetSize_• burst_time_• idle_time_• rate_• shape_
• Telnet• interval_
• FTP• maxpkts_
• Default values in ns/tcl/lib/ns-default.tcl• All above are virtual applications
• focus only on “size” and “time” when data are transferred
Application-Level Simulation• Simulate applications that actually transfer their
own data• e.g. simulate various webcaching algorithms
• Features• Build on top of existing transport protocol• Transmit user data, e.g., HTTP header
• Examples• TCP: Application/HttpApp• UDP: Agent/Message
Application-Level Simulationa representation of a uniform application-level data unit (ADU)a common interface to pass data between applicationsmechanisms to pass data between applications and transport agents.
ADUfunctionality of an ADU is similar to that of a Packetpack user data into an arraythen included in the user data area of an nspacketUser must derive new agents to acceptuser data from applications, or use an wrapper like TcpApp
Passing data between applications
class Process {public:Process() : target_(0) {}inline Process*& target() { return target_; }
virtual void process_data(int size, char* data) = 0;virtual void send_data(int size, char* data = 0);
protected:Process* target_;};
Compare to Real World
• More abstract (much simpler):• No addresses, just global variables• Connect them rather than name
lookup/bind/listen/accept• Easy to change implementation
Set tsrc2 [new agent/TCP/Newreno]Set tsrc3 [new agent/TCP/Vegas]
Summary: Generic Script Structure
set ns [new Simulator]set ns [new Simulator]
# [Turn on tracing]# [Turn on tracing]
# Create topology# Create topology
# Setup packet loss, link dynamics# Setup packet loss, link dynamics
# Create routing agents# Create routing agents
# Create: # Create:
# # -- multicast groupsmulticast groups
# # -- protocol agentsprotocol agents
# # -- application and/or setup traffic sourcesapplication and/or setup traffic sources
# Post# Post--processing processing procsprocs
# Start simulation# Start simulation
Question?
Two examples
• Multicast• Web traffic
G2time1.3s
G2time1.2s
G1G2
time1.35s
Example: Multicast Routing
• Dynamic group membership
n0 n1
n2
n3
1.5Mb, 10ms
1.5Mb, 10ms
G1
time1.25s
G2
1.5Mb, 10ms
Multicast: Step 1
• Scheduler, tracing, and topology
# Create scheduler# Create scheduler
set ns [new Simulator]set ns [new Simulator]
# Turn on multicast# Turn on multicast
$ns multicast$ns multicast
# Turn on Tracing# Turn on Tracing
set set fdfd [new [new ““mcast.nammcast.nam”” w]w]
$ns $ns namtracenamtrace--all $all $fdfd
Multicast: Step 2
• Topology
# Create nodes# Create nodes
set n0 [$ns node]set n0 [$ns node]
set n1 [$ns node]set n1 [$ns node]
set n2 [$ns node]set n2 [$ns node]
set n3 [$ns node]set n3 [$ns node]
# Create links# Create links
$ns duplex$ns duplex--link $n0 $n1 1.5Mb 10ms link $n0 $n1 1.5Mb 10ms DropTailDropTail
$ns duplex$ns duplex--link $n0 $n2 1.5Mb 10ms link $n0 $n2 1.5Mb 10ms DropTailDropTail
$ns duplex$ns duplex--link $n0 $n3 1.5Mb 10ms link $n0 $n3 1.5Mb 10ms DropTailDropTail
Multicast: Step 3
• Routing and group setup
# Routing protocol: let# Routing protocol: let’’s run distance vectors run distance vector
$ns $ns mrtprotomrtproto DMDM
# Allocate group addresses# Allocate group addresses
set group1 [Node set group1 [Node allocaddrallocaddr]]
set group2 [Node set group2 [Node allocaddrallocaddr]]
Multicast: Step 4• Sender 0
# Transport agent for the traffic source# Transport agent for the traffic sourceset set udp0udp0 [new Agent/UDP][new Agent/UDP]$ns attach$ns attach--agent $agent $n1n1 $$udp0udp0$$udp0udp0 set set dst_addrdst_addr_ $_ $group1group1$$udp0udp0 set set dst_portdst_port_ 0_ 0
# Constant Bit Rate source #0 # Constant Bit Rate source #0 set set cbr0cbr0 [new Application/Traffic/CBR][new Application/Traffic/CBR]$$cbr0cbr0 attachattach--agent $agent $udp0udp0# Start at time 1.0 second# Start at time 1.0 second$ns at 1.0 "$$ns at 1.0 "$cbr0cbr0 start"start"
Multicast: Step 5• Sender 1
# Transport agent for the traffic source# Transport agent for the traffic sourceset set udp1udp1 [new Agent/UDP][new Agent/UDP]$ns attach$ns attach--agent $agent $n3n3 $$udp1udp1$$udp1udp1 set set dst_addrdst_addr_ $_ $group2group2$$udp1udp1 set set dst_portdst_port_ 0_ 0
# Constant Bit Rate source #0 # Constant Bit Rate source #0 set set cbr1cbr1 [new Application/Traffic/CBR][new Application/Traffic/CBR]$$cbr1cbr1 attachattach--agent $agent $udp1udp1# Start at time 1.1 second# Start at time 1.1 second$ns at 1.1 "$$ns at 1.1 "$cbr1cbr1 start"start"
Multicast: Step 6
• Receiver with dynamic membership
# Can also be Agent/Null# Can also be Agent/Null
set set rcvrrcvr [new Agent/[new Agent/LossMonitorLossMonitor]]
# Assign it to node $n2# Assign it to node $n2
$ns at $ns at 1.21.2 "$n2 join"$n2 join--group $group $rcvrrcvr $$group2group2""$ns at $ns at 1.251.25 "$n2 leave"$n2 leave--group $group $rcvrrcvr $$group2group2""$ns at $ns at 1.31.3 "$n2 join"$n2 join--group $group $rcvrrcvr $$group2group2""$ns at $ns at 1.351.35 "$n2 join"$n2 join--group $group $rcvrrcvr $$group1group1""
Multicast: Step 7
• End-of-simulation wrapper (as usual)
$ns at 2.0 "finish"$ns at 2.0 "finish"proc finish {} {proc finish {} {
global ns global ns fdfdclose $close $fdfd$ns flush$ns flush--tracetraceputs "running puts "running namnam..."..."exec exec namnam mcast.nammcast.nam &&exit 0exit 0
}}$ns run$ns run
Example: Web traffic
1
2
0
8 3
56
49
7
10 11
1.5Mb, 40ms
10Mb, 20ms
Multiple levels of feedback effects in Web traffic
TCP
HTTP
userclient server
request
response
request
response
timeuserclick
userclick
userclickend of page
user think timepage transmission
> 10sec
1~10sec
< 1sec
2008/10/7
3-level Web Model
•User sessionUser arrivalNumber of page per user
•PagePage arrivalNumber of objects per page
•ObjectObject arrivalObject size
Web
object
user
Page
Web traffic: Step 1
• Scheduler and tracing# Create scheduler# Create schedulerset ns [new Simulator]set ns [new Simulator]
# instantiate web traffic class# instantiate web traffic classset pool set pool [new [new PagePool/WebTrafPagePool/WebTraf]]
# Turn on Tracing# Turn on Tracingset set fdfd [new [new ““web.namweb.nam”” w]w]$ns $ns namtracenamtrace--all $all $fdfd
Web traffic: Step 2
• Topology# Create nodes# Create nodesfor {set i 0} {$i < 12} {for {set i 0} {$i < 12} {incrincr i} {i} {
set n($i) [$ns node]set n($i) [$ns node]}}$ns set $ns set srcsrc_ [list 2 3 4 5 6]_ [list 2 3 4 5 6]$ns set $ns set dstdst_ [list 7 8 9 10 11]_ [list 7 8 9 10 11]
# Create links# Create links$ns duplex$ns duplex--link $n(0) $n(1) 1.5Mb 40ms link $n(0) $n(1) 1.5Mb 40ms DropTailDropTail$ns duplex$ns duplex--link $n(0) $n(2) 10Mb 20ms link $n(0) $n(2) 10Mb 20ms DropTailDropTail$ns duplex$ns duplex--link $n(0) $n(3) 10Mb 20ms link $n(0) $n(3) 10Mb 20ms DropTailDropTail
Web traffic: Step 3
• Set up client and server nodes
$$pool pool setset--numnum--clientclient [[llengthllength [$ns set [$ns set srcsrc_]]_]]$pool $pool setset--numnum--serverserver [[llengthllength [$ns set [$ns set dstdst_]]_]]
set i 0set i 0foreachforeach s [$ns set s [$ns set srcsrc_] {_] {
$pool $pool setset--clientclient $i $n($s)$i $n($s)incrincr ii
}}set i 0set i 0foreachforeach s [$ns set s [$ns set dstdst_] {_] {
$pool $pool setset--serverserver $i $n($s)$i $n($s)incrincr i i
}}
Web traffic: Step 4• Specify the distributions for page arrival,
page size, object arrival, object sizeset set interPageinterPage [new [new RandomVariableRandomVariable/Exponential] /Exponential] $$interPageinterPage set set avgavg_ 1_ 1set set pageSizepageSize [new [new RandomVariableRandomVariable/Constant]/Constant]$$pageSizepageSize set set valval_ 1_ 1set set interObjinterObj [new [new RandomVariableRandomVariable/Exponential]/Exponential]$$interObjinterObj set set avgavg_ 0.01_ 0.01set set objSizeobjSize [new [new RandomVariable/ParetoIIRandomVariable/ParetoII]]$$objSizeobjSize set set avgavg_ 10_ 10$$objSizeobjSize set shape_ 1.2set shape_ 1.2
Web traffic: Step 5• Schedule web sessions
# Let# Let’’s schedule two sessionss schedule two sessions$pool set$pool set--numnum--session 2session 2# Let# Let’’s have 10 pages per sessions have 10 pages per sessionset set numPagenumPage 1010
# session 1 starts at time 0.1s# session 1 starts at time 0.1s$pool $pool createcreate--sessionsession 0 $0 $numPagenumPage 0.1 $0.1 $interPageinterPage $$pageSizepageSize$$interObjinterObj $$objSizeobjSize
# session 2 starts at time 1.2s # session 2 starts at time 1.2s $pool create$pool create--session 1 $session 1 $numPagenumPage 1.2 $1.2 $interPageinterPage $$pageSizepageSize$$interObjinterObj $$objSizeobjSize
Web traffic: Step 6
• End-of-simulation wrapper (as usual)
$ns at 10.0 "finish"$ns at 10.0 "finish"proc finish {} {proc finish {} {
global ns global ns fdfdclose $close $fdfd$ns flush$ns flush--tracetraceputs "running puts "running namnam..."..."exec exec namnam web.namweb.nam &&exit 0exit 0
}}$ns run$ns run
Question?
Outline• An introduction to ns-2
• What is ns-2• Fundamentals• writing ns-2 codes• Wireless support• Traces support and visualization• Emulation• Related work
Writing ns-2 codes
• Extending ns• In OTcl• In C++
• Debugging
ns Directory Structure
TK8.3 OTcl tclclTcl8.3 ns-2 nam-1
tcl
ex test lib
...
...
examples validation tests
C++ code
OTcl code
ns-allinone
mcast
ensure new changes do not
break the old codes
Extending ns in OTcl
• If you don’t want to compile• source your changes in your simulation
scripts• Otherwise
• Modifying code; recompile• Adding new files
• Change Makefile (NS_TCL_LIB), tcl/lib/ns-lib.tcl• Recompile
Add Your Changes into ns
TK8.3 OTcl tclclTcl8.3 ns-2 nam-1
tcl
ex test lib
...
...
examples validation tests
C++ code
OTcl code
ns-allinone
mcastmysrc
msg.tcl
Add Your Change into ns• tcl/lib/ns-lib.tclClass SimulatorClass Simulator……source ../source ../mysrc/msg.tclmysrc/msg.tcl
• MakefileNS_TCL_LIB = NS_TCL_LIB = \\tcl/mysrc/msg.tcltcl/mysrc/msg.tcl \\……
• Or: change Makefile.in, make make distcleandistclean, then ./configure ./configure ----enableenable--debug ,debug ,
make depend make depend andand makemake
Writing ns-2 codes
• Extending ns• In OTcl• In C++
• New components
Extending ns in C++
• Modifying code• make depend• Recompile
• Adding code in new files• Change Makefile• make depend• recompile
Creating New Components
• Guidelines• Two styles
• New agent based on existing packet headers• Add new packet header
Guidelines
• Decide position in class hierarchy• I.e., which class to derive from?
• Create new packet header (if necessary)• Create C++ class, fill in methods• Define OTcl linkage (if any)• Write OTcl code (if any)• Build (and debug)
New Agent, Old Header
• Exercise: TCP jump start• Wide-open transmission window at the
beginning• From cwndcwnd_ += 1_ += 1 To cwndcwnd_ = MAXWIN__ = MAXWIN_
TCP Jump Start – Step 1
TclObject
NsObject
Connector Classifier
Delay AddrClassifierAgent McastClasifierQueue Trace
DropTail RED TCP Enq Deq Drop
Reno SACK JS
Handler
Packet Format
header
dataip header
tcp header
rtp header
trace header
cmn header
...
ts_
ptype_
uid_
size_
iface_
New Packet Header
• Create new header structure• Create static class for OTcl linkage (packet.h)• Enable tracing support of new header(trace.cc)• Enable new header in OTcl (tcl/lib/ns-packet.tcl)• This does not apply when you add a new field
into an existing header!
How Packet Header WorksPacket
next_
hdrlen_
bits_ size determinedat compile time
size determinedat compile time
size determinedat compile time
……
hdr_cmn
hdr_ip
hdr_tcp
size determinedat simulatorstartup time
(PacketHeaderManager)
PacketHeader/Common
PacketHeader/IP
PacketHeader/TCP
Agent/Message – Step 1
TclObject
NsObject
Connector Classifier
Delay AddrClassifierAgent McastClasifierQueue Trace
DropTail RED TCP Enq Deq Drop
Reno SACK
Message
Writing ns-2 codes
• Extending ns• In OTcl• In C++• Debugging: OTcl/C++, memory• Pitfalls
Debugging C++ in ns
• C++/OTcl debugging
• Memory debugging• purify• dmalloc
C++/OTcl Debugging
• Usual technique• Break inside command()• Cannot examine states inside OTcl!
• Solution• Execute tcl-debug inside gdb
C++/OTcl Debugging
((gdbgdb) ) call call Tcl::instance().eval(Tcl::instance().eval(““debugdebug 11””))15: 15: lappendlappend auto_path $auto_path $dbg_librarydbg_librarydbg15.3> wdbg15.3> w*0: application*0: application15: 15: lappendlappend auto_path $auto_path $dbg_librarydbg_library
dbg15.4> Simulator info instancesdbg15.4> Simulator info instances_o1_o1dbg15.5> _o1 nowdbg15.5> _o1 now00dbg15.6> # and other fun stuffdbg15.6> # and other fun stuffdbg15.7> dbg15.7> cc((gdbgdb) where) where#0 0x102218 in write()#0 0x102218 in write()............
Memory Debugging in ns
• Purify• Set PURIFY macro in ns Makefile• Usually, put -colloctor=<ld_path>
• Gray Watson’s dmalloc library• http://www.dmalloc.com• make distclean• ./configure --with-dmalloc=<dmalloc_path>• Analyze results: dmalloc_summarize
dmalloc: Usage
• Turn on dmalloc• alias dmalloc ’eval ‘\dmalloc –C \!*`’• dmalloc -l log low
• dmalloc_summarize ns < logfile• ns must be in current directory• Itemize how much memory is allocated in
each function
Pitfalls
• Scalability vs flexibility• Or, how to write scalable simulation?
• Memory conservation tips• Memory leaks
Scalability vs Flexibility
• It’s tempting to write all-OTcl simulation• Benefit: quick prototyping• Cost: memory + runtime
• Solution• Control the granularity of your split object by
migrating methods from OTcl to C++
THE Merit of OTcl
Program size, complexity
C/C++ OTcl
• Smoothly adjust the granularity of scripting to balance extensibility and performance
• With complete compatibility with existing simulation scripts
high low
split objects
Object Granularity Tips
• Functionality• Per-packet processing C++• Hooks, frequently changing code OTcl
• Data management• Complex/large data structure C++• One-time configuration variables OTcl
Memory usage
Simulator 268KBUnicast node 2KBMulticast node 6KBDuplex link 9KBPacket 2KB
Memory Conservation Tips
• Remove unused packet headers• Avoid tracetrace--allall
• Use arrays for a sequence of variables• Instead of n$in$i, say n($i)n($i)
• Avoid OTcl temporary variables• temp=A; B=temp
• Use dynamic binding•• delay_bind()delay_bind() instead of bind()bind()• See object.{h,cc}
• Use different routing strategies• Computing routing tables dominate the simulation setup time
• Run on FreeBSD• use less memory for malloc()
Memory Leaks
• Purify or dmalloc, but be careful about split objects:•• for {set i 0} {$i < 500} {for {set i 0} {$i < 500} {incrincr i} {i} {
•• set a [new set a [new RandomVariableRandomVariable/Constant]/Constant]
•• }}
• It leaks memory, but can’t be detected!• Solution
• Explicitly delete EVERY split object that was new-ed
Final Word
• My extended ns dumps OTcl scripts!• Find the last 10-20 lines of the dump• Is the error related to “_o*** cmd …” ?
• Check your command()• Otherwise, check the otcl script pointed by the
error message
Questions?
Outline
• An introduction to ns-2• What is ns-2• Fundamentals• Writing ns-2 codes• Traces support and visualization• Wireless support• Emulation• Related work
ns nam Interface
• Color• Node manipulation• Link manipulation• Topology layout• Protocol state• Misc
nam Interface: Color
• Color mapping$ns color 40 red$ns color 40 red
$ns color 41 blue$ns color 41 blue
$ns color 42 chocolate$ns color 42 chocolate
• Color ↔ flow id association$tcp0 set fid_ 40$tcp0 set fid_ 40 ;# red packets;# red packets
$tcp1 set fid_ 41$tcp1 set fid_ 41 ;# blue packets;# blue packets
nam Interface: Nodes• Color
$node color red$node color red
• Shape (can’t be changed after sim starts)$node shape box$node shape box ;# circle, box, hexagon;# circle, box, hexagon
• Marks (concentric “shapes”)$ns at 1.0 $ns at 1.0 ““$n0 add$n0 add--mark m0 blue boxmark m0 blue box””$ns at 2.0 $ns at 2.0 ““$n0 delete$n0 delete--mark m0mark m0””
• Label (single string)$ns at 1.1 $ns at 1.1 ““$n0 label $n0 label \\””web cache 0web cache 0\\””””$node label$node label--at upat up$node label$node label--color bluecolor blue
nam Interfaces: Links
• Color$ns duplex$ns duplex--linklink--op $n0 $n1 color "green"op $n0 $n1 color "green"
• Label$ns duplex$ns duplex--linklink--op $n0 $n1 label "op $n0 $n1 label "abcedabced““$ns duplex$ns duplex--linklink--op $n1 $n2 labelop $n1 $n2 label--color bluecolor blue$ns duplex$ns duplex--linklink--op $n1 $n2 labelop $n1 $n2 label--at downat down
• Queue position$ns duplex-link-op queuePos right
• Dynamics (automatically handled)$ns $ns rtmodelrtmodel Deterministic {2.0 0.9 0.1} $n0 $n1Deterministic {2.0 0.9 0.1} $n0 $n1
• Asymmetric links not allowed
nam Interface: Topology Layout
• “Manual” layout: specify everything$ns duplex$ns duplex--linklink--op $n(0) $n(1) orient rightop $n(0) $n(1) orient right
$ns duplex$ns duplex--linklink--op $n(1) $n(2) orient rightop $n(1) $n(2) orient right
$ns duplex$ns duplex--linklink--op $n(2) $n(3) orient rightop $n(2) $n(3) orient right
$ns duplex$ns duplex--linklink--op $n(3) $n(4) orient 60degop $n(3) $n(4) orient 60deg
• If anything missing automatic layout
nam Interface: Misc
• Packet color$ns color $n blue$ns color $n blue$agent set fid_ $n$agent set fid_ $n
• Annotation• Add textual explanation to your simulation$ns at 3.5 "$ns trace$ns at 3.5 "$ns trace--annotate annotate \\““packet droppacket drop\\""““
• Control playback $ns at 0.0 "$ns set$ns at 0.0 "$ns set--animationanimation--rate 0.1ms"rate 0.1ms"
The nam user interface
Summary of nam
• Turn on nam tracing in your Tcl script• As easy as turning on normal tracing
•$ns namtrace $file
• Specify color/shape/label of node/link• $ns duplex-link-op $node1 $node2 orient left
• Execute nam• exec nam $filename
A live demoNam.exe
namgraph
• Display a graph showing when packets are received/dropped.
• Enabling namgraph• Run the namfilter script on your nam trace file:
exec tclsh /path/to/namfilter.tcl out.nam
namgraph
The nam editor
• Create simple scenarios graphically• Good for those who don’t want to learn Tcl,
but only a limited subset of ns is currently available
The nam editor
Topology generator
• Inet• GT-ITM• TIERS• BRITE
Summary
http://www.isi.edu/nsnam/ns/ns-topogen.html
Packages Graphs Edge Method
NTG n-level probabilistic
RTG Flat random Waxman
GT-ITM Flat random, n-level, Transit-stub various
TIERS 3-level spanning tree
Outline• An introduction to ns-2
• What is ns-2• Fundamentals• Writing ns-2 codes• Traces support and visualization• Wireless support• Emulation• Related work
Wireless support in ns-2
• Introduction• Wireless basics• Wireless internals
• Ad hoc routing• Mobile IP• Satellite networking• Directed diffusion
Contributions to wireless in ns• Original wireless model in ns contributed
by CMU’s Monarch group• Other major contributions from UCB, Sun
microsystems, univ of cincinnati, ISI etc• Other contributed models (not integrated)
in wireless ns includes Blueware, BlueHoc, Mobiwan, GPRS, CIMS etc
Wireless model
• Mobilenode at core of mobility model• Mobilenodes can move in a given topology,
receive/transmit signals from/to wireless channels
• Wireless network stack consists of LL, ARP, MAC, IFQ etc
• Allows simulations of multi-hop ad hoc networks, wireless LANs, sensor networks etc
Wireless Examplefor ad hoc routing
• Scenario• 3 mobile nodes• moving within 670mX670m flat topology• using DSDV ad hoc routing protocol• Random Waypoint mobility model• TCP and CBR traffic
• ns-2/tcl/ex/wireless-demo-csci694.tcl
An Example – Step 1
# Define Global Variables# create simulatorset ns [new Simulator]
# create a flat topology in a 670m x 670m areaset topo [new Topography] $topo load_flatgrid 670 670
An Example – Step 2
# Define standard ns/nam trace
# ns trace
set tracefd [open demo.tr w]
$ns trace-all $tracefd
# nam trace
set namtrace [open demo.nam w]
$ns namtrace-all-wireless $namtrace 670 670
GOD (General Operations Director)
• An omniscient observer• Stores smallest number of hops from one
node to another• Optimal case to compare routing protocol
performance• Automatically generated by scenario file• set god [create-god <no of mnodes>]• $god set-dist <from> <to> <#hops>
Example –Step 3
• Create Godset god [create-god 3]$ns at 900.00 “$god set-dist 2 3 1”
An Example – Step 4
# Define how a mobile node is configured$ns node-config \
-adhocRouting DSDV \-llType LL \-macType Mac/802_11 \-ifqLen 50 \-ifqType Queue/DropTail/PriQueue \-antType Antenna/OmniAntenna \-propType Propagation/TwoRayGround \-phyType Phy/WirelessPhy \-channelType Channel/WirelessChannel \-topoInstance $topo-agentTrace ON \-routerTrace OFF \-macTrace OFF
An Example – Step 5# Next create a mobile node, attach it to the channel set node(0) [$ns node]# disable random motion$node(0) random-motion 0
# Use “for” loop to create 3 nodes:
for {set i < 0} {$i < 3} {incr i} {
set node($i) [$ns node]
$node($i) random-motion 0
}
Mobilenode Movement
• Node position defined in a 3-D model• However z axis not used
$node set X_ <x1>$node set Y_ <y1>$node set Z_ <z1>$node at $time setdest <x2> <y2> <speed>
• Node movement may be logged
Scenario Generator: Movement• Mobile Movement Generator
setdestsetdest --n <num_of_nodes> n <num_of_nodes> --p p pausetimepausetime --s s <<maxspeedmaxspeed> > --t <t <simtimesimtime> > --x <x <maxxmaxx> > --y y <<maxymaxy>>
Source: nsns--2/indep2/indep--utils/cmuutils/cmu--scenscen--gen/setdest/gen/setdest/
• Random movement• $node random-motion 1
•• $node start$node start
A Movement File$node_(2) set Z_ 0.000000000000$node_(2) set Y_ 199.373306816804$node_(2) set X_ 591.256560093833$node_(1) set Z_ 0.000000000000$node_(1) set Y_ 345.357731779204$node_(1) set X_ 257.046298323157$node_(0) set Z_ 0.000000000000$node_(0) set Y_ 239.438009831261$node_(0) set X_ 83.364418416244$ns_ at 50.000000000000 "$node_(2) setdest 369.463244915743
170.519203111152 3.371785899154"$ns_ at 51.000000000000 "$node_(1) setdest 221.826585497093
80.855495003839 14.909259208114"$ns_ at 33.000000000000 "$node_(0) setdest 89.663708107313
283.494644426442 19.153832288917"
Scenario Generator: Traffic• Generating traffic pattern files
• CBR/TCP trafficns ns cbrgen.tclcbrgen.tcl [[--type type cbr|tcpcbr|tcp] [] [--nnnn nodes] [nodes] [--seed seed seed] [seed] [--mc connections] [mc connections] [--rate rate]rate rate]
•• CBR trafficCBR trafficns ns cbrgen.tclcbrgen.tcl ––type type cbrcbr ––nnnn 20 20 ––seed 1 seed 1 ––mc 8 mc 8 --rate 4rate 4
• TCP trafficns ns cbrgen.tclcbrgen.tcl ––type type tcptcp --nnnn 15 15 --seed 0 seed 0 ––mc 6mc 6
• Source: nsns--2/indep2/indep--utils/cmuutils/cmu--scenscen--gen/gen/
A Traffic Scenarioset udp_(0) [new Agent/UDP]$ns_ attach-agent $node_(0) $udp_(0)set null_(0) [new Agent/Null]$ns_ attach-agent $node_(2) $null_(0)set cbr_(0) [new Application/Traffic/CBR]$cbr_(0) set packetSize_ 512$cbr_(0) set interval_ 4.0$cbr_(0) set random_ 1$cbr_(0) set maxpkts_ 10000$cbr_(0) attach-agent $udp_(0)$ns_ connect $udp_(0) $null_(0)$ns_ at 127.93667922166023 "$cbr_(0) start"…….
An Example – Step 6
# Define node movement model source <movement-scenario-files>
# Define traffic modelsource <traffic-scenario-files>
An Example – Step 7
# Define node initial position in namfor {set i 0} {$i < 3 } { incr i} {
$ns initial_node_position $node($i) 20}
# Tell ns/nam the simulation stop time $ns at 200.0 “$ns nam-end-wireless 200.0”$ns at 200.0 “$ns halt”
# Start your simulation $ns run
Energy Extension
• Node is energy-aware• Define node by adding new options:$ns_ node-config \
–energyModel EnergyModel-initialEnergy 100.0-txPower 0.6-rxPower 0.2
nam Visualization
• Use nam to visualize:• Mobile node position• Mobile node moving direction and speed• Energy consumption at nodes (color keyed)
nam Visualization
• Replace$ns $ns namtracenamtrace--all $all $fdfd
with$ns $ns namtracenamtrace--allall--wireless $wireless $fdfd
At the end of simulation, do$ns $ns namnam--endend--wireless [$ns now]wireless [$ns now]
Wireless support in ns-2
• Introduction• Wireless basics• Wireless internals
• Ad hoc routing• Mobile IP• Satellite networking• Directed diffusion
Wireless Internals
• Mobilenode• Basic node that has address and port de-
muxes, routing agent etc• Stack of network components consisting of LL,
MAC, NetIF radio-model etc• Wireless channel
Portrait of A Mobile Node
Node
ARP
Propagation and antenna models
MobileNode
LL
MAC
PHY
LL
CHANNEL
LL
MAC
PHY
Classifier: Forwarding
Agent: Protocol Entity
Node Entry
LL: Link layer object
IFQ: Interface queue
MAC: Mac object
PHY: Net interface
protocolagent
routingagent
addrclassifier
portclassifier
255
IFQIFQ
defaulttarget_
Radio propagation/antenna models
Prop/ant
Mobile Node : Components
• Classifiers• defaulttarget_ points to routing agent object• 255 is the port id assigned for rtagent_
• Routing agent• May be ad hoc routing protocol like AODV,
DSDV or directed diffusion
Mobile Node: Components
• Link Layer• Same as LAN, but with a separate ARP module• Sends queries to ARP
• ARP• Resolves IP address to hardware (MAC) address• Broadcasts ARP query
• Interface queue• Gives priority to routing protocol packets• Has packet filtering capacity
Mobile Node: Components
• MAC• 802.11
• IEEE RTS/CTS/DATA/ACK for unicast• Sends DATA directly for broadcast
• SMAC (for sensor network)• Network interface (PHY)
• Used by mobilenode to access channel• Stamps outgoing pkts with meta-data• Interface with radio/antenna models
Mobile Node: Components• Radio Propagation Model
• Friss-space model – attenuation at near distance (1/r2)
• Two-ray ground reflection model for far distance (1/r4)
• Shadowing model -probabilistic
• Antenna• Omni-directional, unity-gain
Wireless Channel
• Duplicate packets to all mobile nodes attached to the channel except the sender
• It is the receiver’s responsibility to decide if it will accept the packet• Collision is handled at individual receiver• O(N2) messages grid keeper, reference-
copying etc
Grid-keeper: An Optimization
Mobile Node: Misc.
• Energy consumption model for sensor networks
• Visualization of node movement, reachability, and energy
• Validation test suites
Wireless Trace Support
• Original cmu trace format• A separate wireless trace format
developed later at ISI• Current ongoing effort to have ONE format
to combine all wired and wireless formats
Ad Hoc Routing
• Four routing protocols currently supported:• DSDV
• Contributed by CMU• DSR
• Contributed by CMU• AODV
• Recently updated version from univ. of cincinnati;• TORA
• Contributed by CMU• Examples under tcl/test/test-suite-wireless- { lan-newnode.tcl, lan-aodv.tcl, lan-tora.tcl }
A Brief on MobileIP Support
• Developed by Sun• Require a different Node structure than MobileNode• Originally implemented for wired nodes
• Wired-cmu-wireless extension• Originally CMU wireless model only supports ad-hoc
and wireless LAN• Base-stations, support hier-rtg
• Standard MobileIP• Home Agent, Foreign Agent, MobileHosts
• Example•• Under Under tcl/test/testtcl/test/test--suitesuite--wirelesswireless--lanlan--newnode.tclnewnode.tcl (tests: DSDV(tests: DSDV--wiredwired--cumcum--wireless and wireless and DSDVDSDV--wirelesswireless--mipmip))
A Brief on Satellite Networking
• Developed by Tom Henderson (UCB)• Supported models
• Geostationary satellites: bent-pipe and processing-payload
• Low-Earth-Orbit satellites• Example: tcltcl/ex/sat/ex/sat--*.*.tcltcl and and tcl/test/testtcl/test/test--suitesuite--satellite.tclsatellite.tcl
Simulate sensor network with ns-2
• Currently support• Routing
• Direct diffusion• MAC
• SMAC
Outline• An introduction to ns-2
• What is ns-2• Fundamentals• Writing ns-2 codes• Traces support and visualization• Wireless support• Emulation• Related work
What is Emulation ?
• Ability to introduce the simulator into a live network
• Application:• Allows testing real-world implementations• Allows testing simulated protocols
• Requirements: • Scheduler support • Packet capture and generation capabilities
Emulation in ns-2
Read packets Write packets
ns
Network
Scheduler
• ns operates in virtual time using event-driven simulation
• Real-time scheduler • Does not advance the virtual clock to next
event• Dispatches event at real-time
Emulation Objects
• Interface between ns and network traffic
• Network Objects• Access to live network via• BPF and raw sockets
• Tap Objects• Conversion between ns
and• network packet formats
Capture: BPF
ns
Inject: Raw socket
network to ns
ns to network
Modes of Operation
• Packet conversion leads to two modes of operation
• Opaque Mode• Network packet fields are not interpreted
• Protocol Mode• Network packet is interpreted
• TTL values reflect hop count in simulator• Network packet fields are generated
• Ping responder, TCP application
Opaque Mode
• Network packet is passed unmodified through simulator
Network Packet
SourceDestination
Size
Data
Ns packet contains a pointer to the network packet
SourceDestination
Size
Extern
Read packets Write packets
ns
Network
Protocol Mode
• Network packet fields are generated by the simulator
DataThe ns packet
header is mapped onto the network packet header and visa
versa .
Send/receive packets from application
ns
TCP Agent
Network
Host A
TCPApplication
Host B
Send/receive packets from
ns
Network Packet
SourceDestination
Size
SourceDestination
Size
Applications
• Opaque Mode• Cross-traffic interaction leading to drop, delay
and re-ordering of packets • End to End application testing
• Protocol Mode• Protocol and conformance testing• Evaluate effect of DDoS attacks • Wireless networks
Example: Setup
Goal: Make a ns TCP agent interact with a TCP server
TCP server
• Disable IP forwarding• sysctl –w
net.inet.ip.forwarding=0
• Assign 10.0.0.1 and 6000 to TCP agent
• Add route to dummy IP address
• route add 10.0.0.1 192.168.1.1
• Disable IP redirects • sysctl –w net.inet.ip.redirect=0
A 192.168.1.1 B 192.168.1.2 port 8000
Switch
nse
Example Scriptset ns [new Simulator]$ns use-scheduler RealTime
set entry_node [$ns node]set tcp_node [$ns node]
$ns duplex-link $entry_node \$tcp_node 10Mb 1ms DropTail
set tcp [new Agent/TCP/FullTcp]$ns attach-agent $tcp_node $tcp
Activate ns and Change to real-time scheduler
Create topology
Create TCP Agent
TCP Agent
tcp_node entry_node
RawSocket
BPFTCPTap
TCPTap
Example Scriptset bpf [new Network/Pcap/Live] set dev [$bpf open readonly eth0]$bpf filter "src 192.168.1.2 and src port 8000 \
and dst 10.0.0.1 and dst port 6000“set capture_tap [new Agent/TCPTap]$capture_tap network $bpf$ns attach-agent $entry_node $capture_tap$ns simplex-connect $capture_tap $tcp
set rawsocket [new Network/IP] $rawsocket open writeonlyset inject_tap [new Agent/TCPTap] $inject_tap advertised-window 512$inject_tap extipaddr “192.168.1.2" $inject_tap extport 8000$inject_tap network $rawsocket$ns attach-agent $entry_node $inject_tap $ns simplex-connect $tcp $inject_tap
TCP Agent
tcp_node
entry_node
RawSocket
CaptureTap
BPF
InjectTap
Example Script$ns at 0.01 "$tcp advance 1"$ns at 20.0 “exit 0"$ns run
start nse
TCP Server(8000)
Switch
TCP Agent
BPF Raw Socket
B 192.168.1.2A 192.168.1.1
Further Information
• http://www.isi.edu/nsnam/ns/ns-emulation.html• Scripts ~ns/emulate
• Opaque Mode:• em.tcl
• Protocol Mode• thrutcp.tcl• pingdemo.tcl• tcpemu.tcl
• Kevin Fall, Network Emulation in the Vint/NS Simulator, ISCC July 1999
Ns-2 related work
• Other simulators• Researching uses ns-2• Using ns-2 for education
Other simulators
• GloMoSim• Developed by UCLA• Based on Parsec• Good support for wireless simulation
• SSFNET• Java-based (with some C++ components)• Use DML (Domain Modeling Language) for model configuration
• OPNET and QualNet• Commercial software• Good support for all layers
• PDNS (parallel/distributed ns)• Developed by Georgia Tech• Can distribute a simulation on several 8-16 workstations • Aim to support very large simulation (memory & CPU)
• JavaSim• Another Java-based simulator
Research using ns-2
• Routing• MIT Click Router• Zone routing protocol
• Wireless• Mobility generator• MIPv6• Bluetooth• 802.11 PSM• Cellular IP • Hierarchical Mobile IP • GPRS• UMTS
Research using ns-2..
• Generator• Web traffic generators• MPEG• Several topology generators
• Others• MPLS• WFQ, CSFQ• RSVP• RIO• BLUE• TCP westwood• SCTP• Multistate error model
Using ns-2 for education
• Ns-2 scripts/nam traces repository• http://www.isi.edu/nsnam/repository/index.
html• ~ns-2/tcl/ex• ~nam/ex ~nam/edu• Some ns scripts and nam animations
can be used in widely-used textbooks• http://www.isi.edu/nsnam/ns/edu/index.html