Upload
nguyen-viet-ha
View
29
Download
0
Tags:
Embed Size (px)
Citation preview
Outline• An introduction to ns-2
• What is ns-2• Fundamentals• writing ns-2 codes• Wireless support• Traces support and visualization• Emulation• Related work
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
Validation test
old ns-2 test.tcl Standard output
new ns-2That contains Your changes
test.tcl new output
If standard output ≠ new output THEN something is broken
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
Example: Agent/Message
n0 n1
n4
n5
n2
n3
128Kb, 50ms
10Mb, 1ms 10Mb, 1ms
C Ccrosstraffic
S Rmessage agent
Agent/Message
• An UDP agent (without UDP header)• Up to 64 bytes user message• Good for fast prototyping a simple idea• Usage requires extending ns functionality
SS RR
pkt: 64 bytesof arbitrary string
Receiver-sideprocessing
Agent
• A protocol endpoint/enity• Provide
• a local and destination address (like an IP-layer sender)• Functions to generate or fill in packet fields
• To create a new agent• Decide its inheritance structure• Create recv function (and timeout if necessary) to process
the packets• Define OTcl linkage if necessary• Create new header if necessary
Exercise
• Define a new class “Sender” and a new class “Receiver” which are based on class Agent/Message
• Sender• Send a message to the Receiver every 0.1 sec• Message contains its address and a sequence number
• Receiver• Receive message from the Sender• Acknowledge the receive message to the sender• The acknowledgement contains its address and the
sequence number of received message• How would you implement Ping with Agent/Message?
Agent/Message: Step 1
• Define senderclass Sender class Sender ––superclasssuperclass Agent/MessageAgent/Message
# Message format: # Message format: ““AddrAddr Op Op SeqNoSeqNo””
Sender Sender instprocinstproc sendsend--next {} {next {} {
$self $self instvarinstvar seqseq_ _ agent_addragent_addr__
$self send $self send ““$$agent_addragent_addr_ send $_ send $seqseq__””
incrincr seqseq__
global nsglobal ns
$ns at [$ns at [exprexpr [$ns now]+0.1] "$self send[$ns now]+0.1] "$self send--next"next"
}}
Agent/Message: Step 2
• Define sender packet processing
Sender Sender instprocinstproc recvrecv msgmsg {{
$self $self instvarinstvar agent_addragent_addr__
set set sdrsdr [[lindexlindex $$msgmsg 0]0]
set set seqseq [[lindexlindex $$msgmsg 2]2]
puts "Sender gets puts "Sender gets ackack $$seqseq from $from $sdrsdr""
}}
Agent/Message: Step 3
• Define receiver packet processing
Class Receiver Class Receiver ––superclasssuperclass Agent/MessageAgent/Message
Receiver Receiver instprocinstproc recvrecv msgmsg {{
$self $self instvarinstvar agent_addragent_addr__
set set sdrsdr [[lindexlindex $$msgmsg 0]0]
set set seqseq [[lindexlindex $$msgmsg 2]2]
puts puts ““Receiver gets Receiver gets seqseq $$seqseq from $from $sdrsdr””
$self send $self send ““$$addraddr_ _ ackack $$seqseq””}}
Agent/Message: Step 4
• Scheduler and tracing
# Create scheduler# Create scheduler
set ns [new Simulator]set ns [new Simulator]
# Turn on Tracing# Turn on Tracing
set set fdfd [new [new ““message.trmessage.tr”” w]w]
$ns trace$ns trace--all $all $fdfd
Agent/Message: Step 5
• Topologyfor {set i 0} {$i < 6} {for {set i 0} {$i < 6} {incrincr i} {i} {
set n($i) [$ns node]set n($i) [$ns node]}}$ns duplex$ns duplex--link $n(0) $n(1) 128kb 50ms link $n(0) $n(1) 128kb 50ms DropTailDropTail$ns duplex$ns duplex--link $n(1) $n(4) 10Mb 1ms link $n(1) $n(4) 10Mb 1ms DropTailDropTail$ns duplex$ns duplex--link $n(1) $n(5) 10Mb 1ms link $n(1) $n(5) 10Mb 1ms DropTailDropTail$ns duplex$ns duplex--link $n(0) $n(2) 10Mb 1ms link $n(0) $n(2) 10Mb 1ms DropTailDropTail$ns duplex$ns duplex--link $n(0) $n(3) 10Mb 1ms link $n(0) $n(3) 10Mb 1ms DropTailDropTail
$ns queue$ns queue--limit $n(0) $n(1) 5limit $n(0) $n(1) 5$ns queue$ns queue--limit $n(1) $n(0) 5limit $n(1) $n(0) 5
Agent/Message: Step 6
• Routing
# Packet loss produced by # Packet loss produced by queueingqueueing
# Routing protocol: let# Routing protocol: let’’s run distance vectors run distance vector
$ns $ns rtprotortproto DVDV
Agent/Message: Step 7
• Cross trafficset udp0 [new Agent/UDP]set udp0 [new Agent/UDP]$ns attach$ns attach--agent $n(2) $udp0agent $n(2) $udp0set null0 [new Agent/NULL]set null0 [new Agent/NULL]$ns attach$ns attach--agent $n(4) $null0agent $n(4) $null0$ns connect $udp0 $null0$ns connect $udp0 $null0
set exp0 [new Application/Traffic/Exponential]set exp0 [new Application/Traffic/Exponential]$exp0 set rate_ 128k$exp0 set rate_ 128k$exp0 attach$exp0 attach--agent $udp0agent $udp0$ns at 1.0 $ns at 1.0 ““$exp0 start$exp0 start””
Agent/Message: Step 8• Message agents
set set sdrsdr [new Sender][new Sender]$$sdrsdr set set seqseq_ 0_ 0$$sdrsdr set set packetSizepacketSize_ 1000_ 1000
set set rcvrrcvr [new Receiver][new Receiver]$$rcvrrcvr set set packetSizepacketSize_ 40_ 40
$ns attach$ns attach--agent $n(3) $agent $n(3) $sdrsdr$ns attach$ns attach--agent $n(5) $agent $n(5) $rcvrrcvr$ns connect $$ns connect $sdrsdr $$rcvrrcvr$ns at 1.1 $ns at 1.1 ““$$sdrsdr sendsend--nextnext””
Agent/Message: Step 9
• End-of-simulation wrapper (as usual)
$ns at 2.0 finish$ns at 2.0 finish
proc finish {} {proc finish {} {
global ns global ns fdfd
$ns flush$ns flush--tracetrace
close $close $fdfd
exit 0exit 0
}}
$ns run$ns run
Agent/Message: Result
• Example output> ./ns > ./ns msg.tclmsg.tclReceiver gets Receiver gets seqseq 0 from 30 from 3Sender gets Sender gets ackack 0 from 50 from 5Receiver gets Receiver gets seqseq 1 from 31 from 3Sender gets Sender gets ackack 1 from 51 from 5Receiver gets Receiver gets seqseq 2 from 32 from 3Sender gets Sender gets ackack 2 from 52 from 5Receiver gets Receiver gets seqseq 3 from 33 from 3Sender gets Sender gets ackack 3 from 53 from 5Receiver gets Receiver gets seqseq 4 from 34 from 3Sender gets Sender gets ackack 4 from 54 from 5Receiver gets Receiver gets seqseq 5 from 35 from 3
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
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_
•• Useful for deep space communication Useful for deep space communication
TCP Jump Start – Decide position in class hierarchy
TclObject
NsObject
Connector Classifier
Delay AddrClassifierAgent McastClasifierQueue Trace
DropTail RED TCP Enq Deq Drop
Reno SACK JS
Handler
TCP Jump Start – Create C++ class
• New file: tcp-js.h
class class JSTCPAgentJSTCPAgent : public : public TcpAgentTcpAgent {{
public:public:
virtual void set_initial_window() {virtual void set_initial_window() {
cwndcwnd_ = MAXWIN_;_ = MAXWIN_;
}}
private:private:
intint MAXWIN_;MAXWIN_;
};};
TCP Jump Start – Define OTcllinkage
• New file: tcp-js.ccstatic JSTcpClass : public TclClass {public:
JSTcpClass() : TclClass("Agent/TCP/JS") {}TclObject* create(int, const char*const*) {
return (new JSTcpAgent());}
};JSTcpAgent::JSTcpAgent() {
bind(“MAXWIN_”, MAXWIN_);}
TCP Jump Start – Build
• Create an instance of jump-start TCP in your tcl script tcp-js.tcl
• Set MAXWIN_ value in tcl• Add tcp-js.o in Makefile.in• Re-configure, make depend and recompile• Run yr tcl script tcp-js.tcl
Packet Format
header
dataip header
tcp header
rtp header
trace header
cmn header
...
ts_
ptype_
uid_
size_
iface_
remove-all-packet-headers ;# removes all except commonadd-packet-header IP Message ;# hdrs reqd for cbr traffic
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
Example: Agent/Message
• New packet header for 64-byte message• New transport agent to process this new
header
New Packet Header – Step 1
• Create header structurestructstruct hdr_msghdr_msg {{
char msg_[64];char msg_[64];static static intint offset_;offset_;inline static inline static intint& offset() { return offset_; }& offset() { return offset_; }inline static inline static hdr_msghdr_msg* access(Packet* p) {* access(Packet* p) {return (return (hdr_msghdr_msg*) p*) p-->access(offset_);>access(offset_);
}}/* per/* per--field member functions */field member functions */char* char* msgmsg() { return (() { return (msgmsg_); }_); }intint maxmsgmaxmsg() { return (() { return (sizeof(msgsizeof(msg_)); }_)); }
};};
New Packet Header – Step 2
• Otcl linkage: PacketHeader/Messagestatic class static class MessageHeaderClassMessageHeaderClass : :
public public PacketHeaderClassPacketHeaderClass {{public:public:MessageHeaderClassMessageHeaderClass() : () : PacketHeaderClass("PacketHeaderClass("PacketHeaderPacketHeader/Message/Message",",
sizeof(hdr_msgsizeof(hdr_msg)) {)) {bind_offset(&hdr_msg::offsetbind_offset(&hdr_msg::offset_);_);
}}} } class_msghdrclass_msghdr;;
New Packet Header – Step 3
• Enable tracing (packet.h):enumenum packet_t {packet_t {
PT_TCP,PT_TCP,……,,PT_MESSAGEPT_MESSAGE,,PT_NTYPE // This MUST be the LAST onePT_NTYPE // This MUST be the LAST one
};};class p_info {class p_info {
…………name_[PT_MESSAGE] = name_[PT_MESSAGE] = ““messagemessage””;;name_[PT_NTYPE]= "undefined";name_[PT_NTYPE]= "undefined";
…………};};
New Packet Header – Step 4
• Register new header (tcl/lib/ns-packet.tcl)
foreachforeach protprot {{
{ Common { Common off_cmnoff_cmn_ }_ }
……
{ { Message Message off_msgoff_msg__ }}
}}
addadd--packetpacket--header $header $protprot
Packet Header: Caution
• Some old code, e.g.:RtpAgent::RtpAgentRtpAgent::RtpAgent() {() {
…………
bind(bind(““off_rtpoff_rtp__””, &, &off_rtpoff_rtp););
}}
…………
hdr_rtphdr_rtp* * rhrh = (= (hdr_rtphdr_rtp*)p*)p-->>access(off_rtpaccess(off_rtp_);_);
• Don’t follow this example!
Agent/Message – Step 1
TclObject
NsObject
Connector Classifier
Delay AddrClassifierAgent McastClasifierQueue Trace
DropTail RED TCP Enq Deq Drop
Reno SACK
Message
Agent/Message – Step 2
• C++ class definition// Standard split object declaration// Standard split object declaration
static static ……
class class MessageAgentMessageAgent : public Agent {: public Agent {
public:public:
MessageAgentMessageAgent() : Agent(() : Agent(PT_MESSAGEPT_MESSAGE) {}) {}
virtual virtual intint command(intcommand(int argcargc, const char*const* , const char*const* argvargv););
virtual void virtual void recv(Packetrecv(Packet*, Handler*);*, Handler*);
};};
Agent/Message – Step 3• Packet processing: $msgAgent send “data1”
intint MessageAgent::command(intMessageAgent::command(int, const char*const* , const char*const* argvargv)){{
TclTcl& & tcltcl = = Tcl::instanceTcl::instance();();if (strcmp(argv[1], "send") == 0) {if (strcmp(argv[1], "send") == 0) {Packet* Packet* pktpkt = = allocpktallocpkt();();hdr_msghdr_msg* * mhmh = = hdr_msg::access(pkthdr_msg::access(pkt););// We ignore message size check...// We ignore message size check...strcpy(mhstrcpy(mh-->>msgmsg(), argv[2]);(), argv[2]);send(pktsend(pkt, 0);, 0);return (TCL_OK);return (TCL_OK);
}}return (return (Agent::command(argcAgent::command(argc, , argvargv));));
}}
Agent/Message – Step 4• Packet processing: receive
void void MessageAgent::recv(PacketMessageAgent::recv(Packet* * pktpkt, Handler*), Handler*){{
hdr_msghdr_msg* * mhmh = = hdr_msg::access(pkthdr_msg::access(pkt););
// // OTclOTcl callbackcallbackchar wrk[128];char wrk[128];sprintf(wrksprintf(wrk, "%s , "%s recvrecv {%s}", name(), {%s}", name(), mhmh-->>msgmsg());());TclTcl& & tcltcl = = Tcl::instanceTcl::instance();();tcl.eval(wrktcl.eval(wrk););
Packet::free(pktPacket::free(pkt););}}
Debugging C++ in ns
• C++/OTcl debugging
• Memory debugging (memory leak is a common bug)• purify• dmalloc
C++/OTcl Debugging
• Usual technique• Break inside command()• Cannot examine states inside OTcl!
• Solution• Execute tcl-debug inside gdb• http://expect.nist.gov/tcl-debug/tcl-debug.ps.Z
C++/OTcl Debugging
C++ OTcl
debug 1debug 1
debug 1debug 1
OtclOtcl commandcommand
OtclOtcl commandcommand
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
Homework
• Run ns-2 on http://www.isi.edu/nsnam/ns/tutorial/examples/example2.tcl
• Execute dmalloc• Submit the memory profile to TA• Due date: May 30
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 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
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"
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
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
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
Inet topology generator
• from University of Michigan • AS level Internet topology • Create topologies with accurate degree
distributions • Conversion of Inet output to ns-2 format
• inet2ns < inet.topology > ns.topology
GT-ITM• Installation
• Comes with ns-allinone• Require Knuth’s cweb and SGB
• Usage• itm <config_file>
• Three graph models• Flat random: Waxman• n-level hierarchy• Transit-stub
Converters for GT-ITM
• sgb2ns• Convert SGB format to ns config file•• sgb2ns <SGB_file> <sgb2ns <SGB_file> <OTcl_fileOTcl_file>>
•• ts2nsts2ns: output lists of transit and stub nodes• sgb2hier
• Convert transit-stub information into hierarchical addresses
•• sgb2hierns <SGB_file> <sgb2hierns <SGB_file> <OTcl_fileOTcl_file>>
Tiers topology generator• 3-level hierarchy• Conversion of Tiers output to ns-2 format
• an awk script tiers2ns.awk is included in ~ns-2/bin to convert the output of tiers into ns-2 scripts.
BRITE• From Boston University• Supports multiple generation models
• flat AS• flat Router• hierarchical topologies
• Object-oriented design to allow the flexibility to add new topology models
• Can import from Inet, GT-ITM, Skitter,..• Can export to ns-2, JavaSim, SSFNET format• Written in Java and C++• GUI support