introduction to ns-2ce.aut.ac.ir/~bakhshis/ns-2/introduction to ns-2.pdf · 3/29/2007 ncku 4 ns...

Post on 23-Mar-2020

12 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

3/29/2007 NCKU 1

Introduction to ns-2

3/29/2007 NCKU 2

Outline

•An introduction to ns-2•What is ns-2•Fundamentals•Writing ns-2 codes•Wireless support•Traces support and visualization•Emulation•Related work

3/29/2007 NCKU 3

What is ns-2

•History•What does it support

3/29/2007 NCKU 4

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

3/29/2007 NCKU 5

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 provideunderstanding, but•Limited details

•Important niches•Limited re-use

3/29/2007 NCKU 6

History 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-levelsimulator• Used by 10000+ users from 1000+ institutes from 50+ countries• 300+ posts to ns-users@isi.edu every month

3/29/2007 NCKU 7

ns-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

3/29/2007 NCKU 8

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

3/29/2007 NCKU 9

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

3/29/2007 NCKU 10

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

3/29/2007 NCKU 11

“Ns” 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

3/29/2007 NCKU 12

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, …

3/29/2007 NCKU 13

Getting Help

•ns-2 build questions•http://www.isi.edu/nsnam/ns/ns-build.html

•ns-users@isi.edu•ns-users-request@isi.edu•“subscribe ns-users” in body•Archive: http://www.isi.edu/nsnam/ns

3/29/2007 NCKU 14

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

3/29/2007 NCKU 15

Cautions

•Abstraction of the real world is necessaryfor a simulator•You must justify the usage of the

simulator based on your research goals

3/29/2007 NCKU 16

Question?

3/29/2007 NCKU 17

Outline

•An introduction to ns-2•What is ns-2•Fundamentals•Writing ns-2 codes•Wireless support•Traces support and visualization•Emulation•Related work

3/29/2007 NCKU 18

Prerequisite

•Some programming experience ofobject-oriented language (such as C++,Java)

3/29/2007 NCKU 19

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 ofreal time

•Ns uses simple model: single thread ofcontrol => no locking or race conditions toworry about

3/29/2007 NCKU 20

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

3/29/2007 NCKU 21

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

Tcl

OTclTclCL

ns-2C++

EventScheduler

NetworkComponents

3/29/2007 NCKU 22

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 speedLearning and debugging (two languages)

3/29/2007 NCKU 23

Control vs. Data

•Create topology•Setup routing•Create transport

connection•Create traffic

•Details of links andnodes•Details of a routing

protocol•Details of TCP

implementation•Details of a packet

OTcl C++

3/29/2007 NCKU 24

Otcl and C++: The Duality

•OTcl (object variant of Tcl) and C++ share classhierarchy•TclCL is glue library that makes it easy to share

functions, variables, etc

C++

otcl

C++/OTclsplit objects

ns

usersimulationscripts

3/29/2007 NCKU 25

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 realprogramming language tobuild network topologies,traffic models, etc.

3/29/2007 NCKU 26

Compare Otcl to C++•Object oriented extension of Tcl•C++ constructor/destructor => OTclinit/destroy method

•C++ this => OTcl $self•OTclmethods always “virtual”•C++ static variable => OTcl class

variable•Multiple inheritance is supported

3/29/2007 NCKU 27

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)

3/29/2007 NCKU 28

Using ns

Problem

Simulationmodel

Setup/runsimulation

with ns

Resultanalysis

Modifyns

3/29/2007 NCKU 29

C++/OTcl Linkage

Root of ns-2 object hierarchy

bind(): link variable values betweenC++ and OTclTclObject

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

3/29/2007 NCKU 30

TclObject

•Basic hierarchy in ns for split objects•Mirrored in both C++ and OTcl•Example••setset tcptcp [new Agent/TCP][new Agent/TCP]••$$tcptcp setset packetSizepacketSize_ 1024_ 1024••$$tcptcp advancebyadvanceby 50005000

3/29/2007 NCKU 31

TclObject: Hierarchy andShadowing

TclObject

Agent

Agent/TCP

Agent/TCP OTclshadow object

_o123Agent/TCP C++

object

*tcp

TclObject

Agent

TcpAgent

OTcl classhierarchy

C++ classhierarchy

3/29/2007 NCKU 32

TclObject::bind()

•Link C++ member variables to OTclobject variables•C++•TcpAgent::TcpAgent() {•bind(“window_”, &wnd_);•… …

•}

•OTcl••setset tcptcp [new Agent/TCP][new Agent/TCP]••$$tcptcp set window_ 200set window_ 200

3/29/2007 NCKU 33

TclObject::command()

•Implement OTcl methods in C++•Trap point: OTcl method cmd{}•Access the shadow object

•Send all arguments after cmd{} call toTclObject::command()

3/29/2007 NCKU 34

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

3/29/2007 NCKU 35

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);

}

3/29/2007 NCKU 36

TclObject: Creation andDeletion

•Global procedures: new{}, delete{}•Example••setset tcptcp [new Agent/TCP][new Agent/TCP]••……••delete $delete $tcptcp

3/29/2007 NCKU 37

C++

OTcl

TclObject: Creation andDeletion

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

completeinitialization

completeinitialization

which C++object to create?–TclClass

3/29/2007 NCKU 38

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;

3/29/2007 NCKU 39

NsObject

•Other important objects:•NsObject: has recv() method•Connector: has target() and drop()•BiConnector: uptarget() &

downtarget()•Class hierarchy•NsObject•Connector•PingAgent

•BiConnector•Mac802_11

PHY

MAC

NETWORK

TRANSPORT

SESSION

PRESENTATION

APPLICATION

3/29/2007 NCKU 40

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”);

3/29/2007 NCKU 41

Class Tcl

Tcl& 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;

}

3/29/2007 NCKU 42

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());

}

3/29/2007 NCKU 43

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

3/29/2007 NCKU 44

Question?

3/29/2007 NCKU 45

Ns programming

•Create the event scheduler•Turn on tracing•Create network•Setup routing•Insert errors•Create transport connection•Create traffic•Transmit application-level data

3/29/2007 NCKU 46

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

3/29/2007 NCKU 47

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”

3/29/2007 NCKU 48

Some scheduler-relatedcommands

•Set now [$ns now]•$ns cancel <event>•$ns after <delay> <event>•Execute <event> after <delay>

•$ns dumpq•Dump all events in the scheduler queue

3/29/2007 NCKU 49

Discrete Event Scheduler

time_, uid_, next_, handler_head_ ->

handler_ -> handle()

time_, uid_, next_, handler_insert

head_ ->

3/29/2007 NCKU 50

Hello World - InteractiveMode

Interactive 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%

3/29/2007 NCKU 51

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

3/29/2007 NCKU 52

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 $slink $fmon$fmon set pdrops_

3/29/2007 NCKU 53

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 $$tcptcp$ns monitor$ns monitor--agentagent--trace $trace $tcptcp$srm0$srm0 tracevartracevar cwndcwnd__…………$ns delete$ns delete--agentagent--trace $trace $tcptcp

3/29/2007 NCKU 54

Ns Internals

•Tcl commands translates into•series of object creation•plumbing of these objects

3/29/2007 NCKU 55

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

Network Topology: Node

n0 n1

AddrClassifier

PortClassifier

classifier_

dmux_

entry_

Node entry

UnicastNode

MulticastClassifier

classifier_

dmux_

entry_

Node entry

MulticastNode

multiclassifier_

set n0 [ns_ node] Set ns_ [new Simulator–multicast on]Set n1 [ns_ node]

0 0

1

3/29/2007 NCKU 57

Node Addressing

•Two basic address styles available: flatand 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 specifichier addresses

58

Hierarchical Node

n2

Nodeentry

Level 1Level 2

Level 3

Addressclassifier To Port

demux

ns_ node-config–addressing hier

3/29/2007 NCKU 59

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{}

Network Topology: Link

n0 n1

enqT_ queue_ deqT_

drophead_ drpT_

link_ ttl_

n1entry_head_

tracing simplex link

duplex link

[ns_ duplex-link $n0 $n1 5Mb 2ms drop-tail]

3/29/2007 NCKU 61

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

3/29/2007 NCKU 62

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

3/29/2007 NCKU 63

Setup Routing

•Unicast$ns rtproto <type><type>: Static, Session, DV, cost, multi-path

•Multicast$ns multicast (right after [new Simulator])$ns mrtproto <type><type>: CtrMcast, DM, ST, BST

•Other types of routing supported: source routing,hierarchical routing

3/29/2007 NCKU 64

Routing..

n0 n1

AddrClassifier

PortClassifier

classifier_

dmux_

entry_

Node entry 01 enqT_ queue_ deqT_

drophead_ drpT_

link_ ttl_

n1entry_

head_

3/29/2007 NCKU 65

..Routing

n0 n1

AddrClassifier

PortClassifier

classifier_

dmux_

entry_

01

AddrClassifier

PortClassifier

classifier_

dmux_

entry_

10

Link n0-n1

Link n1-n0

3/29/2007 NCKU 66

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

3/29/2007 NCKU 67

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

3/29/2007 NCKU 68

Network Dynamics

•Link failures•Hooks in routing module to reflect routing

changes•Four models

$ns$ns rtmodelrtmodel Trace <Trace <configconfig_file> $n0 $n1_file> $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>]

3/29/2007 NCKU 69

•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 Paretoon-off

set src [newApplication/Traffic/Exponential]

set src [newApplication/Traffic/Pareto]

$src attach-agent $udp

Creating Connection andTraffic I

3/29/2007 NCKU 70

Creating Connection andTraffic 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

3/29/2007 NCKU 71

Creating Traffic: TraceDriven

•Trace drivenset tfile [new Tracefile]$tfile filename <file>set src [new Application/Traffic/Trace]$src attach-tracefile $tfile<file>:•Binary format (native!)•inter-packet time (msec) and packet size (byte)

Transport

n0 n1

AddrClassifier

PortClassifier

classifier_

dmux_

entry_

Agent/TCP

agents_

AddrClassifier

PortClassifier

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

73

Application

n0 n1

AddrClassifier

PortClassifier

classifier_

dmux_

entry_

Agent/TCP

agents_

AddrClassifier

PortClassifier

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

3/29/2007 NCKU 74

Packet Flow

01

n0 n1

AddrClassifier

PortClassifier

entry_

0 Agent/TCP AddrClassifier

PortClassifier

entry_

10

Link n0-n1

Link n1-n0

0 Agent/TCPSink

dst_=1.0 dst_=0.0Application/FTP

3/29/2007 NCKU 75

Application objects I

•Exponential•packetSize_•burst_time_•idle_time_•rate_

•CBR•packetSize_•rate_•interval_•random_•maxpkts_

3/29/2007 NCKU 76

Application 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

3/29/2007 NCKU 77

Application-LevelSimulation

•Simulate applications that actually transfer theirown 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

3/29/2007 NCKU 78

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 implementationSet tsrc2 [new agent/TCP/Newreno]Set tsrc3 [new agent/TCP/Vegas]

3/29/2007 NCKU 79

Summary: Generic ScriptStructure

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--processingprocessing procsprocs# Start simulation# Start simulation

3/29/2007 NCKU 80

Question?

3/29/2007 NCKU 81

Two examples

•Multicast•Web traffic

3/29/2007 NCKU 82

G2time1.3s

G2time1.2s

G1G2

time1.35s

Example: MulticastRouting

•Dynamic group membership

n0 n1

n2

n3

1.5Mb, 10ms

1.5Mb, 10ms

G1

time1.25s

G2

1.5Mb, 10ms

3/29/2007 NCKU 83

Multicast: Step 1

•Scheduler, tracing, and topology

# Create scheduler# Create schedulerset ns [new Simulator]set ns [new Simulator]

# Turn on multicast# Turn on multicast$ns multicast$ns multicast

# Turn on Tracing# Turn on Tracingsetset fdfd [new “[new “mcastmcast..namnam” w]” w]$ns$ns namtracenamtrace--all $all $fdfd

3/29/2007 NCKU 84

Multicast: Step 2

•Topology

# Create nodes# Create nodesset 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 10mslink $n0 $n1 1.5Mb 10ms DropTailDropTail$ns duplex$ns duplex--link $n0 $n2 1.5Mb 10mslink $n0 $n2 1.5Mb 10ms DropTailDropTail$ns duplex$ns duplex--link $n0 $n3 1.5Mb 10mslink $n0 $n3 1.5Mb 10ms DropTailDropTail

3/29/2007 NCKU 85

Multicast: Step 3

•Routing and group setup

# Routing protocol: let’s run distance vector# Routing protocol: let’s run distance vector$ns$ns mrtprotomrtproto DMDM

# Allocate group addresses# Allocate group addressesset group1 [Nodeset group1 [Node allocaddrallocaddr]]set group2 [Nodeset group2 [Node allocaddrallocaddr]]

3/29/2007 NCKU 86

Multicast: Step 4

•Sender 0

# Transport agent for the traffic source# Transport agent for the traffic sourcesetset udp0udp0 [new Agent/UDP][new Agent/UDP]$ns attach$ns attach--agent $agent $n1n1 $$udp0udp0$$udp0udp0 setset dstdst__addraddr_ $_ $group1group1$$udp0udp0 setset dstdst_port_ 0_port_ 0

# Constant Bit Rate source #0# Constant Bit Rate source #0setset 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"

3/29/2007 NCKU 87

Multicast: Step 5

•Sender 1

# Transport agent for the traffic source# Transport agent for the traffic sourcesetset udp1udp1 [new Agent/UDP][new Agent/UDP]$ns attach$ns attach--agent $agent $n3n3 $$udp1udp1$$udp1udp1 setset dstdst__addraddr_ $_ $group2group2$$udp1udp1 setset dstdst_port_ 0_port_ 0

# Constant Bit Rate source #0# Constant Bit Rate source #0setset 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"

3/29/2007 NCKU 88

Multicast: Step 6

•Receiver with dynamic membership

# Can also be Agent/Null# Can also be Agent/Nullsetset 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""

3/29/2007 NCKU 89

Multicast: Step 7

•End-of-simulation wrapper (as usual)

$ns at 2.0 "finish"$ns at 2.0 "finish"proc finish {} {proc finish {} {

global nsglobal ns fdfdclose $close $fdfd$ns flush$ns flush--tracetraceputs "runningputs "running namnam..."..."execexec namnam mcastmcast..namnam &&exit 0exit 0

}}$ns run$ns run

3/29/2007 NCKU 90

Example: Web traffic

1

2

0

8 3

56

49

7

10 11

1.5Mb, 40ms

10Mb, 20ms

3/29/2007 NCKU 91

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 poolset pool [new[new PagePoolPagePool//WebTrafWebTraf]]

# Turn on Tracing# Turn on Tracingsetset fdfd [new “web.[new “web.namnam” w]” w]$ns$ns namtracenamtrace--all $all $fdfd

3/29/2007 NCKU 92

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 40mslink $n(0) $n(1) 1.5Mb 40ms DropTailDropTail$ns duplex$ns duplex--link $n(0) $n(2) 10Mb 20mslink $n(0) $n(2) 10Mb 20ms DropTailDropTail$ns duplex$ns duplex--link $n(0) $n(3) 10Mb 20mslink $n(0) $n(3) 10Mb 20ms DropTailDropTail

3/29/2007 NCKU 93

Web traffic: Step 3•Set up client and server nodes

$$poolpool 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 sets [$ns set srcsrc_] {_] {

$pool$pool setset--clientclient $i $n($s)$i $n($s)incrincr ii

}}set i 0set i 0foreachforeach s [$ns sets [$ns set dstdst_] {_] {

$pool$pool setset--serverserver $i $n($s)$i $n($s)incrincr ii

}}

3/29/2007 NCKU 94

Web traffic: Step 4

•Specify the distributions for page arrival,page size, object arrival, object sizesetset interPageinterPage [new[new RandomVariableRandomVariable/Exponential]/Exponential]$$interPageinterPage setset avgavg_ 1_ 1setset pageSizepageSize [new[new RandomVariableRandomVariable/Constant]/Constant]$$pageSizepageSize setset valval_ 1_ 1setset interObjinterObj [new[new RandomVariableRandomVariable/Exponential]/Exponential]$$interObjinterObj setset avgavg_ 0.01_ 0.01setset objSizeobjSize [new[new RandomVariableRandomVariable//ParetoIIParetoII]]$$objSizeobjSize setset avgavg_ 10_ 10$$objSizeobjSize set shape_ 1.2set shape_ 1.2

3/29/2007 NCKU 95

Web traffic: Step 5

•Schedule web sessions

# Let’s schedule two sessions# Let’s schedule two sessions$pool set$pool set--numnum--session 2session 2# Let’s have 10 pages per session# Let’s have 10 pages per sessionsetset 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

3/29/2007 NCKU 96

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 nsglobal ns fdfdclose $close $fdfd$ns flush$ns flush--tracetraceputs "runningputs "running namnam..."..."execexec namnam web.web.namnam &&exit 0exit 0

}}$ns run$ns run

3/29/2007 NCKU 97

Question?

3/29/2007 NCKU 98

Outline

•An introduction to ns-2•What is ns-2•Fundamentals•writing ns-2 codes•Wireless support•Traces support and visualization•Emulation•Related work

3/29/2007 NCKU 99

Writing ns-2 codes

•Extending ns•In OTcl•In C++

•Debugging

3/29/2007 NCKU 100

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

3/29/2007 NCKU 101

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

3/29/2007 NCKU 102

Example: Agent/Message

n0 n1

n4

n5

n2

n3

128Kb, 50ms

10Mb, 1ms 10Mb, 1ms

C Ccrosstraffic

S R

message agent

3/29/2007 NCKU 103

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 arbitrarystring

Receiver-sideprocessing

3/29/2007 NCKU 104

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

3/29/2007 NCKU 105

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

3/29/2007 NCKU 106

Agent/Message: Step 1

•Define senderclass Senderclass Sender ––superclasssuperclass Agent/MessageAgent/Message

# Message format: “# Message format: “AddrAddr OpOp SeqNoSeqNo””SenderSender instprocinstproc sendsend--next {} {next {} {

$self$self instvarinstvar seqseq_ agent__ agent_addraddr__$self send “$agent_$self send “$agent_addraddr_ 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"

}}

3/29/2007 NCKU 107

Agent/Message: Step 2

•Define sender packet processing

SenderSender instprocinstproc recvrecv msgmsg {{$self$self instvarinstvar agent_agent_addraddr__setset sdrsdr [[lindexlindex $$msgmsg 0]0]setset seqseq [[lindexlindex $$msgmsg 2]2]puts "Sender getsputs "Sender gets ackack $$seqseq from $from $sdrsdr""

}}

3/29/2007 NCKU 108

Agent/Message: Step 3

•Define receiver packet processing

Class ReceiverClass Receiver ––superclasssuperclass Agent/MessageAgent/MessageReceiverReceiver instprocinstproc recvrecv msgmsg {{

$self$self instvarinstvar agent_agent_addraddr__setset sdrsdr [[lindexlindex $$msgmsg 0]0]setset seqseq [[lindexlindex $$msgmsg 2]2]puts “Receiver gets puts “Receiver gets seqseq $$seqseq from $from $sdrsdr””$self send “$$self send “$addraddr__ ackack $$seqseq””

}}

3/29/2007 NCKU 109

Agent/Message: Step 4

•Scheduler and tracing

# Create scheduler# Create schedulerset ns [new Simulator]set ns [new Simulator]

# Turn on Tracing# Turn on Tracingsetset fdfd [new “message.[new “message.trtr” w]” w]$ns trace$ns trace--all $all $fdfd

3/29/2007 NCKU 110

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 50mslink $n(0) $n(1) 128kb 50ms DropTailDropTail$ns duplex$ns duplex--link $n(1) $n(4) 10Mb 1mslink $n(1) $n(4) 10Mb 1ms DropTailDropTail$ns duplex$ns duplex--link $n(1) $n(5) 10Mb 1mslink $n(1) $n(5) 10Mb 1ms DropTailDropTail$ns duplex$ns duplex--link $n(0) $n(2) 10Mb 1mslink $n(0) $n(2) 10Mb 1ms DropTailDropTail$ns duplex$ns duplex--link $n(0) $n(3) 10Mb 1mslink $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

3/29/2007 NCKU 111

Agent/Message: Step 6

•Routing

# Packet loss produced by# Packet loss produced by queueingqueueing

# Routing protocol: let’s run distance vector# Routing protocol: let’s run distance vector$ns$ns rtprotortproto DVDV

3/29/2007 NCKU 112

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 “$exp0 start”$ns at 1.0 “$exp0 start”

3/29/2007 NCKU 113

Agent/Message: Step 8•Message agents

setset sdrsdr [new Sender][new Sender]$$sdrsdr setset seqseq_ 0_ 0$$sdrsdr setset packetSizepacketSize_ 1000_ 1000

setset rcvrrcvr [new Receiver][new Receiver]$$rcvrrcvr setset 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--next”next”

3/29/2007 NCKU 114

Agent/Message: Step 9

•End-of-simulation wrapper (as usual)

$ns at 2.0 finish$ns at 2.0 finishproc finish {} {proc finish {} {

global nsglobal ns fdfd$ns flush$ns flush--tracetraceclose $close $fdfdexit 0exit 0

}}$ns run$ns run

3/29/2007 NCKU 115

Agent/Message: Result

•Example output> ./ns msg.> ./ns msg.tcltclReceiver getsReceiver gets seqseq 0 from 30 from 3Sender getsSender gets ackack 0 from 50 from 5Receiver getsReceiver gets seqseq 1 from 31 from 3Sender getsSender gets ackack 1 from 51 from 5Receiver getsReceiver gets seqseq 2 from 32 from 3Sender getsSender gets ackack 2 from 52 from 5Receiver getsReceiver gets seqseq 3 from 33 from 3Sender getsSender gets ackack 3 from 53 from 5Receiver getsReceiver gets seqseq 4 from 34 from 3Sender getsSender gets ackack 4 from 54 from 5Receiver getsReceiver gets seqseq 5 from 35 from 3

3/29/2007 NCKU 116

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

3/29/2007 NCKU 117

Add Your Change into ns

•tcl/lib/ns-lib.tclClass SimulatorClass Simulator……source ../source ../mysrcmysrc/msg./msg.tcltcl

•MakefileNS_TCL_LIB =NS_TCL_LIB = \\tcltcl//mysrcmysrc/msg./msg.tcltcl \\……•Or: change Makefile.in, makemake distcleandistclean, then./configure./configure ----enableenable--debug ,debug ,make dependmake depend andand makemake

3/29/2007 NCKU 118

Writing ns-2 codes

•Extending ns•In OTcl•In C++•New components

3/29/2007 NCKU 119

Extending ns in C++

•Modifying code•make depend•Recompile

•Adding code in new files•Change Makefile•make depend•recompile

3/29/2007 NCKU 120

Creating New Components

•Guidelines•Two styles•New agent based on existing packet headers•Add new packet header

3/29/2007 NCKU 121

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)

3/29/2007 NCKU 122

New Agent, Old Header

•Exercise: TCP jump start•Wide-open transmission window at the

beginning•From cwndcwnd_ += 1_ += 1 To cwndcwnd_ = MAXWIN__ = MAXWIN_

3/29/2007 NCKU 123

TCP Jump Start –Step 1

TclObject

NsObject

Connector Classifier

Delay AddrClassifierAgent McastClasifierQueue Trace

DropTail RED TCP Enq Deq Drop

Reno SACK JS

Handler

3/29/2007 NCKU 124

TCP Jump Start –Step 2

•New file: tcp-js.h

classclass JSTCPAgentJSTCPAgent : public: public TcpAgentTcpAgent {{public:public:

virtual void set_initial_window() {virtual void set_initial_window() {cwndcwnd_ = MAXWIN_;_ = MAXWIN_;

}}private:private:

intint MAXWIN_;MAXWIN_;};};

3/29/2007 NCKU 125

TCP Jump Start –Step 3

•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_);}

3/29/2007 NCKU 126

TCP Jump Start –Step 4

•Create an instance of jump-start TCP inyour 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

3/29/2007 NCKU 127

Packet Format

header

dataip header

tcp header

rtp header

trace header

cmn header

...

ts_

ptype_

uid_

size_

iface_

3/29/2007 NCKU 128

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!

3/29/2007 NCKU 129

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

3/29/2007 NCKU 130

Example: Agent/Message

•New packet header for 64-byte message•New transport agent to process this new

header

3/29/2007 NCKU 131

New Packet Header–Step 1

•Create header structurestructstruct hdrhdr__msgmsg {{

char msg_[64];char msg_[64];staticstatic intint offset_;offset_;inline staticinline static intint& offset() { return offset_; }& offset() { return offset_; }inline staticinline static hdrhdr__msgmsg* access(Packet* p) {* access(Packet* p) {return (return (hdrhdr__msgmsg*) p*) p-->access(offset_);>access(offset_);

}}/* per/* per--field member functions */field member functions */char*char* msgmsg() { return (() { return (msgmsg_); }_); }intint maxmsgmaxmsg() { return (() { return (sizeofsizeof((msgmsg_)); }_)); }

};};

3/29/2007 NCKU 132

New Packet Header–Step 2

•Otcl linkage: PacketHeader/Messagestatic classstatic class MessageHeaderClassMessageHeaderClass ::

publicpublic PacketHeaderClassPacketHeaderClass {{public:public:MessageHeaderClassMessageHeaderClass() :() :PacketHeaderClassPacketHeaderClass("("PacketHeaderPacketHeader/Message/Message",",

sizeofsizeof((hdrhdr__msgmsg)) {)) {bind_offset(&bind_offset(&hdrhdr__msgmsg::offset_);::offset_);

}}} class_} class_msghdrmsghdr;;

3/29/2007 NCKU 133

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] = “message”;name_[PT_MESSAGE] = “message”;name_[PT_NTYPE]= "undefined";name_[PT_NTYPE]= "undefined";…………

};};

3/29/2007 NCKU 134

New Packet Header–Step 4

•Register new header (tcl/lib/ns-packet.tcl)

foreachforeach protprot {{{ Common off_{ Common off_cmncmn_ }_ }……{{ Message off_Message off_msgmsg__ }}

}}addadd--packetpacket--header $header $protprot

3/29/2007 NCKU 135

Packet Header: Caution

•Some old code, e.g.:RtpAgentRtpAgent::::RtpAgentRtpAgent() {() {…… …… bind(“off_bind(“off_rtprtp_”, &off__”, &off_rtprtp););

}}…………hdrhdr__rtprtp** rhrh = (= (hdrhdr__rtprtp*)p*)p-->access(off_>access(off_rtprtp_);_);

•Don’t follow this example!

3/29/2007 NCKU 136

Agent/Message –Step 1

TclObject

NsObject

Connector Classifier

Delay AddrClassifierAgent McastClasifierQueue Trace

DropTail RED TCP Enq Deq Drop

Reno SACK

Message

3/29/2007 NCKU 137

Agent/Message –Step 2

•C++ class definition// Standard split object declaration// Standard split object declarationstatic …static …

classclass MessageAgentMessageAgent : public Agent {: public Agent {public:public:

MessageAgentMessageAgent() : Agent(() : Agent(PT_MESSAGEPT_MESSAGE) {}) {}virtualvirtual intint command(command(intint argcargc, const char*const*, const char*const*argvargv););virtual voidvirtual void recvrecv(Packet*, Handler*);(Packet*, Handler*);

};};

3/29/2007 NCKU 138

Agent/Message –Step 3

•Packet processing: $msgAgent send “data1”intint MessageAgentMessageAgent::command(::command(intint, const char*const*, const char*const* argvargv)){{

TclTcl&& tcltcl == TclTcl::instance();::instance();if (strcmp(argv[1], "send") == 0) {if (strcmp(argv[1], "send") == 0) {Packet*Packet* pktpkt == allocpktallocpkt();();hdrhdr__msgmsg** mhmh == hdrhdr__msgmsg::access(::access(pktpkt););// We ignore message size check...// We ignore message size check...strcpystrcpy((mhmh-->>msgmsg(), argv[2]);(), argv[2]);send(send(pktpkt, 0);, 0);return (TCL_OK);return (TCL_OK);

}}return (Agent::command(return (Agent::command(argcargc,, argvargv));));

}}

3/29/2007 NCKU 139

Agent/Message –Step 4

•Packet processing: receivevoidvoid MessageAgentMessageAgent::::recvrecv(Packet*(Packet* pktpkt, Handler*), Handler*){{

hdrhdr__msgmsg** mhmh == hdrhdr__msgmsg::access(::access(pktpkt););

//// OTclOTcl callbackcallbackchar wrk[128];char wrk[128];sprintfsprintf((wrkwrk, "%s, "%s recvrecv {%s}", name(),{%s}", name(), mhmh-->>msgmsg());());TclTcl&& tcltcl == TclTcl::instance();::instance();tcltcl..evaleval((wrkwrk););

Packet::free(Packet::free(pktpkt););}}

3/29/2007 NCKU 140

Writing ns-2 codes

•Extending ns•In OTcl•In C++•Debugging: OTcl/C++, memory•Pitfalls

3/29/2007 NCKU 141

Debugging C++ in ns

•C++/OTcl debugging

•Memory debugging•purify•dmalloc

3/29/2007 NCKU 142

C++/OTcl Debugging

•Usual technique•Break inside command()•Cannot examine states inside OTcl!

•Solution•Execute tcl-debug inside gdb

3/29/2007 NCKU 143

C++/OTcl Debugging

((gdbgdb)) callcall TclTcl::instance().::instance().evaleval(“debug 1”)(“debug 1”)15:15: lappendlappend auto_path $auto_path $dbgdbg_library_librarydbg15.3> wdbg15.3> w*0: application*0: application15:15: lappendlappend auto_path $auto_path $dbgdbg_library_librarydbg15.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()............

3/29/2007 NCKU 144

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

3/29/2007 NCKU 145

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

3/29/2007 NCKU 146

Pitfalls

•Scalability vs flexibility•Or, how to write scalable simulation?

•Memory conservation tips•Memory leaks

3/29/2007 NCKU 147

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++

3/29/2007 NCKU 148

THE Merit of OTcl

Program size, complexity

C/C++ OTcl

•Smoothly adjust the granularity of scripting tobalance extensibility and performance•With complete compatibility with existing

simulation scripts

high low

split objects

3/29/2007 NCKU 149

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

3/29/2007 NCKU 150

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()

3/29/2007 NCKU 152

Memory Leaks

•Purify or dmalloc, but be careful about splitobjects:••for {set i 0} {$i < 500} {for {set i 0} {$i < 500} {incrincr i} {i} {•• set a [newset a [new RandomVariableRandomVariable/Constant]/Constant]••}}

•It leaks memory, but can’t be detected!

•Solution•Explicitly delete EVERY split object that was new-ed

3/29/2007 NCKU 153

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 bythe error message

3/29/2007 NCKU 154

Questions?

3/29/2007 NCKU 155

Outline

•An introduction to ns-2•What is ns-2•Fundamentals•Writing ns-2 codes•Traces support and visualization•Wireless support•Emulation•Related work

3/29/2007 NCKU 156

nsnam Interface

•Color•Node manipulation•Link manipulation•Topology layout•Protocol state•Misc

3/29/2007 NCKU 157

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

3/29/2007 NCKU 158

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 “$n0 add$ns at 1.0 “$n0 add--mark m0 blue box”mark m0 blue box”$ns at 2.0 “$n0 delete$ns at 2.0 “$n0 delete--mark m0”mark m0”

•Label (single string)$ns at 1.1 “$n0 label $ns at 1.1 “$n0 label \\”web cache 0”web cache 0\\””””$node label$node label--at upat up$node label$node label--color bluecolor blue

3/29/2007 NCKU 159

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

3/29/2007 NCKU 160

nam Interface: TopologyLayout

•“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 automaticlayout

3/29/2007 NCKU 161

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--annotateannotate \\“packet drop“packet drop\\"“"“

• Control playback$ns at 0.0 "$ns set$ns at 0.0 "$ns set--animationanimation--rate 0.1ms"rate 0.1ms"

3/29/2007 NCKU 162

The nam user interface

3/29/2007 NCKU 163

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

3/29/2007 NCKU 164

A live demoCmd.exe

3/29/2007 NCKU 165

namgraph

•Display a graph showing when packetsare received/dropped.•Enabling namgraph•Run the namfilter script on your nam trace

file:exec tclsh /path/to/namfilter.tcl out.nam

3/29/2007 NCKU 166

namgraph

3/29/2007 NCKU 167

The nam editor

•Create simple scenarios graphically•Good for those who don’t want to learn

Tcl, but only a limited subset of ns iscurrently available

3/29/2007 NCKU 168

The nam editor

3/29/2007 NCKU 169

Topology generator

•Inet•GT-ITM•TIERS•BRITE

3/29/2007 NCKU 170

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

3/29/2007 NCKU 171

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

3/29/2007 NCKU 172

GT-ITM: Transit-StubModel

stubdomains

transitdomains

transit-transit link

stub-stub link

3/29/2007 NCKU 173

Converters for GT-ITM

•sgb2ns•Convert SGB format to ns config file••sgb2ns <SGB_file> <sgb2ns <SGB_file> <OTclOTcl_file>_file>••ts2nsts2ns: output lists of transit and stub nodes

•sgb2hier•Convert transit-stub information into

hierarchical addresses••sgb2hierns <SGB_file> <sgb2hierns <SGB_file> <OTclOTcl_file>_file>

3/29/2007 NCKU 174

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 intons-2 scripts.

3/29/2007 NCKU 175

BRITE

•From Boston University•Supports multiple generation models•flat AS•flat Router•hierarchical topologies

•Object-oriented design to allow the flexibility toadd 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

3/29/2007 NCKU 176

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

3/29/2007 NCKU 177

A case study: class webtraf

3/29/2007 NCKU 178

Outline

•An introduction to ns-2•What is ns-2•Fundamentals•Writing ns-2 codes•Traces support and visualization•Wireless support•Emulation•Related work

3/29/2007 NCKU 179

Wireless support in ns-2

•Introduction•Wireless basics•Wireless internals

•Ad hoc routing•Mobile IP•Satellite networking•Directed diffusion

3/29/2007 NCKU 180

Contributions to wirelessin ns

•Original wireless model in ns contributedby 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

3/29/2007 NCKU 181

Wireless model

•Mobilenode at core of mobility model•Mobilenodes can move in a given topology,

receive/transmit signals from/to wirelesschannels•Wireless network stack consists of LL, ARP,

MAC, IFQ etc•Allows simulations of multi-hop ad hoc

networks, wireless LANs, sensor networks etc

3/29/2007 NCKU 182

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

3/29/2007 NCKU 183

An Example –Step 1

# Define Global Variables# create simulatorset ns [new Simulator]

# create a flat topology in a 670m x 670mareaset topo [new Topography]$topo load_flatgrid 670 670

3/29/2007 NCKU 184

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

3/29/2007 NCKU 185

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>

3/29/2007 NCKU 186

Example –Step 3

•Create Godset god [create-god 3]$ns at 900.00 “$god set-dist 2 3 1”

3/29/2007 NCKU 187

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

3/29/2007 NCKU 188

An Example –Step 5# Next create a mobile node, attach it to thechannelset 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

}

3/29/2007 NCKU 189

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

3/29/2007 NCKU 190

Scenario Generator:Movement

•Mobile Movement Generatorsetdestsetdest --n <num_of_nodes>n <num_of_nodes> --pp pausetimepausetime --ss<<maxspeedmaxspeed>> --t <t <simtimesimtime>> --x <x <maxxmaxx>> --yy<<maxymaxy>>

Source: nsns--2/indep2/indep--utils/cmuutils/cmu--scenscen--gen/setdest/gen/setdest/

•Random movement•$node random-motion 1••$node start$node start

3/29/2007 NCKU 191

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"

3/29/2007 NCKU 192

Scenario Generator: Traffic

•Generating traffic pattern files•CBR/TCP trafficnsns cbrgencbrgen..tcltcl [[--typetype cbrcbr||tcptcp] [] [--nnnn nodes] [nodes] [--seedseedseed] [seed] [--mc connections] [mc connections] [--rate rate]rate rate]

••CBR trafficCBR trafficnsns cbrgencbrgen..tcltcl ––typetype cbrcbr ––nnnn 2020 ––seed 1seed 1 ––mc 8mc 8 --rate 4rate 4

•TCP trafficnsns cbrgencbrgen..tcltcl ––typetype tcptcp --nnnn 1515 --seed 0seed 0 ––mc 6mc 6

•Source: nsns--2/indep2/indep--utils/cmuutils/cmu--scenscen--gen/gen/

3/29/2007 NCKU 193

A Traffic Scenario

set 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"…….

3/29/2007 NCKU 194

An Example –Step 6

# Define node movement modelsource <movement-scenario-files>

# Define traffic modelsource <traffic-scenario-files>

3/29/2007 NCKU 195

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

3/29/2007 NCKU 196

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

3/29/2007 NCKU 197

nam Visualization

•Use nam to visualize:•Mobile node position•Mobile node moving direction and speed•Energy consumption at nodes (color keyed)

3/29/2007 NCKU 198

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]

3/29/2007 NCKU 199

Wireless support in ns-2

•Introduction•Wireless basics•Wireless internals

•Ad hoc routing•Mobile IP•Satellite networking•Directed diffusion

3/29/2007 NCKU 200

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

3/29/2007 NCKU 201

Portrait of A Mobile Node

Node

ARP

Propagationand antennamodels

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

3/29/2007 NCKU 202

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

3/29/2007 NCKU 203

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

3/29/2007 NCKU 204

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

3/29/2007 NCKU 205

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

3/29/2007 NCKU 206

Wireless Channel

•Duplicate packets to all mobile nodesattached 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

3/29/2007 NCKU 207

Grid-keeper: AnOptimization

3/29/2007 NCKU 208

Mobile Node: Misc.

•Energy consumption model for sensornetworks•Visualization of node movement,

reachability, and energy•Validation test suites

3/29/2007 NCKU 209

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 wirelessformats

3/29/2007 NCKU 210

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••UnderUnder tcltcl/test/test/test/test--suitesuite--wirelesswireless--lanlan--newnodenewnode..tcltcl (tests: DSDV(tests: DSDV--wiredwired--cumcum--wireless andwireless andDSDVDSDV--wirelesswireless--mipmip))

3/29/2007 NCKU 212

A Brief on SatelliteNetworking

•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 andandtcltcl/test/test/test/test--suitesuite--satellite.satellite.tcltcl

3/29/2007 NCKU 213

Simulate sensor networkwith ns-2

•Currently support•Routing•Direct diffusion

•MAC•SMAC

3/29/2007 NCKU 214

Sensor network

•Wireless sensor network•Special ad hoc wireless network•Large number of nodes w/ sensors & actuators•Battery-powered nodes energy efficiency•Unplanned deployment self-organization•Node density & topology change robustness

•Sensor-net applications• Nodes cooperate for a common task• In-network data processing

3/29/2007 NCKU 215

Introduction to DirectDiffusion

•Properties of Sensor Networks•Data centric, but not node centric•Have no notion of central authority•Are often resource constrained

•Nodes are tied to physical locations, but:•They may not know the topology•They may fail or move arbitrarily

•Problem: How can we get data from thesensors?

3/29/2007 NCKU 216

Basic idea of DirectedDiffusion

•Data centric –nodes are unimportant•Request driven:•Sinks place requests as interests•Sources are eventually found and satisfy interests•Intermediate nodes route data toward sinks

•Localized repair and reinforcement•Multi-path delivery for multiple sources, sinks,

and queries

3/29/2007 NCKU 217

A toy example

•Sensor nodes are monitoring a flat spacefor animals•We are interested in receiving data for all

4-legged creatures seen in a rectanglearea•We want to specify the data rate

3/29/2007 NCKU 218

Interest and Event Naming

•Sink: Query/interest:• Type=four-legged animal• Interval=20ms (event data rate)• Duration=10 seconds (time to cache)• Rect=[-100, 100, 200, 400]

•Source: Reply:• Type=four-legged animal• Instance = elephant• Location = [125, 220]• Confidence = 0.85• Timestamp = 01:20:40

•Attribute-Value pairs, no advanced namingscheme

3/29/2007 NCKU 219

Diffusion (High Level)

•Sinks broadcast interest to neighbors•Interests are cached by neighbors•Gradients are set up pointing back to

where interests came from at low datarate•Once a source receives an interest, it

routes measurements along gradients

3/29/2007 NCKU 220

Gradients

•Gradients from Source (S) to Sink (N) areinitially small•Increased during reinforcement to find the

best path•How gradients are increased/decreased

based on only local rules•Application-specfic

3/29/2007 NCKU 221

Interest Propagation

• Flooding• Constrained or Directional flooding based on location.• Directional Propagation based on previously cached data.

Source

Sink

Interest

Gradient

3/29/2007 NCKU 222

Directed Diffusion (Data)

•The source matches signature waveforms fromcodebook against observations

•The source matches data against interest cache,compute highest event rate request from all gradients,and (re) sample events at this rate

• Intermediate node:•Finds matching entry in interest cache, no match –silent drop•Checks and updates data cache (loop prevention, aggregation)•Retrieve all gradients, and resend message, doing frequency

conversion if necessary

3/29/2007 NCKU 223

Data Propagation

• Reinforcement to single path delivery.

• Multipath delivery with probabilistic forwarding.

• Multipath delivery with selective quality along different path.

Source

Sink

Gradient

Data

3/29/2007 NCKU 224

Directed Diffusion(Reinforcement)

•Reinforcement:•Sink/intermediate nodes pick a neighbor based on

some local rules and increase the gradient (e.g.higher event rates)•This neighbor, in turn, reinforces upstream nodes•Passive reinforcement handling (timeout) or active

(weights)•Multiple sinks: Exploit prior setup (i.e., use cache)• Intermediate nodes use reinforcement for local repair

3/29/2007 NCKU 225

Local rules

•Which neighbor ?•Neighbor(s) from whom new events received.•Neighbor who’s consistently performing better than others.•Neighbor from whom most events received.

Reinforce one of the neighbor after receiving initial data.

Source

Sink

Gradient

Data

Reinforcement

3/29/2007 NCKU 226

Negative Reinforcement

• Time out• Explicitly Degrade the path by re-sending interest with lower data

rate.

Source

Sink

Gradient

Data

Reinforcement

3/29/2007 NCKU 227

A Brief on DirectedDiffusion

•Developed by SCADDS group at USC/ISI•Diffusion model in ns consists of•A core diffusion layer•A library of APIs for diffusion applications•Add-on filters (for gradient routing, logging, tagging,

srcrtg, GEAR etc)

•Much in development•Source code in ~ns/diffusion3

•Examples under tcl/ex/diffusion3 and test/test-suite-diffusion3.tcl

3/29/2007 NCKU 228

Medium Access Control inSensor Nets

• Important attributes of MAC protocols• Collision avoidance• Energy efficiency• Scalability in node density• Latency• Fairness• Throughput• Bandwidth utilization

Primary

Secondary

3/29/2007 NCKU 229

•Major sources of energy waste•Idle listening•Energy consumption of typical 802.11 WLAN cards•idle:receive — 1:1.05 to 1:2 (Stemm 1997)

Energy Efficiency in MAC

3/29/2007 NCKU 230

•Major sources of energy waste (cont.)•Idle listening•Long idle time when no sensing event happens

• Collisions• Control overhead• Overhearing

•We try to reduce energy consumption fromall above sources•Combine benefits of TDMA + contention

protocols

Energy Efficiency in MAC

Common to allwireless networks

Dominant in sensor nets

3/29/2007 NCKU 231

Sensor-MAC (S-MAC)Design

•Tradeoffs

•Major components in S-MAC• Periodic listen and sleep• Collision avoidance• Overhearing avoidance•Massage passing

LatencyFairness

Energy

3/29/2007 NCKU 232

Periodic Listen and Sleep

•Problem: Idle listening consumes significantenergy

•Solution: Periodic listen and sleep

• Turn off radio when sleeping• Reduce duty cycle to ~ 10% (200ms on/2s off)

sleeplisten listen sleep

Latency Energy

3/29/2007 NCKU 233

Periodic Listen and Sleep•Schedules can differ

• Prefer neighboring nodes have same schedule— easy broadcast & low control overhead

Border nodes:two schedulesbroadcast twice

Node 1

Node 2

sleeplisten listen sleep

sleeplisten listen sleep

Schedule 2

Schedule 1

3/29/2007 NCKU 234

Periodic Listen and Sleep

•Schedule Synchronization•Remember neighbors’ schedules • — to know when to send to them

•Each node broadcasts its schedule every fewperiods of sleeping and listening•Re-sync when receiving a schedule update•Schedule packets also serve as beacons for

new nodes to join a neighborhood

3/29/2007 NCKU 235

Collision Avoidance

•Problem: Multiple senders want to talk•Options: Contention vs. TDMA•Solution: Similar to IEEE 802.11 ad hoc

mode (DCF)•Physical and virtual carrier sense•Randomized backoff time•RTS/CTS for hidden terminal problem•RTS/CTS/DATA/ACK sequence

3/29/2007 NCKU 236

Overhearing Avoidance

•Problem: Receive packets destined toothers•Solution: Sleep when neighbors talk•use in-channel signaling

•Who should sleep?• All immediate neighbors of sender and receiver

•How long to sleep?• The duration field in each packet informs other

nodes the sleep interval

3/29/2007 NCKU 237

Message Passing

•Problem: Sensor net in-network processingrequires entire message

•Solution: Don’t interleave different messages•Long message is fragmented & sent in burst•RTS/CTS reserve medium for entire message•Fragment-level error recovery — ACK•— extend Tx time and re-transmit

immediately•Other nodes sleep for whole message time

Fairness EnergyMsg-level latency

3/29/2007 NCKU 238

Msg Passing vs. 802.11fragmentation

•S-MAC message passing

RTS 21 ......

Data 19ACK 18CTS 20

Data 17ACK 16

Data 1ACK 0

RTS 3 ......

Data 3ACK 2CTS 2

Data 3ACK 2

Data 1ACK 0

•Fragmentation in IEEE 802.11• No indication of entire time — other nodes keep listening• If ACK is not received, give up Tx — fairness

3/29/2007 NCKU 239

A brief on SMAC

•SMAC –MAC designed for sensornetworks•Similar RTS/CTS/DATA/ACK like 802.11•Additional sleep-wakeup cycles•Reduce energy consumptions during idle

phases•Examples under tcl/test/test-suite-

smac.tcl

3/29/2007 NCKU 240

Outline

•An introduction to ns-2•What is ns-2•Fundamentals•Writing ns-2 codes•Traces support and visualization•Wireless support•Emulation•Related work

3/29/2007 NCKU 241

What is Emulation ?

•Ability to introduce the simulator into alive network•Application:•Allows testing real-world implementations•Allows testing simulated protocols

•Requirements:•Scheduler support•Packet capture and generation capabilities

3/29/2007 NCKU 242

Emulation in ns-2

Read packets Write packets

ns

Network

3/29/2007 NCKU 243

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

3/29/2007 NCKU 244

Emulation Objects

•Interface between nsand 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

3/29/2007 NCKU 245

Modes of Operation

•Packet conversion leads to two modes ofoperation

•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

3/29/2007 NCKU 246

Opaque Mode•Network packet is passed unmodified

through simulator

Network Packet

SourceDestination

Size

Data

Ns packet containsa pointer to thenetwork packet

SourceDestination

Size

Extern

Read packets Write packets

ns

Network

3/29/2007 NCKU 247

Protocol Mode

•Network packet fields are generated bythe simulator

Data

The ns packetheader is

mapped onto thenetwork packetheader and visa

versa .

Send/receivepackets fromapplication

ns

TCP Agent

Network

Host A

TCPApplication

Host B

Send/receivepackets from

ns

Network Packet

SourceDestination

Size

SourceDestination

Size

3/29/2007 NCKU 248

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

3/29/2007 NCKU 249

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 6000to TCP agent

• Add route to dummy IPaddress

• 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

3/29/2007 NCKU 250

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 andChange to real-timescheduler

Create topology

Create TCP Agent

TCP Agent

tcp_node entry_node

RawSocket

BPFTCPTap

TCPTap

3/29/2007 NCKU 251

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

3/29/2007 NCKU 252

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

3/29/2007 NCKU 253

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

3/29/2007 NCKU 254

Ns-2 related work

•Other simulators•Researching uses ns-2•Using ns-2 for education

3/29/2007 NCKU 255

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

3/29/2007 NCKU 256

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

3/29/2007 NCKU 257

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

3/29/2007 NCKU 258

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

top related