Title: Introduction to ns2
1Introduction to ns-2
2Outline
- Part 1 model and simulate Internet traffic
- Part 2 an introduction to ns-2
- What is ns-2
- Fundamentals
- Writing ns-2 codes
- Wireless support
- Traces support and visualization
- Emulation
- Related work
- Part 3 trace-driven network simulation
3What is ns-2
- History
- What does it support
4Ns 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
5Alternatives
- 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
6History of ns-2
- History
- Cornell REAL simulator -1989
- VINT project (UCB, Xerox ,USC/ISI) 1995
- USC/ISI SAMAN/CONSER project 1999
- Size
- 220K lines of codes
- 45 C
- 31 OTcl
- 23 test suite/example/documents
- 400 pages of mannual
- 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 ns-users_at_isi.edu every month
7ns-2 support
- Platform
- FreeBSD, Linux, Solaris, Windows and Mac
- Release
- Periodical release 6 months
- current release ns-2.27, Jan 18, 2004
- Daily snapshot
- Validation
- 100 test suites and 100 examples
8What 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
9Wired 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
10Wireless 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
11Ns Components
- Ns, the simulator itself
- Nam, the network animator
- Visualize ns (or other) output
- Nam editor GUI interface to generate ns scripts
- Pre-processing
- Traffic and topology generators
- Post-processing
- Simple trace analysis, often in Awk, Perl, or Tcl
12Installation
- 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,
13Getting Help
- ns-2 build questions
- http//www.isi.edu/nsnam/ns/ns-build.html
- ns-users_at_isi.edu
- ns-users-request_at_isi.edu
- subscribe ns-users in body
- Archive http//www.isi.edu/nsnam/ns
14Resources
- 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
15Cautions
- Abstraction of the real world is necessary for a
simulator - You must justify the usage of the simulator based
on your research goals
16Question?
17Outline
- Part 1 model and simulate Internet traffic
- Part 2 an introduction to ns-2
- What is ns-2
- Fundamentals
- Writing ns-2 codes
- Wireless support
- Traces support and visualization
- Emulation
- Related work
- Part 3 trace-driven network simulation
18Prerequisite
- Some programming experience of object-oriented
language (such as C, Java)
19Discrete 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 gt
no locking or race conditions to worry about
20Discrete Event Examples
simple queuing model
Consider two nodes on an Ethernet
t1, A enqueues pkt on LAN t1.01, LAN dequeues
pkt and triggers B
t1.0 A sends pkt to NIC As NIC starts carrier
sense t1.005 As NIC concludes cs, starts
tx t1.006 Bs NIC begins reciving pkt t1.01
Bs NIC concludes pkt Bs NIC passes pkt to app
detailed CSMA/CD model
21Ns 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
Network Components
TclCL
Event Scheduler
OTcl
Tcl
C
ns-2
22C 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)
23Control 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
C
OTcl
24Otcl and C The Duality
C
user simulation scripts
C/OTcl split objects
otcl
ns
- OTcl (object variant of Tcl) and C share class
hierarchy - TclCL is glue library that makes it easy to share
functions, variables, etc
25Basic Tcl
- variables
- set x 10
- puts x is x
- functions and expressions
- set y pow x 2
- set y expr xx
- control flow
- if x gt 0 return x else
- return expr -x
- while x gt 0
- puts x
- incr x 1
- procedures
- proc pow x n
- if n 1 return x
- set part pow x expr n-1
- return expr xpart
-
- Also lists, associative arrays, etc.
- gt can use a real programming language to build
network topologies, traffic models, etc.
26Compare Otcl to C
- Object oriented extension of Tcl
- C constructor/destructor gt OTcl init/destroy
method - C this gt OTcl self
- OTcl methods always virtual
- C static variable gt OTcl class variable
- Multiple inheritance is supported
27Basic otcl
- Class 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 Person
- Kid instproc greet
- self instvar age_
- puts age_ years old kid Whats up, dude?
-
- set a new Person 45
- set b new Kid 15
- a greet
- b greet
gt can easily make variations of existing things
(TCP, TCP/Reno)
28Using ns
Problem
Result analysis
Simulation model
Modify ns
Setup/run simulation with ns
29C/OTcl Linkage
30TclObject
- Basic hierarchy in ns for split objects
- Mirrored in both C and OTcl
- Example
- set tcp new Agent/TCP
- tcp set packetSize_ 1024
- tcp advanceby 5000
31TclObject Hierarchy and Shadowing
C class hierarchy
OTcl class hierarchy
TclObject
TclObject
Agent
Agent
TcpAgent
Agent/TCP
tcp
_o123
Agent/TCP OTcl shadow object
Agent/TCP C object
32TclObjectbind()
- Link C member variables to OTcl object
variables - C
- TcpAgentTcpAgent()
- bind(window_, wnd_)
-
-
- OTcl
- set tcp new Agent/TCP
- tcp set window_ 200
33TclObjectcommand()
- Implement OTcl methods in C
- Trap point OTcl method cmd
- Access the shadow object
- Send all arguments after cmd call to
TclObjectcommand()
34TclObjectcommand()
OTcl space
no such procedure
tcp send
TclObjectunknown
tcp cmd send
C space
TcpAgentcommand()
match send?
Yes
No
Invoke parent return Agentcommand()
process and return
35TclObjectcommand()
- OTcl
- set tcp new Agent/TCP
- tcp send 10
- C
- int TcpAgentcommand(int argc,
- const charconst argv)
- if (argc 3)
- if (strcmp(argv1, send) 0)
- int newseq atoi(argv2)
-
- return(TCL_OK)
-
-
- return (Agentcommand(argc, argv)
-
36TclObject Creation and Deletion
- Global procedures new, delete
- Example
- set tcp new Agent/TCP
-
- delete tcp
37TclObject Creation and Deletion
invoke parent constructor
OTcl
C
38TclClass
Static class TcpClass public TclClass
public TcpClass() TclClass(Agent/TCP)
TclObject create(int, const charconst)
return (new TcpAgent()) class_tcp
39NsObject
- Other important objects
- NsObject has recv() method
- Connector has target() and drop()
- BiConnector uptarget() downtarget()
- Class hierarchy
- NsObject
- Connector
- PingAgent
- BiConnector
- Mac802_11
40Class Tcl
- Singleton class with a handle to Tcl interpreter
- Tcl tcl Tclinstance()
- 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)
41Class Tcl
- Tcl tcl Tclinstance()
- if (argc 2)
- if (strcmp(argv1, now) 0)
- tcl.resultf(g, clock())
- return TCL_OK
-
- tcl.error(command not found)
- return TCL_ERROR
- else if (argc 3)
- tcl.eval(argv2)
- clock_ atof(tcl.result())
- return TCL_OK
-
42Class 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
charconst argv) -
- int RandomCommandcommand(int argc, const
charconst argv) -
- Tcl tcl Tclinstance()
- if (argc 1)
- sprintf(tcl.buffer(), "u",
Randomrandom()) - tcl.result(tcl.buffer())
-
43Brief 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
44Question?
45Ns programming
- Create the event scheduler
- Turn on tracing
- Create network
- Setup routing
- Insert errors
- Create transport connection
- Create traffic
- Transmit application-level data
46Creating Event Scheduler
- Create event scheduler
- set ns new Simulator
- Schedule events
- ns at lttimegt lteventgt
- lteventgt any legitimate ns/tcl commands
- ns at 5.0 finish
- Start scheduler
- ns run
47Event 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
48Some scheduler-related commands
- Set now ns now
- ns cancel lteventgt
- ns after ltdelaygt lteventgt
- Execute lteventgt after ltdelaygt
- ns dumpq
- Dump all events in the scheduler queue
49Discrete Event Scheduler
time_, uid_, next_, handler_
head_ -gt
head_ -gt
handler_ -gt handle()
insert
time_, uid_, next_, handler_
50Hello World - Interactive Mode
- 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.tcl
- Hello World!
- swallow 75
- Interactive mode
- swallow 71 ns
- set ns new Simulator
- _o3
- ns at 1 puts \Hello World!\
- 1
- ns at 1.5 exit
- 2
- ns run
- Hello World!
- swallow 72
51Tracing and Monitoring I
- Packet tracing
- On all links ns trace-all open out.tr w
- On one specific link ns trace-queue n0 n1tr
- ltEventgt lttimegt ltfromgt lttogt ltpktgt ltsizegt -- ltfidgt
ltsrcgt ltdstgt ltseqgt ltattrgt - 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
52Tracing 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 monitor
- set fmon ns_ makeflowmon Fid
- ns_ attach-fmon slink fmon
- fmon set pdrops_
53Tracing and Monitoring III
- Visualize trace in nam
- ns namtrace-all open test.nam w
- ns namtrace-queue n0 n1
- Variable tracing in nam
- Agent/TCP set nam_tracevar_ true
- tcp tracevar srtt_
- tcp tracevar cwnd_
- Monitor agent variables in nam
- ns add-agent-trace tcp tcp
- ns monitor-agent-trace tcp
- srm0 tracevar cwnd_
-
- ns delete-agent-trace tcp
54Ns Internals
- Tcl commands translates into
- series of object creation
- plumbing of these objects
55Creating Network
- Nodes
- set n0 ns node
- set n1 ns node
- Links and queuing
- ns ltlink_typegt n0 n1 ltbandwidthgt ltdelaygt
ltqueue_typegt - ltlink_typegt duplex-link, simplex-link
- ltqueue_typegt DropTail, RED, CBQ, FQ, SFQ, DRR,
diffserv RED queues
56Network Topology Node
Unicast Node
0
0
1
Set ns_ new Simulator multicast on Set n1 ns_
node
set n0 ns_ node
57Node 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
58Hierarchical Node
n2
Address classifier
To Port demux
Node entry
Level 3
Level 2
Level 1
ns_ node-config addressing hier
59Classifiers
- 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
60Network Topology Link
ns_ duplex-link n0 n1 5Mb 2ms drop-tail
61Connectors
- 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
queues 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
62Creating Network LAN
- ns make-lan ltnode_listgt ltbandwidthgt ltdelaygt
ltll_typegt ltifq_typegt ltmac_typegt ltchannel_typegt - ltll_typegt LL
- ltifq_typegt Queue/DropTail,
- ltmac_typegt MAC/802_3
- ltchannel_typegt Channel
63Setup Routing
- Unicast
- ns rtproto lttypegt
- lttypegt Static, Session, DV, cost, multi-path
- Multicast
- ns multicast (right after new Simulator)
- ns mrtproto lttypegt
- lttypegt CtrMcast, DM, ST, BST
- Other types of routing supported source routing,
hierarchical routing
64Routing..
65..Routing
Link n0-n1
66Class RouteLogic
- Route configuration
- rtproto -gt configure -gt compute-routes
- Query nexthop
- ns get-routelogic lookup n1 2
- Recompute route on topology change
- ns get-routelogic notify
67Inserting Errors
- Creating Error Module
- set 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
68Network Dynamics
- Link failures
- Hooks in routing module to reflect routing
changes - Four models
- ns rtmodel Trace ltconfig_filegt n0 n1
- ns rtmodel Exponential ltparamsgt n0 n1
- ns rtmodel Deterministic ltparamsgt n0 n1
- ns rtmodel-at lttimegt updown n0 n1
- Parameter list
- ltstartgt ltup_intervalgt ltdown_intervalgt
ltfinishgt
69Creating Connection and Traffic I
- UDP
- set udp new Agent/UDP
- set null new Agent/Null
- ns attach-agent n0 udp
- ns attach-agent n1 null
- ns connect udp null
- CBR
- set src new Application/Traffic/CBR
- Exponential or Pareto on-off
- set src new Application/Traffic/Exponential
- set src new Application/Traffic/Pareto
- src attach-agent udp
70Creating Connection and Traffic II
- TCP
- set tcp new Agent/TCP
- set tcpsink new Agent/TCPSink
- ns attach-agent n0 tcp
- ns attach-agent n1 tcpsink
- ns connect tcp tcpsink
- FTP
- set ftp new Application/FTP
- ftp attach-agent tcp
- Telnet
- set telnet new Application/Telnet
- telnet attach-agent tcp
71Creating Traffic Trace Driven
- Trace driven
- set tfile new Tracefile
- tfile filename ltfilegt
- set src new Application/Traffic/Trace
- src attach-tracefile tfile
- ltfilegt
- Binary format (native!)
- inter-packet time (msec) and packet size (byte)
72Transport
n0
n1
Port Classifier
Port Classifier
Addr Classifier
Addr Classifier
0
0
0
1
dmux_
dmux_
entry_
entry_
classifier_
classifier_
set tcp new Agent/TCP ns_ attach-agent n0 tcp
set tcpsink new Agent/TCPSink ns_ attach-agent
n1 tcpsink
ns_ connect tcp tcpsink
73Application
n0
n1
Port Classifier
Port Classifier
Agent/TCPSink
Addr Classifier
Agent/TCP
Addr Classifier
0
0
agents_
agents_
0
1
dmux_
dmux_
entry_
entry_
classifier_
classifier_
set ftp new Application/FTP ftp attach-agent
tcp ns at 1.2 ftp start
74Packet Flow
n0
n1
Application/FTP
Port Classifier
Port Classifier
Agent/TCPSink
Addr Classifier
Agent/TCP
Addr Classifier
0
0
Link n0-n1
entry_
entry_
Link n1-n0
75Application objects I
- Exponential
- packetSize_
- burst_time_
- idle_time_
- rate_
- CBR
- packetSize_
- rate_
- interval_
- random_
- maxpkts_
76Application objects II
- Pareto
- packetSize_
- burst_time_
- idle_time_
- rate_
- shape_
- Telnet
- interval_
- FTP
- maxpkts_
- All above are virtual applications
- focus only on size and time when data are
transferred
77Application-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
- Two different solutions
- TCP Application/TcpApp
- UDP Agent/Message
78Compare to Real World
- More abstract (much simpler)
- No addresses, just global variables
- Connect them rather than name lookup/bind/listen/a
ccept - Easy to change implementation
- Set tsrc2 new agent/TCP/Newreno
- Set tsrc3 new agent/TCP/Vegas
79Summary Generic Script Structure
- set ns new Simulator
- Turn on tracing
- Create topology
- Setup packet loss, link dynamics
- Create routing agents
- Create
- - multicast groups
- - protocol agents
- - application and/or setup traffic sources
- Post-processing procs
- Start simulation
80Question?
81Two examples
82Example Multicast Routing
time 1.25s
n2
1.5Mb, 10ms
1.5Mb, 10ms
n0
n1
G1
1.5Mb, 10ms
n3
G2
83Multicast Step 1
- Scheduler, tracing, and topology
- Create scheduler
- set ns new Simulator
- Turn on multicast
- ns multicast
- Turn on Tracing
- set fd new mcast.nam w
- ns namtrace-all fd
84Multicast Step 2
- Topology
- Create nodes
- set n0 ns node
- set n1 ns node
- set n2 ns node
- set n3 ns node
- Create links
- ns duplex-link n0 n1 1.5Mb 10ms DropTail
- ns duplex-link n0 n2 1.5Mb 10ms DropTail
- ns duplex-link n0 n3 1.5Mb 10ms DropTail
85Multicast Step 3
- Routing and group setup
- Routing protocol lets run distance vector
- ns mrtproto DM
- Allocate group addresses
- set group1 Node allocaddr
- set group2 Node allocaddr
86Multicast Step 4
- Sender 0
- Transport agent for the traffic source
- set udp0 new Agent/UDP
- ns attach-agent n1 udp0
- udp0 set dst_addr_ group1
- udp0 set dst_port_ 0
- Constant Bit Rate source 0
- set cbr0 new Application/Traffic/CBR
- cbr0 attach-agent udp0
- Start at time 1.0 second
- ns at 1.0 "cbr0 start"
87Multicast Step 5
- Sender 1
- Transport agent for the traffic source
- set udp1 new Agent/UDP
- ns attach-agent n3 udp1
- udp1 set dst_addr_ group2
- udp1 set dst_port_ 0
- Constant Bit Rate source 0
- set cbr1 new Application/Traffic/CBR
- cbr1 attach-agent udp1
- Start at time 1.1 second
- ns at 1.1 "cbr1 start"
88Multicast Step 6
- Receiver with dynamic membership
- Can also be Agent/Null
- set rcvr new Agent/LossMonitor
- Assign it to node n2
- ns at 1.2 "n2 join-group rcvr group2"
- ns at 1.25 "n2 leave-group rcvr group2"
- ns at 1.3 "n2 join-group rcvr group2"
- ns at 1.35 "n2 join-group rcvr group1"
89Multicast Step 7
- End-of-simulation wrapper (as usual)
- ns at 2.0 "finish"
- proc finish
- global ns fd
- close fd
- ns flush-trace
- puts "running nam..."
- exec nam mcast.nam
- exit 0
-
- ns run
90Example Web traffic
3
7
2
8
10Mb, 20ms
1.5Mb, 40ms
0
4
1
9
5
6
10
11
91Web traffic Step 1
- Scheduler and tracing
- Create scheduler
- set ns new Simulator
- instantiate web traffic class
- set pool new PagePool/WebTraf
- Turn on Tracing
- set fd new web.nam w
- ns namtrace-all fd
92Web traffic Step 2
- Topology
- Create nodes
- for set i 0 i lt 12 incr i
- set n(i) ns node
-
- ns set src_ list 2 3 4 5 6
- ns set dst_ list 7 8 9 10 11
- Create links
- ns duplex-link n(0) n(1) 1.5Mb 40ms DropTail
- ns duplex-link n(0) n(2) 10Mb 20ms DropTail
- ns duplex-link n(0) n(3) 10Mb 20ms DropTail
93Web traffic Step 3
- Set up client and server nodes
- pool set-num-client llength ns set src_
- pool set-num-server llength ns set dst_
- set i 0
- foreach s ns set src_
- pool set-client i n(s)
- incr i
-
- set i 0
- foreach s ns set dst_
- pool set-server i n(s)
- incr i
-
94Web traffic Step 4
- Specify the distributions for page arrival, page
size, object arrival, object size - set interPage new RandomVariable/Exponential
- interPage set avg_ 1
- set pageSize new RandomVariable/Constant
- pageSize set val_ 1
- set interObj new RandomVariable/Exponential
- interObj set avg_ 0.01
- set objSize new RandomVariable/ParetoII
- objSize set avg_ 10
- objSize set shape_ 1.2
-
95Web traffic Step 5
- Schedule web sessions
- Lets schedule two sessions
- pool set-num-session 2
- Lets have 10 pages per session
- set numPage 10
- session 1 starts at time 0.1s
- pool create-session 0 numPage 0.1 interPage
pageSize interObj objSize - session 2 starts at time 1.2s
- pool create-session 1 numPage 1.2 interPage
pageSize interObj objSize -
96Web traffic Step 6
- End-of-simulation wrapper (as usual)
- ns at 10.0 "finish"
- proc finish
- global ns fd
- close fd
- ns flush-trace
- puts "running nam..."
- exec nam web.nam
- exit 0
-
- ns run
97Question?
98Outline
- Part 1 model and simulate Internet traffic
- Part 2 an introduction to ns-2
- What is ns-2
- Fundamentals
- writing ns-2 codes
- Wireless support
- Traces support and visualization
- Emulation
- Related work
- Part 3 trace-driven network simulation
99Writing ns-2 codes
- Extending ns
- In OTcl
- In C
- Debugging
100ns Directory Structure
ns-allinone
TK8.3
OTcl
tclcl
Tcl8.3
ns-2
nam-1
C code
...
tcl
ex
test
mcast
lib
...
examples
validation tests
OTcl code
ensure new changes do not break the old codes
101Extending ns in OTcl
- If you dont 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
102Example Agent/Message
n4
n2
128Kb, 50ms
n0
n1
10Mb, 1ms
10Mb, 1ms
n3
n5
message agent
103Agent/Message
pkt 64 bytes of arbitrary string
Receiver-side processing
S
R
- An UDP agent (without UDP header)
- Up to 64 bytes user message
- Good for fast prototyping a simple idea
- Usage requires extending ns functionality
104Agent
- 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
105Exercise
- 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
106Agent/Message Step 1
- Define sender
- class Sender superclass Agent/Message
- Message format Addr Op SeqNo
- Sender instproc send-next
- self instvar seq_ agent_addr_
- self send agent_addr_ send seq_
- incr seq_
- global ns
- ns at expr ns now0.1 "self send-next"
-
107Agent/Message Step 2
- Define sender packet processing
- Sender instproc recv msg
- self instvar agent_addr_
- set sdr lindex msg 0
- set seq lindex msg 2
- puts "Sender gets ack seq from sdr"
-
108Agent/Message Step 3
- Define receiver packet processing
- Class Receiver superclass Agent/Message
- Receiver instproc recv msg
- self instvar agent_addr_
- set sdr lindex msg 0
- set seq lindex msg 2
- puts Receiver gets seq seq from sdr
- self send addr_ ack seq
-
109Agent/Message Step 4
- Scheduler and tracing
- Create scheduler
- set ns new Simulator
- Turn on Tracing
- set fd new message.tr w
- ns trace-all fd
110Agent/Message Step 5
- Topology
- for set i 0 i lt 6 incr i
- set n(i) ns node
-
- ns duplex-link n(0) n(1) 128kb 50ms DropTail
- ns duplex-link n(1) n(4) 10Mb 1ms DropTail
- ns duplex-link n(1) n(5) 10Mb 1ms DropTail
- ns duplex-link n(0) n(2) 10Mb 1ms DropTail
- ns duplex-link n(0) n(3) 10Mb 1ms DropTail
- ns queue-limit n(0) n(1) 5
- ns queue-limit n(1) n(0) 5
111Agent/Message Step 6
- Routing
-
- Packet loss produced by queueing
- Routing protocol lets run distance vector
- ns rtproto DV
-
112Agent/Message Step 7
- Cross traffic
- set udp0 new Agent/UDP
- ns attach-agent n(2) udp0
- set null0 new Agent/NULL
- ns attach-agent n(4) null0
- ns connect udp0 null0
- set exp0 new Application/Traffic/Exponential
- exp0 set rate_ 128k
- exp0 attach-agent udp0
- ns at 1.0 exp0 start
113Agent/Message Step 8
- Message agents
- set sdr new Sender
- sdr set seq_ 0
- sdr set packetSize_ 1000
- set rcvr new Receiver
- rcvr set packetSize_ 40
- ns attach-agent n(3) sdr
- ns attach-agent n(5) rcvr
- ns connect sdr rcvr
- ns at 1.1 sdr send-next
114Agent/Message Step 9
- End-of-simulation wrapper (as usual)
- ns at 2.0 finish
- proc finish
- global ns fd
- ns flush-trace
- close fd
- exit 0
-
- ns run
115Agent/Message Result
- Example output
- gt ./ns msg.tcl
- Receiver gets seq 0 from 3
- Sender gets ack 0 from 5
- Receiver gets seq 1 from 3
- Sender gets ack 1 from 5
- Receiver gets seq 2 from 3
- Sender gets ack 2 from 5
- Receiver gets seq 3 from 3
- Sender gets ack 3 from 5
- Receiver gets seq 4 from 3
- Sender gets ack 4 from 5
- Receiver gets seq 5 from 3
116Add Your Changes into ns
ns-allinone
TK8.3
OTcl
tclcl
Tcl8.3
ns-2
nam-1
C code
...
tcl
mcast
lib
ex
test
...
mysrc
examples
validation tests
msg.tcl
OTcl code
117Add Your Change into ns
- tcl/lib/ns-lib.tcl
- Class Simulator
-
- source ../mysrc/msg.tcl
- Makefile
- NS_TCL_LIB \
- tcl/mysrc/msg.tcl \
-
- Or change Makefile.in, make distclean, then
./configure --enable-debug , - make depend and make
118Writing ns-2 codes
- Extending ns
- In OTcl
- In C
- New components
119Extending ns in C
- Modifying code
- make depend
- Recompile
- Adding code in new files
- Change Makefile
- make depend
- recompile
120Creating New Components
- Guidelines
- Two styles
- New agent based on existing packet headers
- Add new packet header
121Guidelines
- 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)
122New Agent, Old Header
- Exercise TCP jump start
- Wide-open transmission window at the beginning
- From cwnd_ 1 To cwnd_ MAXWIN_
123TCP Jump Start Step 1
TclObject
Handler
NsObject
Connector
Classifier
Delay
AddrClassifier
Agent
McastClasifier
Queue
Trace
DropTail
RED
TCP
Enq
Deq
Drop
JS
Reno
SACK
124TCP Jump Start Step 2
- New file tcp-js.h
- class JSTCPAgent public TcpAgent
- public
- virtual void set_initial_window()
- cwnd_ MAXWIN_
-
- private
- int MAXWIN_
-
125TCP Jump Start Step 3
- New file tcp-js.cc
- static JSTcpClass public TclClass
- public
- JSTcpClass() TclClass("Agent/TCP/JS")
- TclObject create(int, const charconst)
- return (new JSTcpAgent())
-
-
- JSTcpAgentJSTcpAgent()
- bind(MAXWIN_, MAXWIN_)
-
126TCP Jump Start Step 4
- 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
127Packet Format
header
data
128New 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!
129How Packet Header Works
Packet
size determined at compile time
hdr_cmn
size determined at compile time
size determined at simulator startup
time (PacketHeaderManager)
hdr_ip
size determined at compile time
hdr_tcp
130Example Agent/Message
- New packet header for 64-byte message
- New transport agent to process this new header
131New Packet Header Step 1
- Create header structure
- struct hdr_msg
- char msg_64
- static int offset_
- inline static int offset() return offset_
- inline static hdr_msg access(Packet p)
- return (hdr_msg) p-gtaccess(offset_)
-
- / per-field member functions /
- char msg() return (msg_)
- int maxmsg() return (sizeof(msg_))
132New Packet Header Step 2
- Otcl linkage PacketHeader/Message
- static class MessageHeaderClass
- public PacketHeaderClass
- public
- MessageHeaderClass() PacketHeaderClass("PacketH
eader/Message", - sizeof(hdr_msg))
- bind_offset(hdr_msgoffset_)
-
- class_msghdr
133New Packet Header Step 3
- Enable tracing (packet.h)
- enum packet_t
- PT_TCP,
- ,
- PT_MESSAGE,
- PT_NTYPE // This MUST be the LAST one
-
- class p_info
-
- name_PT_MESSAGE message
- name_PT_NTYPE "undefined"
-
134New Packet Header Step 4
- Register new header (tcl/lib/ns-packet.tcl)
- foreach prot
- Common off_cmn_
-
- Message off_msg_
-
- add-packet-header prot
135Packet Header Caution
- Some old code, e.g.
- RtpAgentRtpAgent()
-
- bind(off_rtp_, off_rtp)
-
-
- hdr_rtp rh (hdr_rtp)p-gtaccess(off_rtp_)
- Dont follow this example!
136Agent/Message Step 1
TclObject
NsObject
Connector
Classifier
Delay
AddrClassifier
Agent
McastClasifier
Queue
Trace
Enq
Deq
Drop
DropTail
RED
TCP
Message
Reno
SACK
137Agent/Message Step 2
- C class definition
- // Standard split object declaration
- static
- class MessageAgent public Agent
- public
- MessageAgent() Agent(PT_MESSAGE)
- virtual int command(int argc, const charconst
argv) - virtual void recv(Packet, Handler)
-
138Agent/Message Step 3
- Packet processing msgAgent send data1
- int MessageAgentcommand(int, const charconst
argv) -
- Tcl tcl Tclinstance()
- if (strcmp(argv1, "send") 0)
- Packet pkt allocpkt()
- hdr_msg mh hdr_msgaccess(pkt)
- // We ignore message size check...
- strcpy(mh-gtmsg(), argv2)
- send(pkt, 0)
- return (TCL_OK)
-
- return (Agentcommand(argc, argv))
139Agent/Message Step 4
- Packet processing receive
- void MessageAgentrecv(Packet pkt, Handler)
-
- hdr_msg mh hdr_msgaccess(pkt)
- // OTcl callback
- char wrk128
- sprintf(wrk, "s recv s", name(), mh-gtmsg())
- Tcl tcl Tclinstance()
- tcl.eval(wrk)
- Packetfree(pkt)
140Writing ns-2 codes
- Extending ns
- In OTcl
- In C
- Debugging OTcl/C, memory
- Pitfalls
141Debugging C in ns
- C/OTcl debugging
- Memory debugging
- purify
- dmalloc
142C/OTcl Debugging
- Usual technique
- Break inside command()
- Cannot examine states inside OTcl!
- Solution
- Execute tcl-debug inside gdb
143C/OTcl Debugging
- (gdb) call Tclinstance().eval(debug 1)
- 15 lappend auto_path dbg_library
- dbg15.3gt w
- 0 application
- 15 lappend auto_path dbg_library
- dbg15.4gt Simulator info instances
- _o1
- dbg15.5gt _o1 now
- 0
- dbg15.6gt and other fun stuff
- dbg15.7gt c
- (gdb) where
- 0 0x102218 in write()
- ......
144Memory Debugging in ns
- Purify
- Set PURIFY macro in ns Makefile
- Usually, put -colloctorltld_pathgt
- Gray Watsons dmalloc library
- http//www.dmalloc.com
- make distclean
- ./configure --with-dmallocltdmalloc_pathgt
- Analyze results dmalloc_summarize
145dmalloc Usage
- Turn on dmalloc
- alias dmalloc eval \dmalloc C \!
- dmalloc -l log low
- dmalloc_summarize ns lt logfile
- ns must be in current directory
- Itemize how much memory is allocated in each
function
146Pitfalls
- Scalability vs flexibility
- Or, how to write scalable simulation?
- Memory conservation tips
- Memory leaks
147Scalability vs Flexibility
- Its 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
148THE Merit of OTcl
Program size, complexity
low
high
OTcl
C/C
split objects
- Smoothly adjust the granularity of scripting to
balance extensibility and performance - With complete compatibility with existing
simulation scripts
149Object Granularity Tips
- Functionality
- Per-packet processing ? C
- Hooks, frequently changing code ? OTcl
- Data management
- Complex/large data structure ? C
- One-time configuration variables ? OTcl
150Memory usage
- Simulator 268KB
- Unicast node 2KB
- Multicast node 6KB
- Duplex link 9KB
- Packet 2KB
151Memory Conservation Tips
- Remove unused packet headers
- Avoid trace-all
- Use arrays for a sequence of variables
- Instead of ni, say n(i)
- Avoid OTcl temporary variables
- tempA Btemp
- Use dynamic binding
- delay_bind() instead of 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()
152Memory Leaks
- Purify or dmalloc, but be careful about split
objects - for set i 0 i lt 500 incr i
- set a new RandomVariable/Constant
-
- It leaks memory, but cant be detected!
- Solution
- Explicitly delete EVERY split object that was
new-ed
153Final 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
154Questions?
155Outline
- Part 1 model and simulate Internet traffic
- Part 2 an introduction to ns-2
- What is ns-2
- Fundamentals
- Writing ns-2 codes
- Traces support and visualization
- Wireless support
- Emulation
- Related work
- Part 3 trace-driven network simulation
156ns?nam Interface
- Color
- Node manipulation
- Link manipulation
- Topology layout
- Protocol state
- Misc
157nam Interface Color
- Color mapping
- ns color 40 red
- ns color 41 blue
- ns color 42 chocolate
- Color ? flow id association
- tcp0 set fid_ 40 red packets
- tcp1 set fid_ 41 blue packets
158nam Interface Nodes
- Color
- node color red
- Shape (cant be changed after sim starts)
- node shape box circle, box, hexagon
- Marks (concentric shapes)
- ns at 1.0 n0 add-mark m0 blue box
- ns at 2.0 n0 delete-mark m0
- Label (single string)
- ns at 1.1 n0 label \web cache 0\
- node label-at up
- node label-color blue
159nam Interfaces Links
- Color
- ns duplex-link-op n0 n1 color "green"
- Label
- ns duplex-link-op n0 n1 label "abced
- ns duplex-link-op n1 n2 label-color blue
- ns duplex-link-op n1 n2 label-at down
- Queue position
- ns duplex-link-op queuePos right
- Dynamics (automatically handled)
- ns rtmodel Deterministic 2.0 0.9 0.1 n0 n1
- Asymmetric links not allowed
160nam Interface Topology Layout
- Manual layout specify everything
- ns duplex-link-op n(0) n(1) orient right
- ns duplex-link-op n(1) n(2) orient right
- ns duplex-link-op n(2) n(3) orient right
- ns duplex-link-op n(3) n(4) orient 60deg
- If anything missing ? automatic layout
161nam Interface Misc
- Packet color
- ns color n blue
- agent set fid_ n
- Annotation
- Add textual explanation to your simulation
- ns at 3.5 "ns trace-annotate \packet drop\"
- Control playback
- ns at 0.0 "ns set-animation-rate 0.1ms"
162The nam user interface
163Summary 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
164A live demo
165namgraph
- 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
166namgraph
167The nam editor
- Create simple scenarios graphically
- Good for those who dont want to learn Tcl, but
only a limited subset of ns is currently available
168The nam editor
169Topology generator
170Inet 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 lt inet.topology gt ns.topology
171GT-ITM
- Installation
- Comes with ns-allinone
- Require Knuths cweb and SGB
- Usage
- itm ltconfig_filegt
- Three graph models
- Flat random Waxman
- n-level hierarchy
- Transit-stub
172GT-ITM Transit-Stub Model
transit domains
transit-transit link
stub-stub link
stub domains
173Converters for GT-ITM
- sgb2ns
- Convert SGB format to ns config file
- sgb2ns ltSGB_filegt ltOTcl_filegt
- ts2ns output lists of transit and stub nodes
- sgb2hier
- Convert transit-stub information into
hierarchical addresses - sgb2hierns ltSGB_filegt ltOTcl_filegt
174Tiers 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.
175BRITE
- 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
176Summary
- http//www.isi.edu/nsnam/ns/ns-topogen.html
177A quick review of what happened yesterday
178ns-2 document
- ns-2 website
- ns-2 manual
- ns-2 user mailing list archive
179Using ns
Problem
Result analysis
Simulation model
Modify ns
Setup/run simulation with ns
180C/OTcl Linkage
181TclObject Hierarchy and Shadowing
C class hierarchy
OTcl class hierarchy
TclObject
TclObject
Agent
Agent
TcpAgent
Agent/TCP
tcp
_o123
Agent/TCP OTcl shadow object
Agent/TCP C object
182TclObject Creation and Deletion
invoke parent constructor
OTcl
C
183TclClass
Static class TcpClass public TclClass
public TcpClass() TclClass(Agent/TCP)
TclObject create(int, const charconst)
return (new TcpAgent()) class_tcp
184TclObjectcommand()
OTcl space
no such procedure
tcp send
TclObjectunknown
tcp cmd send
C space
TcpAgentcommand()
match send?
Yes
No
Invoke parent return Agentcommand()
process and return
185Ns programming
- Create the event scheduler
- Turn on tracing
- Create network
- Setup routing
- Insert errors
- Create transport connection
- Create traffic
- Transmit application-level data
186Commonly-used objects
- Node
- Link
- Packet
- Error module
- Timer
- Agent
- Application
187Network Topology Node
Unicast Node
0
0
1
Set ns_ new Simulator multicast on Set n1 ns_
node
set n0 ns_ node
188Network Topology Link
ns_ duplex-link n0 n1 5Mb 2ms drop-tail
189Packet Format
header
data
190How Packet Header Works
Packet
size determined at compile time
hdr_cmn
size determined at compile time
size determined at simulator startup
time (PacketHeaderManager)
hdr_ip
size determined at compile time
hdr_tcp
191Packet Flow
n0
n1
Application/FTP
Port Classifier
Port Classifier
Agent/TCPSink
Addr Classifier
Agent/TCP
Addr Classifier
0
0
Link n0-n1
entry_
entry_
Link n1-n0
192ns Directory Structure
ns-allinone
TK8.3
OTcl
tclcl
Tcl8.3
ns-2
nam-1
C code
...
tcl
ex
test
mcast
lib
...
examples
validation tests
OTcl code
ensure new changes do not break the old codes
193Guidelines
- 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)
194C/OTcl Debugging
- (gdb) call Tclinstance().eval(debug 1)
- 15 lappend auto_path dbg_library
- dbg15.3gt w
- 0 application
- 15 lappend auto_path dbg_library
- dbg15.4gt Simulator info instances
- _o1
- dbg15.5gt _o1 now
- 0
- dbg15.6gt and other fun stuff
- dbg15.7gt c
- (gdb) where
- 0 0x102218 in write()
- ......
195Memory Debugging in ns
- Purify
- Set PURIFY macro in ns Makefile
- Usually, put -collocto