12.07.2015 Views

The ns Manual (formerly ns Notes and Documentation)1 - NM Lab at ...

The ns Manual (formerly ns Notes and Documentation)1 - NM Lab at ...

The ns Manual (formerly ns Notes and Documentation)1 - NM Lab at ...

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

18 Radio Propag<strong>at</strong>ion Models 17718.1 Free space model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17718.2 Two-ray ground reflection model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17818.3 Shadowing model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17818.3.1 Backgroud . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17818.3.2 Using shadowing model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18018.4 Communic<strong>at</strong>ion range . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18018.5 Comm<strong>and</strong>s <strong>at</strong> a glance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18119 Energy Model in <strong>ns</strong> 18219.1 <strong>The</strong> C++ EnergyModel Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18219.2 <strong>The</strong> OTcl interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18320 Directed Diffusion 18420.1 Wh<strong>at</strong> is Directed Diffusion? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18420.2 <strong>The</strong> diffusion model in <strong>ns</strong> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18420.3 Some mac issues for diffusion in <strong>ns</strong> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18520.4 APIs for using filters in diffusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18620.5 Ping: an example diffusion applic<strong>at</strong>ion implement<strong>at</strong>ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18620.5.1 Ping Applic<strong>at</strong>ion as implemented in C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18620.5.2 Tcl APIs for the ping applic<strong>at</strong>ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18720.6 Changes required to add yr diffusion applic<strong>at</strong>ion to <strong>ns</strong> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18720.7 Test-suites for diffusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18920.8 Comm<strong>and</strong>s <strong>at</strong> a glance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18921 XCP: eXplicit Congestion control Protocol 19121.1 Wh<strong>at</strong> is XCP? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19121.2 Implement<strong>at</strong>ion of XCP in NS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19221.2.1 Endpoints in XCP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19221.2.2 XCP Router . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19321.2.3 XCP queue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19321.3 XCP example script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19421.4 Test-suites for XCP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19721.5 Comm<strong>and</strong>s <strong>at</strong> a glance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19722 DelayBox: Per-Flow Delay <strong>and</strong> Loss 19822.1 Implement<strong>at</strong>ion Details . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19822.2 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19922.3 Comm<strong>and</strong>s <strong>at</strong> a Glance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20023 Changes made to the IEEE 802.15.4 Implement<strong>at</strong>ion in NS-2.31 20223.1 Radio shutdown . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20223.2 Other changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203III Support 20424 Debugging <strong>ns</strong> 20524.1 Tcl-level Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20524.2 C++-Level Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20524.3 Mixing Tcl <strong>and</strong> C debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20624.4 Memory Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20724.4.1 Using dmalloc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20724.4.2 Memory Co<strong>ns</strong>erv<strong>at</strong>ion Tips . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20824.4.3 Some st<strong>at</strong>istics collected by dmalloc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2085


24.5 Memory Leaks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20824.5.1 OTcl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20924.5.2 C/C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20925 M<strong>at</strong>hem<strong>at</strong>ical Support 21025.1 R<strong>and</strong>om Number Gener<strong>at</strong>ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21025.1.1 Seeding <strong>The</strong> RNG . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21125.1.2 OTcl Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21325.1.3 C++ Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21425.2 R<strong>and</strong>om Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21525.3 Integrals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21625.4 <strong>ns</strong>-r<strong>and</strong>om . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21725.5 Some m<strong>at</strong>hem<strong>at</strong>ical-support rel<strong>at</strong>ed objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21825.6 Comm<strong>and</strong>s <strong>at</strong> a glance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21826 Trace <strong>and</strong> Monitoring Support 22026.1 Trace Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22026.1.1 OTcl Helper Functio<strong>ns</strong> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22126.2 Library support <strong>and</strong> examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22226.3 <strong>The</strong> C++ Trace Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22426.4 Trace File Form<strong>at</strong> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22526.5 Packet Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22726.6 Queue Monitoring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22826.7 Per-Flow Monitoring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23026.7.1 <strong>The</strong> Flow Monitor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23026.7.2 Flow Monitor Trace Form<strong>at</strong> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23026.7.3 <strong>The</strong> Flow Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23126.8 Comm<strong>and</strong>s <strong>at</strong> a glance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23127 Test Suite Support 23427.1 Test Suite Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23427.2 Write a Test Suite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23428 <strong>ns</strong> Code Styles 23728.1 Indent<strong>at</strong>ion style . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23728.2 Variable Naming Conventio<strong>ns</strong> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23728.3 Miscellaneous . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237IV Routing 23929 Unicast Routing 24029.1 <strong>The</strong> Interface to the Simul<strong>at</strong>ion Oper<strong>at</strong>or (<strong>The</strong> API) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24029.2 Other Configur<strong>at</strong>ion Mechanisms for Specialised Routing . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24129.3 Protocol Specific Configur<strong>at</strong>ion Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24229.4 Internals <strong>and</strong> Architecture of Routing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24329.4.1 <strong>The</strong> classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24329.4.2 Interface to Network Dynamics <strong>and</strong> Multicast . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24729.5 Protocol Internals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24829.6 Unicast routing objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24929.7 Comm<strong>and</strong>s <strong>at</strong> a glance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2496


30 Multicast Routing 25130.1 Multicast API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25130.1.1 Multicast Behavior Monitor Configur<strong>at</strong>ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25230.1.2 Protocol Specific configur<strong>at</strong>ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25330.2 Internals of Multicast Routing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25430.2.1 <strong>The</strong> classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25430.2.2 Exte<strong>ns</strong>io<strong>ns</strong> to other classes in <strong>ns</strong> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25630.2.3 Protocol Internals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25930.2.4 <strong>The</strong> internal variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26130.3 Comm<strong>and</strong>s <strong>at</strong> a glance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26131 Network Dynamics 26431.1 <strong>The</strong> user level API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26431.2 <strong>The</strong> Internal Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26631.2.1 <strong>The</strong> class rtModel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26631.2.2 class rtQueue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26731.3 Interaction with Unicast Routing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26831.3.1 Exte<strong>ns</strong>io<strong>ns</strong> to Other Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26831.4 Deficencies in the Current Network Dynamics API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26931.5 Comm<strong>and</strong>s <strong>at</strong> a glance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26932 Hierarchical Routing 27132.1 Overview of Hierarchical Routing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27132.2 Usage of Hierarchical routing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27132.3 Cre<strong>at</strong>ing large Hierarchical topologies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27332.4 Hierarchical Routing with SessionSim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27432.5 Comm<strong>and</strong>s <strong>at</strong> a glance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274V Tra<strong>ns</strong>port 27533 UDP Agents 27633.1 UDP Agents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27633.2 Comm<strong>and</strong>s <strong>at</strong> a glance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27734 TCP Agents 27834.1 One-Way TCP Senders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27934.1.1 <strong>The</strong> Base TCP Sender (Tahoe TCP) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27934.1.2 Configur<strong>at</strong>ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27934.1.3 Simple Configur<strong>at</strong>ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27934.1.4 Other Configur<strong>at</strong>ion Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28034.1.5 Other One-Way TCP Senders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28134.2 TCP Receivers (sinks) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28134.2.1 <strong>The</strong> Base TCP Sink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28234.2.2 Delayed-ACK TCP Sink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28234.2.3 Sack TCP Sink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28234.3 Two-Way TCP Agents (FullTcp) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28234.3.1 Simple Configur<strong>at</strong>ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28334.3.2 BayFullTcp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28434.4 Architecture <strong>and</strong> Internals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28434.5 Tracing TCP Dynamics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28634.6 One-Way Trace TCP Trace Dynamics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28634.7 One-Way Trace TCP Trace Dynamics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28634.8 Comm<strong>and</strong>s <strong>at</strong> a glance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2867


35 SCTP Agents 28835.1 <strong>The</strong> Base SCTP Agent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28835.1.1 Configur<strong>at</strong>ion Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28935.1.2 Comm<strong>and</strong>s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29135.2 Exte<strong>ns</strong>io<strong>ns</strong> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29235.2.1 HbAfterRto SCTP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29235.2.2 MultipleFastRtx SCTP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29235.2.3 Timestamp SCTP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29335.2.4 MfrHbAfterRto SCTP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29335.2.5 MfrHbAfterRto SCTP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29335.3 Tracing SCTP Dynamics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29335.4 SCTP Applic<strong>at</strong>io<strong>ns</strong> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29435.5 Example Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29535.5.1 Singled Homed Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29535.5.2 Multihomed Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29636 Agent/SRM 29836.1 Configur<strong>at</strong>ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29836.1.1 Trivial Configur<strong>at</strong>ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29836.1.2 Other Configur<strong>at</strong>ion Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30036.1.3 St<strong>at</strong>istics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30136.1.4 Tracing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30236.2 Architecture <strong>and</strong> Internals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30436.3 Packet H<strong>and</strong>ling: Processing received messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30436.4 Loss Detection—<strong>The</strong> Class SRMinfo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30636.5 Loss Recovery Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30636.6 Session Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30836.7 Extending the Base Class Agent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30936.7.1 Fixed Timers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30936.7.2 Adaptive Timers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30936.8 SRM objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31036.9 Comm<strong>and</strong>s <strong>at</strong> a glance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31137 PLM 31337.1 Configur<strong>at</strong>ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31337.2 <strong>The</strong> Packet Pair Source Gener<strong>at</strong>or . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31537.3 Architecture of the PLM Protocol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31637.3.1 I<strong>ns</strong>tanti<strong>at</strong>ion of a PLM Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31637.3.2 I<strong>ns</strong>tanti<strong>at</strong>ion of a PLM Receiver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31637.3.3 Reception of a Packet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31737.3.4 Detection of a Loss . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31837.3.5 Joining or Leaving a Layer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31837.4 Comm<strong>and</strong>s <strong>at</strong> a Glance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318VI Applic<strong>at</strong>ion 32038 Applic<strong>at</strong>io<strong>ns</strong> <strong>and</strong> tra<strong>ns</strong>port agent API 32138.1 <strong>The</strong> class Applic<strong>at</strong>ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32138.2 <strong>The</strong> tra<strong>ns</strong>port agent API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32238.2.1 Attaching tra<strong>ns</strong>port agents to nodes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32238.2.2 Attaching applic<strong>at</strong>io<strong>ns</strong> to agents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32338.2.3 Using tra<strong>ns</strong>port agents via system calls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32338.2.4 Agent upcalls to applic<strong>at</strong>io<strong>ns</strong> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3238


38.2.5 An example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32438.3 <strong>The</strong> class TrafficGener<strong>at</strong>or . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32538.3.1 An example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32738.4 Simul<strong>at</strong>ed applic<strong>at</strong>io<strong>ns</strong>: Telnet <strong>and</strong> FTP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32838.5 Applic<strong>at</strong>io<strong>ns</strong> objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32838.6 Comm<strong>and</strong>s <strong>at</strong> a glance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33039 Web cache as an applic<strong>at</strong>ion 33139.1 Using applic<strong>at</strong>ion-level d<strong>at</strong>a in <strong>ns</strong> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33139.1.1 ADU . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33139.1.2 Passing d<strong>at</strong>a between applic<strong>at</strong>io<strong>ns</strong> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33239.1.3 Tra<strong>ns</strong>mitting user d<strong>at</strong>a over UDP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33339.1.4 Tra<strong>ns</strong>mitting user d<strong>at</strong>a over TCP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33439.1.5 Class hierarchy rel<strong>at</strong>ed to user d<strong>at</strong>a h<strong>and</strong>ling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33539.2 Overview of web cache classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33539.2.1 Managing HTTP connectio<strong>ns</strong> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33539.2.2 Managing web pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33639.2.3 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33739.3 Representing web pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33739.4 Page pools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33839.4.1 PagePool/M<strong>at</strong>h . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33839.4.2 PagePool/CompM<strong>at</strong>h . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33939.4.3 PagePool/ProxyTrace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33939.4.4 PagePool/Client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34039.4.5 PagePool/WebTraf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34039.5 Web client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34239.6 Web server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34339.7 Web cache . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34439.7.1 Http/Cache . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34439.8 Putting together: a simple example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34539.9 Http trace form<strong>at</strong> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34739.10Comm<strong>and</strong>s <strong>at</strong> a glance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34840 Worm Model 35040.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35040.2 Configur<strong>at</strong>ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35140.3 Comm<strong>and</strong>s <strong>at</strong> a glance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35141 PackMime-HTTP: Web Traffic Gener<strong>at</strong>ion 35341.1 Implement<strong>at</strong>ion Details . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35341.1.1 PackMimeHTTP Client Applic<strong>at</strong>ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35441.1.2 PackMimeHTTP Server Applic<strong>at</strong>ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35541.2 PackMimeHTTP R<strong>and</strong>om Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35541.3 Use of DelayBox with PackMime-HTTP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35641.4 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35641.5 Comm<strong>and</strong>s <strong>at</strong> a Glance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358VII Scale 36142 Session-level Packet Distribution 36242.1 Configur<strong>at</strong>ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36242.1.1 Basic Configur<strong>at</strong>ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36242.1.2 I<strong>ns</strong>erting a Loss Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36442.2 Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3649


42.3 Internals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36542.3.1 Object Linkage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36542.3.2 Packet Forwarding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36642.4 Comm<strong>and</strong>s <strong>at</strong> a glance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36743 Asim: approxim<strong>at</strong>e analytical simul<strong>at</strong>ion 368VIII Emul<strong>at</strong>ion 37244 Emul<strong>at</strong>ion 37344.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37344.2 Real-Time Scheduler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37444.3 Tap Agents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37444.4 Network Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37544.4.1 Pcap/BPF Network Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37544.4.2 IP Network Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37644.4.3 IP/UDP Network Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37644.5 An Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37744.6 Comm<strong>and</strong>s <strong>at</strong> a glance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 378IX Visualiz<strong>at</strong>ion with Nam - <strong>The</strong> Network Anim<strong>at</strong>or 37945 Nam 38045.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38045.2 Nam Comm<strong>and</strong> Line Optio<strong>ns</strong> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38045.3 User Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38145.4 Keyboard Comm<strong>and</strong>s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38245.5 Gener<strong>at</strong>ing External Anim<strong>at</strong>io<strong>ns</strong> from Nam . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38345.6 Network Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38345.7 Anim<strong>at</strong>ion Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38446 Nam Trace 38546.1 Nam Trace Form<strong>at</strong> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38546.1.1 Initializ<strong>at</strong>ion Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38646.1.2 Nodes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38746.1.3 Links . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38746.1.4 Queues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38846.1.5 Packets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38846.1.6 Node Marking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38946.1.7 Agent Tracing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39046.1.8 Variable Tracing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39046.1.9 Executing Tcl Procedures <strong>and</strong> External Code from within Nam . . . . . . . . . . . . . . . . . . . . . 39046.1.10 Using Streams for Realtime Applic<strong>at</strong>io<strong>ns</strong> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39246.1.11 Nam Trace File Form<strong>at</strong> Lookup Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39546.2 Ns comm<strong>and</strong>s for cre<strong>at</strong>ing <strong>and</strong> controlling nam anim<strong>at</strong>io<strong>ns</strong> . . . . . . . . . . . . . . . . . . . . . . . . . . . 40146.2.1 Node . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40146.2.2 Link/Queue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40146.2.3 Agent <strong>and</strong> Fe<strong>at</strong>ures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40246.2.4 Some Generic Comm<strong>and</strong>s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40210


X Other 40347 Educ<strong>at</strong>ional use of NS <strong>and</strong> NAM 40447.1 Using NS for educ<strong>at</strong>ional purposes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40447.1.1 I<strong>ns</strong>talling/building/running <strong>ns</strong> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40447.1.2 <strong>The</strong> educ<strong>at</strong>ional scripts’ inventory page: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40447.2 Using NAM for educ<strong>at</strong>ional purposes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40511


Chapter 1IntroductionLet’s start <strong>at</strong> the very beginning,a very nice place to start,when you sing, you begin with A, B, C,when you simul<strong>at</strong>e, you begin with the topology, 1. . .This document (<strong>ns</strong> <strong>Notes</strong> <strong>and</strong> <strong>Document<strong>at</strong>ion</strong>) provides reference document<strong>at</strong>ion for <strong>ns</strong>. Although we begin with a simplesimul<strong>at</strong>ion script, resources like Marc Greis’s tutorial web pages (originally <strong>at</strong> his web site, now <strong>at</strong> http://www.isi.edu/<strong>ns</strong>nam/<strong>ns</strong>/tutorial/) or the slides from one of the <strong>ns</strong> tutorials are problably better places to begin for the <strong>ns</strong>novice.We first begin by showing a simple simul<strong>at</strong>ion script. This script is also available in the sources in ~<strong>ns</strong>/tcl/ex/simple.tcl.This script defines a simple topology of four nodes, <strong>and</strong> two agents, a UDP agent with a CBR traffic gener<strong>at</strong>or, <strong>and</strong> a TCPagent. <strong>The</strong> simul<strong>at</strong>ion ru<strong>ns</strong> for 3s. <strong>The</strong> output is two trace files, out.tr <strong>and</strong> out.nam. When the simul<strong>at</strong>ion completes <strong>at</strong>the end of 3s, it will <strong>at</strong>tempt to run a nam visualis<strong>at</strong>ion of the simul<strong>at</strong>ion on your screen.# <strong>The</strong> preambleset <strong>ns</strong> [new Simul<strong>at</strong>or];# initialise the simul<strong>at</strong>ion# Predefine tracingset f [open out.tr w]$<strong>ns</strong> trace-all $fset nf [open out.nam w]$<strong>ns</strong> namtrace-all $nf1 with apologies to Rodgers <strong>and</strong> Hammerstein12


# so, we lied. now, we define the topology## n0# \# 5Mb \# 2ms \# \# n2 --------- n3# / 1.5Mb# 5Mb / 10ms# 2ms /# /# n1#set n0 [$<strong>ns</strong> node]set n1 [$<strong>ns</strong> node]set n2 [$<strong>ns</strong> node]set n3 [$<strong>ns</strong> node]$<strong>ns</strong> duplex-link $n0 $n2 5Mb 2ms DropTail$<strong>ns</strong> duplex-link $n1 $n2 5Mb 2ms DropTail$<strong>ns</strong> duplex-link $n2 $n3 1.5Mb 10ms DropTail# Some agents.set udp0 [new Agent/UDP];# A UDP agent$<strong>ns</strong> <strong>at</strong>tach-agent $n0 $udp0 ;# on node $n0set cbr0 [new Applic<strong>at</strong>ion/Traffic/CBR];# A CBR traffic gener<strong>at</strong>or agent$cbr0 <strong>at</strong>tach-agent $udp0;# <strong>at</strong>tached to the UDP agent$udp0 set class_ 0 ;# actually, the default, but. . .set null0 [new Agent/Null];# Its sink$<strong>ns</strong> <strong>at</strong>tach-agent $n3 $null0 ;# on node $n3$<strong>ns</strong> connect $udp0 $null0$<strong>ns</strong> <strong>at</strong> 1.0 "$cbr0 start"puts [$cbr0 set packetSize_]puts [$cbr0 set interval_]# A FTP over TCP/Tahoe from $n1 to $n3, flowid 2set tcp [new Agent/TCP]$tcp set class_ 1$<strong>ns</strong> <strong>at</strong>tach-agent $n1 $tcpset sink [new Agent/TCPSink]$<strong>ns</strong> <strong>at</strong>tach-agent $n3 $sinkset ftp [new Applic<strong>at</strong>ion/FTP]$ftp <strong>at</strong>tach-agent $tcp$<strong>ns</strong> <strong>at</strong> 1.2 "$ftp start";# TCP does not gener<strong>at</strong>e its own traffic$<strong>ns</strong> connect $tcp $sink$<strong>ns</strong> <strong>at</strong> 1.35 "$<strong>ns</strong> detach-agent $n0 $tcp ; $<strong>ns</strong> detach-agent $n3 $sink"13


# <strong>The</strong> simul<strong>at</strong>ion ru<strong>ns</strong> for 3s.# <strong>The</strong> simul<strong>at</strong>ion comes to an end when the scheduler invokes the finish{} procedure below.# This procedure closes all trace files, <strong>and</strong> invokes nam visualiz<strong>at</strong>ion on one of the trace files.$<strong>ns</strong> <strong>at</strong> 3.0 "finish"proc finish {} {global <strong>ns</strong> f nf$<strong>ns</strong> flush-traceclose $fclose $nf}puts "running nam..."exec nam out.nam &exit 0# Finally, start the simul<strong>at</strong>ion.$<strong>ns</strong> run15


Chapter 2Undocumented FacilitiesNs is often growing to include new protocols. Unfortun<strong>at</strong>ely the documention doesn’t grow quite as often. This section listswh<strong>at</strong> remai<strong>ns</strong> to be documented, or wh<strong>at</strong> needs to be improved.(<strong>The</strong> document<strong>at</strong>ion is in the doc subdirectory of the <strong>ns</strong> source code if you want to add to it. :-)Interface to the Interpreter• nothing currentlySimul<strong>at</strong>or BasicsSupportRoutingQueueingTra<strong>ns</strong>port• LANs need to be upd<strong>at</strong>ed for new wired/wireless support (Yuri upd<strong>at</strong>ed this?)• wireless support needs to be added (done)• should explicitly list queueing optio<strong>ns</strong> in the queue mgt chapter?• should pick a single list mgt package <strong>and</strong> document it• should document the trace-post-processing utilities in bin• <strong>The</strong> usage <strong>and</strong> design of link st<strong>at</strong>e <strong>and</strong> MPLS routing modules are not documented <strong>at</strong> all. (Note: link st<strong>at</strong>e <strong>and</strong>MPLS appeared only in daily snapshots <strong>and</strong> releases after 09/14/2000.)• need to document hierarchical routing/addressing (Padma has done)• need a chapter on supported ad-hoc routing protocols• CBQ needs document<strong>at</strong>ion (can maybe build off of ftp://ftp.ee.lbl.gov/papers/cbqsims.ps.Z?)• need to document MFTP• need to document RTP (session-rtp.cc, etc.)• need to document multicast building blocks• should repair <strong>and</strong> document snoop <strong>and</strong> tcp-intTraffic <strong>and</strong> scenarios (new section)• should add a description of how to drive the simul<strong>at</strong>or from traces• should add discussion of the scenario gener<strong>at</strong>or• should add discussion of http traffic sourcesApplic<strong>at</strong>ion• is the non-Haobo http stuff documented? no.16


Scale• should add disucssion of mixed mode (pending)Emul<strong>at</strong>ion• nothing currentlyOther• should document admission control policies?• should add a valid<strong>at</strong>ion chapter <strong>and</strong> snarf up the contents of <strong>ns</strong>-tests.html• should snarf up Marc Greis’ tutorial r<strong>at</strong>her than just referring to it?17


Part IInterface to the Interpreter18


Chapter 3OTcl Linkage<strong>ns</strong> is an object oriented simul<strong>at</strong>or, written in C++, with an OTcl interpreter as a frontend. <strong>The</strong> simul<strong>at</strong>or supports a classhierarchy in C++ (also called the compiled hierarchy in this document), <strong>and</strong> a similar class hierarchy within the OTcl interpreter(also called the interpreted hierarchy in this document). <strong>The</strong> two hierarchies are closely rel<strong>at</strong>ed to each other; from theuser’s perspective, there is a one-to-one correspondence between a class in the interpreted hierarchy <strong>and</strong> one in the compiledhierarchy. <strong>The</strong> root of this hierarchy is the class TclObject. Users cre<strong>at</strong>e new simul<strong>at</strong>or objects through the interpreter; theseobjects are i<strong>ns</strong>tanti<strong>at</strong>ed within the interpreter, <strong>and</strong> are closely mirrored by a corresponding object in the compiled hierarchy.<strong>The</strong> interpreted class hierarchy is autom<strong>at</strong>ically established through methods defined in the class TclClass. user i<strong>ns</strong>tanti<strong>at</strong>edobjects are mirrored through methods defined in the class TclObject. <strong>The</strong>re are other hierarchies in the C++ code <strong>and</strong> OTclscripts; these other hierarchies are not mirrored in the manner of TclObject.3.1 Concept OverviewWhy two languages? <strong>ns</strong> uses two languages because simul<strong>at</strong>or has two different kinds of things it needs to do. On one h<strong>and</strong>,detailed simul<strong>at</strong>io<strong>ns</strong> of protocols requires a systems programming language which can efficiently manipul<strong>at</strong>e bytes, packetheaders, <strong>and</strong> implement algorithms th<strong>at</strong> run over large d<strong>at</strong>a sets. For these tasks run-time speed is important <strong>and</strong> turn-aroundtime (run simul<strong>at</strong>ion, find bug, fix bug, recompile, re-run) is less important.On the other h<strong>and</strong>, a large part of network research involves slightly varying parameters or configur<strong>at</strong>io<strong>ns</strong>, or quickly exploringa number of scenarios. In these cases, iter<strong>at</strong>ion time (change the model <strong>and</strong> re-run) is more important. Since configur<strong>at</strong>ionru<strong>ns</strong> once (<strong>at</strong> the beginning of the simul<strong>at</strong>ion), run-time of this part of the task is less important.<strong>ns</strong> meets both of these needs with two languages, C++ <strong>and</strong> OTcl. C++ is fast to run but slower to change, making it suitablefor detailed protocol implement<strong>at</strong>ion. OTcl ru<strong>ns</strong> much slower but can be changed very quickly (<strong>and</strong> interactively), making itideal for simul<strong>at</strong>ion configur<strong>at</strong>ion. <strong>ns</strong> (via tclcl) provides glue to make objects <strong>and</strong> variables appear on both langauges.For more inform<strong>at</strong>ion about the idea of scripting languages <strong>and</strong> split-language programming, see Ousterhout’s article in IEEEComputer [26]. For more inform<strong>at</strong>ion about split level programming for network simul<strong>at</strong>ion, see the <strong>ns</strong> paper [2].Which language for wh<strong>at</strong>? Having two languages raises the question of which language should be used for wh<strong>at</strong> purpose.Our basic advice is to use OTcl:• for configur<strong>at</strong>ion, setup, <strong>and</strong> “one-time” stuff19


• if you can do wh<strong>at</strong> you want by manipul<strong>at</strong>ing existing C++ objects<strong>and</strong> use C++:• if you are doing anything th<strong>at</strong> requires processing each packet of a flow• if you have to change the behavior of an existing C++ class in ways th<strong>at</strong> weren’t anticip<strong>at</strong>edFor example, links are OTcl objects th<strong>at</strong> assemble delay, queueing, <strong>and</strong> possibly loss modules. If your experiment can bedone with those pieces, gre<strong>at</strong>. If i<strong>ns</strong>tead you want do something fancier (a special queueing dicipline or model of loss), thenyou’ll need a new C++ object.<strong>The</strong>re are certainly grey areas in this spectrum: most routing is done in OTcl (although the core Dijkstra algorithm is in C++).We’ve had HTTP simul<strong>at</strong>io<strong>ns</strong> where each flow was started in OTcl <strong>and</strong> per-packet processing was all in C++. This approacheworked OK until we had 100s of flows starting per second of simul<strong>at</strong>ed time. In general, if you’re ever having to invoke Tclmany times per second, you problably should move th<strong>at</strong> code to C++.3.2 Code OverviewIn this document, we use the term “interpreter” to be synonymous with the OTcl interpreter. <strong>The</strong> code to interface with theinterpreter resides in a separ<strong>at</strong>e directory, tclcl. <strong>The</strong> rest of the simul<strong>at</strong>or code resides in the directory, <strong>ns</strong>-2. We will usethe not<strong>at</strong>ion ~tclcl/〈file〉 to refer to a particular 〈file〉 in the Tcl directory. Similarly, we will use the not<strong>at</strong>ion, ~<strong>ns</strong>/〈file〉 torefer to a particular 〈file〉 in the <strong>ns</strong>-2 directory.<strong>The</strong>re are a number of classes defined in ~tclcl/. We only focus on the six th<strong>at</strong> are used in <strong>ns</strong>: <strong>The</strong> Class Tcl (Section 3.3)contai<strong>ns</strong> the methods th<strong>at</strong> C++ code will use to access the interpreter. <strong>The</strong> class TclObject (Section 3.4) is the base class forall simul<strong>at</strong>or objects th<strong>at</strong> are also mirrored in the compiled hierarchy. <strong>The</strong> class TclClass (Section 3.5) defines the interpretedclass hierarchy, <strong>and</strong> the methods to permit the user to i<strong>ns</strong>tanti<strong>at</strong>e TclObjects. <strong>The</strong> class TclComm<strong>and</strong> (Section 3.6) is used todefine simple global interpreter comm<strong>and</strong>s. <strong>The</strong> class EmbeddedTcl (Section 3.7) contai<strong>ns</strong> the methods to load higher levelbuiltin comm<strong>and</strong>s th<strong>at</strong> make configuring simul<strong>at</strong>io<strong>ns</strong> easier. Finally, the class I<strong>ns</strong>tVar (Section 3.8) contai<strong>ns</strong> methods to accessC++ member variables as OTcl i<strong>ns</strong>tance variables.<strong>The</strong> procedures <strong>and</strong> functio<strong>ns</strong> described in this chapter can be found in ~tclcl/Tcl.{cc, h}, ~tclcl/Tcl2.cc, ~tclcl/tcl-object.tcl,<strong>and</strong>, ~tclcl/tracedvar.{cc, h}. <strong>The</strong> file ~tclcl/tcl2c++.c is used in building <strong>ns</strong>, <strong>and</strong> is mentioned briefly in this chapter.3.3 Class Tcl<strong>The</strong> class Tcl encapsul<strong>at</strong>es the actual i<strong>ns</strong>tance of the OTcl interpreter, <strong>and</strong> provides the methods to access <strong>and</strong> communic<strong>at</strong>ewith th<strong>at</strong> interpreter. <strong>The</strong> methods described in this section are relevant to the <strong>ns</strong> programmer who is writing C++ code.<strong>The</strong> class provides methods for the following oper<strong>at</strong>io<strong>ns</strong>:• obtain a reference to the Tcl i<strong>ns</strong>tance;• invoke OTcl procedures through the interpreter;• retrieve, or pass back results to the interpreter;• report error situ<strong>at</strong>io<strong>ns</strong> <strong>and</strong> exit in an uniform manner; <strong>and</strong>20


• store <strong>and</strong> lookup “TclObjects”.• acquire direct access to the interpreter.We describe each of the methods in the following subsectio<strong>ns</strong>.3.3.1 Obtain a Reference to the class Tcl i<strong>ns</strong>tanceA single i<strong>ns</strong>tance of the class is declared in ~tclcl/Tcl.cc as a st<strong>at</strong>ic member variable; the programmer must obtain a referenceto this i<strong>ns</strong>tance to access other methods described in this section. <strong>The</strong> st<strong>at</strong>ement required to access this i<strong>ns</strong>tance is:Tcl& tcl = Tcl::i<strong>ns</strong>tance();3.3.2 Invoking OTcl Procedures<strong>The</strong>re are four different methods to invoke an OTcl comm<strong>and</strong> through the i<strong>ns</strong>tance, tcl. <strong>The</strong>y differ essentially in theircalling arguments. Each function passes a string to the interpreter, th<strong>at</strong> then evalu<strong>at</strong>es the string in a global context. <strong>The</strong>semethods will return to the caller if the interpreter retur<strong>ns</strong> TCL_OK. On the other h<strong>and</strong>, if the interpreter retur<strong>ns</strong> TCL_ERROR,the methods will call tkerror{}. <strong>The</strong> user can overload this procedure to selectively disregard certain types of errors. Suchintricacies of OTcl programming are outside the scope of this document. <strong>The</strong> next section (Section 3.3.3) describes methodsto access the result returned by the interpreter.• tcl.eval(char* s) invokes Tcl_GlobalEval() to execute s through the interpreter.• tcl.evalc(co<strong>ns</strong>t char* s) preserves the argument string s. It copies the string s into its internal buffer; it then invokesthe previous eval(char* s) on the internal buffer.• tcl.eval() assumes th<strong>at</strong> the comm<strong>and</strong> is already stored in the class’ internal bp_; it directly invokes tcl.eval(char*bp_). A h<strong>and</strong>le to the buffer itself is available through the method tcl.buffer(void).• tcl.evalf(co<strong>ns</strong>t char* s, . . . ) is a Printf(3) like equivalent. It uses vsprintf(3) internally to cre<strong>at</strong>e the inputstring.As an example, here are some of the ways of using the above methods:Tcl& tcl = Tcl::i<strong>ns</strong>tance();char wrk[128];strcpy(wrk, "Simul<strong>at</strong>or set NumberInterfaces_ 1");tcl.eval(wrk);sprintf(tcl.buffer(), "Agent/SRM set requestFunction_ %s", "Fixed");tcl.eval();tcl.evalc("puts stdout hello world");tcl.evalf("%s request %d %d", name_, sender, msgid);3.3.3 Passing Results to/from the InterpreterWhen the interpreter invokes a C++ method, it expects the result back in the priv<strong>at</strong>e member variable, tcl_->result. Twomethods are available to set this variable.21


• tcl.result(co<strong>ns</strong>t char* s)Pass the result string s back to the interpreter.• tcl.resultf(co<strong>ns</strong>t char* fmt, . . . )varargs(3) variant of above to form<strong>at</strong> the result using vsprintf(3), pass the result string back to the interpreter.if (strcmp(argv[1], "now") == 0) {tcl.resultf("%.17g", clock());return TCL_OK;}tcl.result("Invalid oper<strong>at</strong>ion specified");return TCL_ERROR;Likewise, when a C++ method invokes an OTcl comm<strong>and</strong>, the interpreter retur<strong>ns</strong> the result in tcl_->result.• tcl.result(void) must be used to retrieve the result. Note th<strong>at</strong> the result is a string, th<strong>at</strong> must be converted into aninternal form<strong>at</strong> appropri<strong>at</strong>e to the type of result.tcl.evalc("Simul<strong>at</strong>or set NumberInterfaces_");char* ni = tcl.result();if (<strong>at</strong>oi(ni) != 1)tcl.evalc("Simul<strong>at</strong>or set NumberInterfaces_ 1");3.3.4 Error Reporting <strong>and</strong> ExitThis method provides a uniform way to report errors in the compiled code.• tcl.error(co<strong>ns</strong>t char* s) performs the following functio<strong>ns</strong>: write s to stdout; write tcl_->result to stdout; exitwith error code 1.tcl.resultf("cmd = %s", cmd);tcl.error("invalid comm<strong>and</strong> specified");/*NOTREACHED*/Note th<strong>at</strong> there are minor differences between returning TCL_ERROR as we did in the previous subsection (Section 3.3.3),<strong>and</strong> calling Tcl::error(). <strong>The</strong> former gener<strong>at</strong>es an exception within the interpreter; the user can trap the exception <strong>and</strong>possibly recover from the error. If the user has not specified any traps, the interpreter will print a stack trace <strong>and</strong> exit. However,if the code invokes error(), then the simul<strong>at</strong>ion user cannot trap the error; in addition, <strong>ns</strong> will not print any stack trace.3.3.5 Hash Functio<strong>ns</strong> within the Interpreter<strong>ns</strong> stores a reference to every TclObject in the compiled hierarchy in a hash table; this permits quick access to the objects.<strong>The</strong> hash table is internal to the interpreter. <strong>ns</strong> uses the name of the TclObject as the key to enter, lookup, or delete theTclObject in the hash table.22


• tcl.enter(TclObject* o) will i<strong>ns</strong>ert a pointer to the TclObject o into the hash table.It is used by TclClass::cre<strong>at</strong>e_shadow() to i<strong>ns</strong>ert an object into the table, when th<strong>at</strong> object is cre<strong>at</strong>ed.• tcl.lookup(char* s) will retrieve the TclObject with the name s.It is used by TclObject::lookup().• tcl.remove(TclObject* o) will delete references to the TclObject o from the hash table.It is used by TclClass::delete_shadow() to remove an existing entry from the hash table, when th<strong>at</strong> object isdeleted.<strong>The</strong>se functio<strong>ns</strong> are used internally by the class TclObject <strong>and</strong> class TclClass.3.3.6 Other Oper<strong>at</strong>io<strong>ns</strong> on the InterpreterIf the above methods are not sufficient, then we must acquire the h<strong>and</strong>le to the interpreter, <strong>and</strong> write our own functio<strong>ns</strong>.• tcl.interp(void) retur<strong>ns</strong> the h<strong>and</strong>le to the interpreter th<strong>at</strong> is stored within the class Tcl.3.4 Class TclObjectclass TclObject is the base class for most of the other classes in the interpreted <strong>and</strong> compiled hierarchies. Every objectin the class TclObject is cre<strong>at</strong>ed by the user from within the interpreter. An equivalent shadow object is cre<strong>at</strong>ed in the compiledhierarchy. <strong>The</strong> two objects are closely associ<strong>at</strong>ed with each other. <strong>The</strong> class TclClass, described in the next section, contai<strong>ns</strong>the mechanisms th<strong>at</strong> perform this shadowing.In the rest of this document, we often refer to an object as a TclObject 1 . By this, we refer to a particular object th<strong>at</strong> is eitherin the class TclObject, or in a class th<strong>at</strong> is derived from the class TclObject. If it is necessary, we will explicitly qualifywhether th<strong>at</strong> object is an object within the interpreter, or an object within the compiled code. In such cases, we will use theabbrevi<strong>at</strong>io<strong>ns</strong> “interpreted object”, <strong>and</strong> “compiled object” to distinguish the two. <strong>and</strong> within the compiled code respectively.Differences from <strong>ns</strong> v1 Unlike <strong>ns</strong> v1, the class TclObject subsumes the earlier functio<strong>ns</strong> of the NsObject class. It thereforestores the interface variable bindings (Section 3.4.2) th<strong>at</strong> tie OTcl i<strong>ns</strong>tance variables in the interpreted object to correspondingC++ member variables in the compiled object. <strong>The</strong> binding is stronger than in <strong>ns</strong> v1 in th<strong>at</strong> any changes to the OTcl variablesare trapped, <strong>and</strong> the current C++ <strong>and</strong> OTcl values are made co<strong>ns</strong>istent after each access through the interpreter. <strong>The</strong> co<strong>ns</strong>istencyis done through the class I<strong>ns</strong>tVar (Section 3.8). Also unlike <strong>ns</strong> v1, objects in the class TclObject are no longer stored asa global link list. I<strong>ns</strong>tead, they are stored in a hash table in the class Tcl (Section 3.3.5).Example configur<strong>at</strong>ion of a TclObjectAgent/SRM/Adaptive).<strong>The</strong> following example illustr<strong>at</strong>es the configur<strong>at</strong>ion of an SRM agent (classset srm [new Agent/SRM/Adaptive]$srm set packetSize_ 1024$srm traffic-source $s01 In the l<strong>at</strong>est release of <strong>ns</strong> <strong>and</strong> <strong>ns</strong>/tclcl, this object has been renamed to SplitObjefct, which more accur<strong>at</strong>ely reflects its n<strong>at</strong>ure of existence. However,for the moment, we will continue to use the term TclObject to refer to these objects <strong>and</strong> this class.23


By convention in <strong>ns</strong>, the class Agent/SRM/Adaptive is a subclass of Agent/SRM, is a subclass of Agent, is a subclass ofTclObject. <strong>The</strong> corresponding compiled class hierarchy is the ASRMAgent, derived from SRMAgent, derived from Agent,derived from TclObject respectively. <strong>The</strong> first line of the above example shows how a TclObject is cre<strong>at</strong>ed (or destroyed)(Section 3.4.1); the next line configures a bound variable (Section 3.4.2); <strong>and</strong> finally, the last line illustr<strong>at</strong>es the interpretedobject invoking a C++ method as if they were an i<strong>ns</strong>tance procedure (Section 3.4.4).3.4.1 Cre<strong>at</strong>ing <strong>and</strong> Destroying TclObjectsWhen the user cre<strong>at</strong>es a new TclObject, using the procedures new{} <strong>and</strong> delete{}; these procedures are defined in~tclcl/tcl-object.tcl. <strong>The</strong>y can be used to cre<strong>at</strong>e <strong>and</strong> destroy objects in all classes, including TclObjects. 2 . In this section,we describe the internal actio<strong>ns</strong> executed when a TclObject is cre<strong>at</strong>ed.Cre<strong>at</strong>ing TclObjects By using new{}, the user cre<strong>at</strong>es an interpreted TclObject. the interpreter will execute the co<strong>ns</strong>tructorfor th<strong>at</strong> object, init{}, passing it any arguments provided by the user. <strong>ns</strong> is respo<strong>ns</strong>ible for autom<strong>at</strong>ically cre<strong>at</strong>ing thecompiled object. <strong>The</strong> shadow object gets cre<strong>at</strong>ed by the base class TclObject’s co<strong>ns</strong>tructor. <strong>The</strong>refore, the co<strong>ns</strong>tructor forthe new TclObject must call the parent class co<strong>ns</strong>tructor first. new{} retur<strong>ns</strong> a h<strong>and</strong>le to the object, th<strong>at</strong> can then be used forfurther oper<strong>at</strong>io<strong>ns</strong> upon th<strong>at</strong> object.<strong>The</strong> following example illustr<strong>at</strong>es the Agent/SRM/Adaptive co<strong>ns</strong>tructor:Agent/SRM/Adaptive i<strong>ns</strong>tproc init args {eval $self next $args$self array set closest_ "requestor 0 repairor 0"$self set eps_ [$class set eps_]}<strong>The</strong> following sequence of actio<strong>ns</strong> are performed by the interpreter as part of i<strong>ns</strong>tanti<strong>at</strong>ing a new TclObject. For ease ofexposition, we describe the steps th<strong>at</strong> are executed to cre<strong>at</strong>e an Agent/SRM/Adaptive object. <strong>The</strong> steps are:1. Obtain an unique h<strong>and</strong>le for the new object from the TclObject name space. <strong>The</strong> h<strong>and</strong>le is returned to the user. Mosth<strong>and</strong>les in <strong>ns</strong> have the form _o〈NNN〉, where 〈NNN〉 is an integer. This h<strong>and</strong>le is cre<strong>at</strong>ed by getid{}. It can beretrieved from C++ with the name(){} method.2. Execute the co<strong>ns</strong>tructor for the new object. Any user-specified arguments are passed as arguments to the co<strong>ns</strong>tructor.This co<strong>ns</strong>tructor must invoke the co<strong>ns</strong>tructor associ<strong>at</strong>ed with its parent class.In our example above, the Agent/SRM/Adaptive calls its parent class in the very first line.Note th<strong>at</strong> each co<strong>ns</strong>tructor, in turn invokes its parent class’ co<strong>ns</strong>tructor ad nauseum. <strong>The</strong> last co<strong>ns</strong>tructor in <strong>ns</strong> is theTclObject co<strong>ns</strong>tructor. This co<strong>ns</strong>tructor is respo<strong>ns</strong>ible for setting up the shadow object, <strong>and</strong> performing other initializ<strong>at</strong>io<strong>ns</strong><strong>and</strong> bindings, as we explain below. It is preferable to call the parent co<strong>ns</strong>tructors first before performing theinitializ<strong>at</strong>io<strong>ns</strong> required in this class. This allows the shadow objects to be set up, <strong>and</strong> the variable bindings established.3. <strong>The</strong> TclObject co<strong>ns</strong>tructor invokes the i<strong>ns</strong>tance procedure cre<strong>at</strong>e-shadow{} for the class Agent/SRM/Adaptive.4. When the shadow object is cre<strong>at</strong>ed, <strong>ns</strong> calls all of the co<strong>ns</strong>tructors for the compiled object, each of which may establishvariable bindings for objects in th<strong>at</strong> class, <strong>and</strong> perform other necessary initializ<strong>at</strong>io<strong>ns</strong>. Hence our earlier injunction th<strong>at</strong>it is preferable to invoke the parent co<strong>ns</strong>tructors prior to performing the class initializ<strong>at</strong>io<strong>ns</strong>.5. After the shadow object is successfully cre<strong>at</strong>ed, cre<strong>at</strong>e_shadow(void)2 As an example, the classes Simul<strong>at</strong>or, Node, Link, or rtObject, are classes th<strong>at</strong> are not derived from the class TclObject. Objects in these classes are not,therefore, TclObjects. However, a Simul<strong>at</strong>or, Node, Link, or route Object is also i<strong>ns</strong>tanti<strong>at</strong>ed using the new procedure in <strong>ns</strong>.24


(a) adds the new object to hash table of TclObjects described earlier (Section 3.3.5).(b) makes cmd{} an i<strong>ns</strong>tance procedure of the newly cre<strong>at</strong>ed interpreted object. This i<strong>ns</strong>tance procedure invokes thecomm<strong>and</strong>() method of the compiled object. In a l<strong>at</strong>er subsection (Section 3.4.4), we describe how the comm<strong>and</strong>method is defined, <strong>and</strong> invoked.Note th<strong>at</strong> all of the above shadowing mechanisms only work when the user cre<strong>at</strong>es a new TclObject through the interpreter.It will not work if the programmer cre<strong>at</strong>es a compiled TclObject unil<strong>at</strong>erally. <strong>The</strong>refore, the programmer is enjoined not touse the C++ new method to cre<strong>at</strong>e compiled objects directly.Deletion of TclObjects <strong>The</strong> delete oper<strong>at</strong>ion destroys the interpreted object, <strong>and</strong> the corresponding shadow object. Forexample, use-scheduler{〈scheduler〉} uses the delete procedure to remove the default list scheduler, <strong>and</strong> i<strong>ns</strong>tanti<strong>at</strong>ean altern<strong>at</strong>e scheduler in its place.Simul<strong>at</strong>or i<strong>ns</strong>tproc use-scheduler type {$self i<strong>ns</strong>tvar scheduler_}delete scheduler_set scheduler_ [new Scheduler/$type];# first delete the existing list schedulerAs with the co<strong>ns</strong>tructor, the object destructor must call the destructor for the parent class explicitly as the very last st<strong>at</strong>ementof the destructor. <strong>The</strong> TclObject destructor will invoke the i<strong>ns</strong>tance procedure delete-shadow, th<strong>at</strong> in turn invokes theequivalent compiled method to destroy the shadow object. <strong>The</strong> interpreter itself will destroy the interpreted object.3.4.2 Variable BindingsIn most cases, access to compiled member variables is restricted to compiled code, <strong>and</strong> access to interpreted member variablesis likewise confined to access via interpreted code; however, it is possible to establish bi-directional bindings such th<strong>at</strong> boththe interpreted member variable <strong>and</strong> the compiled member variable access the same d<strong>at</strong>a, <strong>and</strong> changing the value of eithervariable changes the value of the corresponding paired variable to same value.<strong>The</strong> binding is established by the compiled co<strong>ns</strong>tructor when th<strong>at</strong> object is i<strong>ns</strong>tanti<strong>at</strong>ed; it is autom<strong>at</strong>ically accessible by theinterpreted object as an i<strong>ns</strong>tance variable. <strong>ns</strong> supports five different d<strong>at</strong>a types: reals, b<strong>and</strong>width valued variables, time valuedvariables, integers, <strong>and</strong> boolea<strong>ns</strong>. <strong>The</strong> syntax of how these values can be specified in OTcl is different for each variable type.• Real <strong>and</strong> Integer valued variables are specified in the “normal” form. For example,$object set realvar 1.2e3$object set intvar 12• B<strong>and</strong>width is specified as a real value, optionally suffixed by a ‘k’ or ‘K’ to mean kilo-quantities, or ‘m’ or ‘M’ to meanmega-quantities. A final optional suffix of ‘B’ indic<strong>at</strong>es th<strong>at</strong> the quantity expressed is in Bytes per second. <strong>The</strong> defaultis b<strong>and</strong>width expressed in bits per second. For example, all of the following are equivalent:$object set bwvar 1.5m$object set bwvar 1.5mb$object set bwvar 1500k25


$object set bwvar 1500kb$object set bwvar .1875MB$object set bwvar 187.5kB$object set bwvar 1.5e6• Time is specified as a real value, optionally suffixed by a ‘m’ to express time in milli-seconds, ‘n’ to express time innano-seconds, or ‘p’ to express time in pico-seconds. <strong>The</strong> default is time expressed in seconds. For example, all of thefollowing are equivalent:$object set timevar 1500m$object set timevar 1.5$object set timevar 1.5e9n$object set timevar 1500e9pNote th<strong>at</strong> we can also safely add a s to reflect the time unit of seconds. <strong>ns</strong> will ignore anything other than a valid realnumber specific<strong>at</strong>ion, or a trailing ‘m’, ‘n’, or ‘p’.• Boolea<strong>ns</strong> can be expressed either as an integer, or as ‘T’ or ‘t’ for true. Subsequent characters after the first letter areignored. If the value is neither an integer, nor a true value, then it is assumed to be false. For example,$object set boolvar t$object set boolvar true$object set boolvar 1$object set boolvar false$object set boolvar junk$object set boolvar 0;# set to true;# or any non-zero value;# set to false<strong>The</strong> following example shows the co<strong>ns</strong>tructor for the ASRMAgent 3 .ASRMAgent::ASRMAgent() {bind("pdistance_", &pdistance_); /* real variable */bind("requestor_", &requestor_); /* integer variable */bind_time("lastSent_", &lastSessSent_); /* time variable */bind_bw("ctrlLimit_", &ctrlBWLimit_); /* b<strong>and</strong>width variable */bind_bool("running_", &running_); /* boolean variable */}Note th<strong>at</strong> all of the functio<strong>ns</strong> above take two arguments, the name of an OTcl variable, <strong>and</strong> the address of the correspondingcompiled member variable th<strong>at</strong> is linked. While it is often the case th<strong>at</strong> these bindings are established by the co<strong>ns</strong>tructor ofthe object, it need not always be done in this manner. We will discuss such altern<strong>at</strong>e methods when we describe the classI<strong>ns</strong>tVar (Section 3.8) in detail l<strong>at</strong>er.Each of the variables th<strong>at</strong> is bound is autom<strong>at</strong>ically initialised with default values when the object is cre<strong>at</strong>ed. <strong>The</strong> defaultvalues are specified as interpreted class variables. This initialis<strong>at</strong>ion is done by the routing init-i<strong>ns</strong>tvar{}, invoked bymethods in the class I<strong>ns</strong>tvar, described l<strong>at</strong>er (Section 3.8). init-i<strong>ns</strong>tvar{} checks the class of the interpreted object, <strong>and</strong>all of the parent class of th<strong>at</strong> object, to find the first class in which the variable is defined. It uses the value of the variable inth<strong>at</strong> class to initialise the object. Most of the bind initialis<strong>at</strong>ion values are defined in ~<strong>ns</strong>/tcl/lib/<strong>ns</strong>-default.tcl.For example, if the following class variables are defined for the ASRMAgent:3 Note th<strong>at</strong> this co<strong>ns</strong>tructor is embellished to illustr<strong>at</strong>e the fe<strong>at</strong>ures of the variable binding mechanism.26


Agent/SRM/Adaptive set pdistance_ 15.0Agent/SRM set pdistance_ 10.0Agent/SRM set lastSent_ 8.345mAgent set ctrlLimit_ 1.44MAgent/SRM/Adaptive set running_ f<strong>The</strong>refore, every new Agent/SRM/Adaptive object will have pdistance_ set to 15.0; lastSent_ is set to 8.345m fromthe setting of the class variable of the parent class; ctrlLimit_ is set to 1.44M using the class variable of the parent classtwice removed; running is set to false; the i<strong>ns</strong>tance variable pdistance_ is not initialised, because no class variable existsin any of the class hierarchy of the interpreted object. In such i<strong>ns</strong>tance, init-i<strong>ns</strong>tvar{} will invoke warn-i<strong>ns</strong>tvar{},to print out a warning about such a variable. <strong>The</strong> user can selectively override this procedure in their simul<strong>at</strong>ion scripts, toelide this warning.Note th<strong>at</strong> the actual binding is done by i<strong>ns</strong>tanti<strong>at</strong>ing objects in the class I<strong>ns</strong>tVar. Each object in the class I<strong>ns</strong>tVar binds onecompiled member variable to one interpreted member variable. A TclObject stores a list of I<strong>ns</strong>tVar objects corresponding toeach of its member variable th<strong>at</strong> is bound in this fashion. <strong>The</strong> head of this list is stored in its member variable i<strong>ns</strong>tvar_ ofthe TclObject.One last point to co<strong>ns</strong>ider is th<strong>at</strong> <strong>ns</strong> will guarantee th<strong>at</strong> the actual values of the variable, both in the interpreted object <strong>and</strong> thecompiled object, will be identical <strong>at</strong> all times. However, if there are methods <strong>and</strong> other variables of the compiled object th<strong>at</strong>track the value of this variable, they must be explicitly invoked or changed whenever the value of this variable is changed.This usually requires additional primitives th<strong>at</strong> the user should invoke. One way of providing such primitives in <strong>ns</strong> is throughthe comm<strong>and</strong>() method described in the next section.3.4.3 Variable TracingIn addition to variable bindings, TclObject also supports tracing of both C++ <strong>and</strong> Tcl i<strong>ns</strong>tance variables. A traced variablecan be cre<strong>at</strong>ed <strong>and</strong> configured either in C++ or Tcl. To establish variable tracing <strong>at</strong> the Tcl level, the variable must be visiblein Tcl, which mea<strong>ns</strong> th<strong>at</strong> it must be a bounded C++/Tcl or a pure Tcl i<strong>ns</strong>tance variable. In addition, the object th<strong>at</strong> ow<strong>ns</strong>the traced variable is also required to establish tracing using the Tcl trace method of TclObject. <strong>The</strong> first argument to thetrace method must be the name of the variable. <strong>The</strong> optional second argument specifies the trace object th<strong>at</strong> is respo<strong>ns</strong>iblefor tracing th<strong>at</strong> variable. If the trace object is not specified, the object th<strong>at</strong> own the variable is respo<strong>ns</strong>ible for tracing it.For a TclObject to trace variables, it must extend the C++ trace method th<strong>at</strong> is virtually defined in TclObject. <strong>The</strong> Traceclass implements a simple trace method, thereby, it can act as a generic tracer for variables.class Trace : public Connector {...virtual void trace(TracedVar*);};Below is a simple example for setting up variable tracing in Tcl:# \$tcp tracing its own variable cwnd_\$tcp trace cwnd_# the variable ssthresh_ of \$tcp is traced by a generic \$tracerset tracer [new Trace/Var]\$tcp trace ssthresh_ \$tracer27


For a C++ variable to be traceable, it must belong to a class th<strong>at</strong> derives from TracedVar. <strong>The</strong> virtual base class TracedVarkeeps track of the variable’s name, owner, <strong>and</strong> tracer. Classes th<strong>at</strong> derives from TracedVar must implement the virtual methodvalue, th<strong>at</strong> takes a character buffer as an argument <strong>and</strong> writes the value of the variable into th<strong>at</strong> buffer.class TracedVar {...virtual char* value(char* buf) = 0;protected:TracedVar(co<strong>ns</strong>t char* name);co<strong>ns</strong>t char* name_; // name of the variableTclObject* owner_; // the object th<strong>at</strong> ow<strong>ns</strong> this variableTclObject* tracer_; // callback when the variable is changed...};<strong>The</strong> TclCL library exports two classes of TracedVar: TracedInt <strong>and</strong> TracedDouble. <strong>The</strong>se classes can be used inplace of the basic type int <strong>and</strong> double respectively. Both TracedInt <strong>and</strong> TracedDouble overload all the oper<strong>at</strong>ors th<strong>at</strong> canchange the value of the variable such as assignment, increment, <strong>and</strong> decrement. <strong>The</strong>se overloaded oper<strong>at</strong>ors use the assignmethod to assign the new value to the variable <strong>and</strong> call the tracer if the new value is different from the old one. TracedInt <strong>and</strong>TracedDouble also implement their value methods th<strong>at</strong> output the value of the variable into string. <strong>The</strong> width <strong>and</strong> precisionof the output can be pre-specified.3.4.4 comm<strong>and</strong>Methods: Definition <strong>and</strong> Invoc<strong>at</strong>ionFor every TclObject th<strong>at</strong> is cre<strong>at</strong>ed, <strong>ns</strong> establishes the i<strong>ns</strong>tance procedure, cmd{}, as a hook to executing methods through thecompiled shadow object. <strong>The</strong> procedure cmd{} invokes the method comm<strong>and</strong>() of the shadow object autom<strong>at</strong>ically, passingthe arguments to cmd{} as an argument vector to the comm<strong>and</strong>() method.<strong>The</strong> user can invoke the cmd{} method in one of two ways: by explicitly invoking the procedure, specifying the desiredoper<strong>at</strong>ion as the first argument, or implicitly, as if there were an i<strong>ns</strong>tance procedure of the same name as the desired oper<strong>at</strong>ion.Most simul<strong>at</strong>ion scripts will use the l<strong>at</strong>ter form, hence, we will describe th<strong>at</strong> mode of invoc<strong>at</strong>ion first.Co<strong>ns</strong>ider the th<strong>at</strong> the distance comput<strong>at</strong>ion in SRM is done by the compiled object; however, it is often used by the interpretedobject. It is usually invoked as:$srmObject distance? 〈agentAddress〉If there is no i<strong>ns</strong>tance procedure called distance?, the interpreter will invoke the i<strong>ns</strong>tance procedure unknown{}, definedin the base class TclObject. <strong>The</strong> unknown procedure then invokes$srmObject cmd distance? 〈agentAddress〉to execute the oper<strong>at</strong>ion through the compiled object’s comm<strong>and</strong>() procedure.Ofcourse, the user could explicitly invoke the oper<strong>at</strong>ion directly. One reason for this might be to overload the oper<strong>at</strong>ion byusing an i<strong>ns</strong>tance procedure of the same name. For example,Agent/SRM/Adaptive i<strong>ns</strong>tproc distance? addr {28


}$self i<strong>ns</strong>tvar distanceCache_if ![info exists distanceCache_($addr)] {set distanceCache_($addr) [$self cmd distance? $addr]}set distanceCache_($addr)We now illustr<strong>at</strong>e how the comm<strong>and</strong>() method using ASRMAgent::comm<strong>and</strong>() as an example.int ASRMAgent::comm<strong>and</strong>(int argc, co<strong>ns</strong>t char*co<strong>ns</strong>t*argv) {Tcl& tcl = Tcl::i<strong>ns</strong>tance();if (argc == 3) {if (strcmp(argv[1], "distance?") == 0) {int sender = <strong>at</strong>oi(argv[2]);SRMinfo* sp = get_st<strong>at</strong>e(sender);tcl.tesultf("%f", sp->distance_);return TCL_OK;}}return (SRMAgent::comm<strong>and</strong>(argc, argv));}We can make the following observ<strong>at</strong>io<strong>ns</strong> from this piece of code:• <strong>The</strong> function is called with two arguments:<strong>The</strong> first argument (argc) indic<strong>at</strong>es the number of arguments specified in the comm<strong>and</strong> line to the interpreter.<strong>The</strong> comm<strong>and</strong> line arguments vector (argv) co<strong>ns</strong>ists of— argv[0] contai<strong>ns</strong> the name of the method, “cmd”.— argv[1] specifies the desired oper<strong>at</strong>ion.— If the user specified any arguments, then they are placed in argv[2...(argc - 1)].<strong>The</strong> arguments are passed as strings; they must be converted to the appropri<strong>at</strong>e d<strong>at</strong>a type.• If the oper<strong>at</strong>ion is successfully m<strong>at</strong>ched, the m<strong>at</strong>ch should return the result of the oper<strong>at</strong>ion using methods describedearlier (Section 3.3.3).• comm<strong>and</strong>() itself must return either TCL_OK or TCL_ERROR to indic<strong>at</strong>e success or failure as its return code.• If the oper<strong>at</strong>ion is not m<strong>at</strong>ched in this method, it must invoke its parent’s comm<strong>and</strong> method, <strong>and</strong> return the correspondingresult.This permits the user to concieve of oper<strong>at</strong>io<strong>ns</strong> as having the same inheritance properties as i<strong>ns</strong>tance procedures orcompiled methods.In the event th<strong>at</strong> this comm<strong>and</strong> method is defined for a class with multiple inheritance, the programmer has the libertyto choose one of two implement<strong>at</strong>io<strong>ns</strong>:1) Either they can invoke one of the parent’s comm<strong>and</strong> method, <strong>and</strong> return the result of th<strong>at</strong> invoc<strong>at</strong>ion, or2) <strong>The</strong>y can each of the parent’s comm<strong>and</strong> methods in some sequence, <strong>and</strong> return the result of the first invoc<strong>at</strong>ion th<strong>at</strong>is successful. If none of them are successful, then they should return an error.In our document, we call oper<strong>at</strong>io<strong>ns</strong> executed through the comm<strong>and</strong>() i<strong>ns</strong>tproc-likes. This reflects the usage of these oper<strong>at</strong>io<strong>ns</strong>as if they were OTcl i<strong>ns</strong>tance procedures of an object, but can be very subtly different in their realis<strong>at</strong>ion <strong>and</strong> usage.29


3.5 Class TclClassThis compiled class (class TclClass) is a pure virtual class. Classes derived from this base class provide two functio<strong>ns</strong>:co<strong>ns</strong>truct the interpreted class hierarchy to mirror the compiled class hierarchy; <strong>and</strong> provide methods to i<strong>ns</strong>tanti<strong>at</strong>e newTclObjects. Each such derived class is associ<strong>at</strong>ed with a particular compiled class in the compiled class hierarchy, <strong>and</strong> cani<strong>ns</strong>tanti<strong>at</strong>e new objects in the associ<strong>at</strong>ed class.As an example, co<strong>ns</strong>ider a class such as the class RenoTcpClass. It is derived from class TclClass, <strong>and</strong> is associ<strong>at</strong>edwith the class RenoTcpAgent. It will i<strong>ns</strong>tanti<strong>at</strong>e new objects in the class RenoTcpAgent. <strong>The</strong> compiled class hierarchyfor RenoTcpAgent is th<strong>at</strong> it derives from TcpAgent, th<strong>at</strong> in turn derives from Agent, th<strong>at</strong> in turn derives (roughly) fromTclObject. RenoTcpClass is defined asst<strong>at</strong>ic class RenoTcpClass: public TclClass {public:RenoTcpClass() : TclClass("Agent/TCP/Reno") {}TclObject* cre<strong>at</strong>e(int argc, co<strong>ns</strong>t char*co<strong>ns</strong>t* argv) {return (new RenoTcpAgent());}} class_reno;We can make the following observ<strong>at</strong>io<strong>ns</strong> from this definition:1. <strong>The</strong> class defines only the co<strong>ns</strong>tructor, <strong>and</strong> one additional method, to cre<strong>at</strong>e i<strong>ns</strong>tances of the associ<strong>at</strong>ed TclObject.2. <strong>ns</strong> will execute the RenoTcpClass co<strong>ns</strong>tructor for the st<strong>at</strong>ic variable class_reno, when it is first started. This setsup the appropri<strong>at</strong>e methods <strong>and</strong> the interpreted class hierarchy.3. <strong>The</strong> co<strong>ns</strong>tructor specifies the interpreted class explicitly as Agent/TCP/Reno. This also specifies the interpretedclass hierarchy implicitly.Recall th<strong>at</strong> the convention in <strong>ns</strong> is to use the character slash (’/’) is a separ<strong>at</strong>or. For any given class A/B/C/D, theclass A/B/C/D is a sub-class of A/B/C, th<strong>at</strong> is itself a sub-class of A/B, th<strong>at</strong>, in turn, is a sub-class of A. A itself is asub-class of TclObject.In our case above, the TclClass co<strong>ns</strong>tructor cre<strong>at</strong>es three classes, Agent/TCP/Reno sub-class of Agent/TCP subclassof Agent sub-class of TclObject.4. This class is associ<strong>at</strong>ed with the class RenoTcpAgent; it cre<strong>at</strong>s new objects in this associ<strong>at</strong>ed class.5. <strong>The</strong> RenoTcpClass::cre<strong>at</strong>e method retur<strong>ns</strong> TclObjects in the class RenoTcpAgent.6. When the user specifies new Agent/TCP/Reno, the routine RenoTcpClass::cre<strong>at</strong>e is invoked.7. <strong>The</strong> arguments vector (argv) co<strong>ns</strong>ists of— argv[0] contai<strong>ns</strong> the name of the object.— argv[1...3] contain $self, $class, <strong>and</strong> $proc.Since cre<strong>at</strong>e is called through the i<strong>ns</strong>tance procedurecre<strong>at</strong>e-shadow, argv[3] contai<strong>ns</strong> cre<strong>at</strong>e-shadow.— argv[4] contain any additional arguments (passed as a string) provided by the user.<strong>The</strong> class Trace illustr<strong>at</strong>es argument h<strong>and</strong>ling by TclClass methods.class TraceClass : public TclClass {public:30


TraceClass() : TclClass("Trace") {}TclObject* cre<strong>at</strong>e(int args, co<strong>ns</strong>t char*co<strong>ns</strong>t* argv) {if (args >= 5)return (new Trace(*argv[4]));elsereturn NULL;}} trace_class;A new Trace object is cre<strong>at</strong>ed asnew Trace "X"Finally, the nitty-gritty details of how the interpreted class hierarchy is co<strong>ns</strong>tructed:1. <strong>The</strong> object co<strong>ns</strong>tructor is executed when <strong>ns</strong> first starts.2. This co<strong>ns</strong>tructor calls the TclClass co<strong>ns</strong>tructor with the name of the interpreted class as its argument.3. <strong>The</strong> TclClass co<strong>ns</strong>tructor stores the name of the class, <strong>and</strong> i<strong>ns</strong>erts this object into a linked list of the TclClass objects.4. During initializ<strong>at</strong>ion of the simul<strong>at</strong>or, Tcl_AppInit(void) invokes TclClass::bind(void)5. For each object in the list of TclClass objects, bind() invokes register{}, specifying the name of the interpretedclass as its argument.6. register{} establishes the class hierarchy, cre<strong>at</strong>ing the classes th<strong>at</strong> are required, <strong>and</strong> not yet cre<strong>at</strong>ed.7. Finally, bind() defines i<strong>ns</strong>tance procedures cre<strong>at</strong>e-shadow <strong>and</strong> delete-shadow for this new class.3.5.1 How to Bind St<strong>at</strong>ic C++ Class Member VariablesIn Section 3.4, we have seen how to expose member variables of a C++ object into OTcl space. This, however, does not applyto st<strong>at</strong>ic member variables of a C++ class. Of course, one may cre<strong>at</strong>e an OTcl variable for the st<strong>at</strong>ic member variable of everyC++ object; obviously this defe<strong>at</strong>s the whole meaning of st<strong>at</strong>ic members.We cannot solve this binding problem using a similar solution as binding in TclObject, which is based on I<strong>ns</strong>tVar, becauseI<strong>ns</strong>tVars in TclCL require the presence of a TclObject. However, we can cre<strong>at</strong>e a method of the corresponding TclClass <strong>and</strong>access st<strong>at</strong>ic members of a C++ class through the methods of its corresponding TclClass. <strong>The</strong> procedure is as follows:1. Cre<strong>at</strong>e your own derived TclClass as described above;2. Declare methods bind() <strong>and</strong> method() in your derived class;3. Cre<strong>at</strong>e your binding methods in the implement<strong>at</strong>ion of your bind() with add_method("your_method"), thenimplement the h<strong>and</strong>ler in method() in a similar way as you would do in TclObject::comm<strong>and</strong>(). Notice th<strong>at</strong> thenumber of arguments passed to TclClass::method() are different from those passed to TclObject::comm<strong>and</strong>().<strong>The</strong> former has two more arguments in the front.As an example, we show a simplified version of PacketHeaderClass in ~<strong>ns</strong>/packet.cc. Suppose we have the followingclass Packet which has a st<strong>at</strong>ic variable hdrlen_ th<strong>at</strong> we want to access from OTcl:31


class Packet {......st<strong>at</strong>ic int hdrlen_;};<strong>The</strong>n we do the following to co<strong>ns</strong>truct an accessor for this variable:class PacketHeaderClass : public TclClass {protected:PacketHeaderClass(co<strong>ns</strong>t char* classname, int hdrsize);TclObject* cre<strong>at</strong>e(int argc, co<strong>ns</strong>t char*co<strong>ns</strong>t* argv);/* <strong>The</strong>se two implements OTcl class access methods */virtual void bind();virtual int method(int argc, co<strong>ns</strong>t char*co<strong>ns</strong>t* argv);};void PacketHeaderClass::bind(){}TclClass::bind();add_method("hdrlen");/* Call to base class bind() must precede add_method() */int PacketHeaderClass::method(int ac, co<strong>ns</strong>t char*co<strong>ns</strong>t* av){Tcl& tcl = Tcl::i<strong>ns</strong>tance();/* Notice this argument tra<strong>ns</strong>l<strong>at</strong>ion; we can then h<strong>and</strong>le them as if in TclObject::comm<strong>and</strong>() */int argc = ac - 2;co<strong>ns</strong>t char*co<strong>ns</strong>t* argv = av + 2;if (argc == 2) {if (strcmp(argv[1], "hdrlen") == 0) {tcl.resultf("%d", Packet::hdrlen_);return (TCL_OK);}} else if (argc == 3) {if (strcmp(argv[1], "hdrlen") == 0) {Packet::hdrlen_ = <strong>at</strong>oi(argv[2]);return (TCL_OK);}}return TclClass::method(ac, av);}After this, we can then use the following OTcl comm<strong>and</strong> to access <strong>and</strong> change values of Packet::hdrlen_:PacketHeader hdrlen 120set i [PacketHeader hdrlen]32


3.6 Class TclComm<strong>and</strong>This class (class TclComm<strong>and</strong>) provides just the mechanism for <strong>ns</strong> to export simple comm<strong>and</strong>s to the interpreter, th<strong>at</strong> canthen be executed within a global context by the interpreter. <strong>The</strong>re are two functio<strong>ns</strong> defined in ~<strong>ns</strong>/misc.cc: <strong>ns</strong>-r<strong>and</strong>om <strong>and</strong><strong>ns</strong>-version. <strong>The</strong>se two functio<strong>ns</strong> are initialized by the function init_misc(void), defined in ~<strong>ns</strong>/misc.cc; init_miscis invoked by Tcl_AppInit(void) during startup.• class VersionComm<strong>and</strong> defines the comm<strong>and</strong> <strong>ns</strong>-version. It takes no argument, <strong>and</strong> retur<strong>ns</strong> the current <strong>ns</strong>version string.% <strong>ns</strong>-version ;# get the current version2.0a12• class R<strong>and</strong>omComm<strong>and</strong> defines the comm<strong>and</strong> <strong>ns</strong>-r<strong>and</strong>om. With no argument, <strong>ns</strong>-r<strong>and</strong>om retur<strong>ns</strong> an integer,uniformly distributed in the interval [0, 2 31 − 1].When specified an argument, it takes th<strong>at</strong> argument as the seed. If this seed value is 0, the comm<strong>and</strong> uses a heuristicseed value; otherwise, it sets the seed for the r<strong>and</strong>om number gener<strong>at</strong>or to the specified value.% <strong>ns</strong>-r<strong>and</strong>om ;# return a r<strong>and</strong>om number2078917053% <strong>ns</strong>-r<strong>and</strong>om 0 ;#set the seed heuristically858190129% <strong>ns</strong>-r<strong>and</strong>om 23786 ;#set seed to specified value23786Note th<strong>at</strong>, it is generally not advisable to co<strong>ns</strong>truct top-level comm<strong>and</strong>s th<strong>at</strong> are available to the user. We now describe howto define a new comm<strong>and</strong> using the example class say_hello. <strong>The</strong> example defines the comm<strong>and</strong> hi, to print the string“hello world”, followed by any comm<strong>and</strong> line arguments specified by the user. For example,% hi this is <strong>ns</strong> [<strong>ns</strong>-version]hello world, this is <strong>ns</strong> 2.0a121. <strong>The</strong> comm<strong>and</strong> must be defined within a class derived from the class TclComm<strong>and</strong>. <strong>The</strong> class definition is:class say_hello : public TclComm<strong>and</strong> {public:say_hello();int comm<strong>and</strong>(int argc, co<strong>ns</strong>t char*co<strong>ns</strong>t* argv);};2. <strong>The</strong> co<strong>ns</strong>tructor for the class must invoke the TclComm<strong>and</strong> co<strong>ns</strong>tructor with the comm<strong>and</strong> as argument; i.e.,say_hello() : TclComm<strong>and</strong>("hi") {}<strong>The</strong> TclComm<strong>and</strong> co<strong>ns</strong>tructor sets up "hi" as a global procedure th<strong>at</strong> invokes TclComm<strong>and</strong>::disp<strong>at</strong>ch_cmd().3. <strong>The</strong> method comm<strong>and</strong>() must perform the desired action.<strong>The</strong> method is passed two arguments. <strong>The</strong> first argument, argc, contai<strong>ns</strong> the number of actual arguments passed bythe user.33


<strong>The</strong> actual arguments passed by the user are passed as an argument vector (argv) <strong>and</strong> contai<strong>ns</strong> the following:— argv[0] contai<strong>ns</strong> the name of the comm<strong>and</strong> (hi).— argv[1...(argc - 1)] contai<strong>ns</strong> additional arguments specified on the comm<strong>and</strong> line by the user.comm<strong>and</strong>() is invoked by disp<strong>at</strong>ch_cmd().#include /* because we are using stream I/O */int say_hello::comm<strong>and</strong>(int argc, co<strong>ns</strong>t char*co<strong>ns</strong>t* argv) {cout


script after making their own changes. Finally, after adding the scripts to ~<strong>ns</strong>/tcl/lib/<strong>ns</strong>-lib.tcl, <strong>and</strong> every time thereafter th<strong>at</strong>they change their script, the user must recompile <strong>ns</strong> for their changes to take effect. Of course, in most cases 4 , the user ca<strong>ns</strong>ource their script to override the embedded code.<strong>The</strong> rest of this subsection illustr<strong>at</strong>e how to integr<strong>at</strong>e individual scripts directly into <strong>ns</strong>. <strong>The</strong> first step is convert the script intoan EmbeddedTcl object. <strong>The</strong> lines below exp<strong>and</strong> <strong>ns</strong>-lib.tcl <strong>and</strong> cre<strong>at</strong>e the EmbeddedTcl object i<strong>ns</strong>tance called et_<strong>ns</strong>_lib:tclsh bin/tcl-exp<strong>and</strong>.tcl tcl/lib/<strong>ns</strong>-lib.tcl | \../Tcl/tcl2c++ et_<strong>ns</strong>_lib > gen/<strong>ns</strong>_tcl.cc<strong>The</strong> script, ~<strong>ns</strong>/bin/tcl-exp<strong>and</strong>.tcl exp<strong>and</strong>s <strong>ns</strong>-lib.tcl by replacing all source lines with the corresponding source files.<strong>The</strong> program, ~tclcl/tcl2cc.c, converts the OTcl code into an equivalent EmbeddedTcl object, et_<strong>ns</strong>_lib.During initializ<strong>at</strong>ion, invoking the method EmbeddedTcl::load explicitly evalu<strong>at</strong>es the array.— ~tclcl/tcl-object.tcl is evalu<strong>at</strong>ed by the method Tcl::init(void); Tcl_AppInit() invokes Tcl::Init(). <strong>The</strong>exact comm<strong>and</strong> syntax for the load is:et_tclobject.load();— Similarly, ~<strong>ns</strong>/tcl/lib/<strong>ns</strong>-lib.tcl is evalu<strong>at</strong>ed directly by Tcl_AppInit in ~<strong>ns</strong>/<strong>ns</strong>_tclsh.cc.et_<strong>ns</strong>_lib.load();3.8 Class I<strong>ns</strong>tVarThis section describes the internals of the class I<strong>ns</strong>tVar. This class defines the methods <strong>and</strong> mechanisms to bind a C++member variable in the compiled shadow object to a specified OTcl i<strong>ns</strong>tance variable in the equivalent interpreted object. <strong>The</strong>binding is set up such th<strong>at</strong> the value of the variable can be set or accessed either from within the interpreter, or from withinthe compiled code <strong>at</strong> all times.<strong>The</strong>re are five i<strong>ns</strong>tance variable classes: class I<strong>ns</strong>tVarReal, class I<strong>ns</strong>tVarTime, class I<strong>ns</strong>tVarB<strong>and</strong>width,class I<strong>ns</strong>tVarInt, <strong>and</strong> class I<strong>ns</strong>tVarBool, corresponding to bindings for real, time, b<strong>and</strong>width, integer, <strong>and</strong>boolean valued variables respectively.We now describe the mechanism by which i<strong>ns</strong>tance variables are set up. We use the class I<strong>ns</strong>tVarReal to illustr<strong>at</strong>e theconcept. However, this mechanism is applicable to all five types of i<strong>ns</strong>tance variables.When setting up an interpreted variable to access a member variable, the member functio<strong>ns</strong> of the class I<strong>ns</strong>tVar assume th<strong>at</strong>they are executing in the appropri<strong>at</strong>e method execution context; therefore, they do not query the interpreter to determine thecontext in which this variable must exist.In order to guarantee the correct method execution context, a variable must only be bound if its class is already establishedwithin the interpreter, <strong>and</strong> the interpreter is currently oper<strong>at</strong>ing on an object in th<strong>at</strong> class. Note th<strong>at</strong> the former requires th<strong>at</strong>when a method in a given class is going to make its variables accessible via the interpreter, there must be an associ<strong>at</strong>ed4 <strong>The</strong> few places where this might not work are when certain variables might have to be defined or undefined, or otherwise the script contai<strong>ns</strong> code otherthan procedure <strong>and</strong> variable definitio<strong>ns</strong> <strong>and</strong> executes actio<strong>ns</strong> directly th<strong>at</strong> might not be reversible.35


class TclClass (Section 3.5) defined th<strong>at</strong> identifies the appropri<strong>at</strong>e class hierarchy to the interpreter. <strong>The</strong> appropri<strong>at</strong>e methodexecution context can therefore be cre<strong>at</strong>ed in one of two ways.An implicit solution occurs whenever a new TclObject is cre<strong>at</strong>ed within the interpreter. This sets up the method executioncontext within the interpreter. When the compiled shadow object of the interpreted TclObject is cre<strong>at</strong>ed, the co<strong>ns</strong>tructor forth<strong>at</strong> compiled object can bind its member variables of th<strong>at</strong> object to interpreted i<strong>ns</strong>tance variables in the context of the newlycre<strong>at</strong>ed interpreted object.An explicit solution is to define a bind-variables oper<strong>at</strong>ion within a comm<strong>and</strong> function, th<strong>at</strong> can then be invokedvia the cmd method. <strong>The</strong> correct method execution context is established in order to execute the cmd method. Likewise,the compiled code is now oper<strong>at</strong>ing on the appropri<strong>at</strong>e shadow object, <strong>and</strong> can therefore safely bind the required membervariables.An i<strong>ns</strong>tance variable is cre<strong>at</strong>ed by specifying the name of the interpreted variable, <strong>and</strong> the address of the member variable inthe compiled object. <strong>The</strong> co<strong>ns</strong>tructor for the base class I<strong>ns</strong>tVar cre<strong>at</strong>es an i<strong>ns</strong>tance of the variable in the interpreter, <strong>and</strong> the<strong>ns</strong>ets up a trap routine to c<strong>at</strong>ch all accesses to the variable through the interpreter.Whenever the variable is read through the interpreter, the trap routine is invoked just prior to the occurrence of the read. <strong>The</strong>routine invokes the appropri<strong>at</strong>e get function th<strong>at</strong> retur<strong>ns</strong> the current value of the variable. This value is then used to set thevalue of the interpreted variable th<strong>at</strong> is then read by the interpreter.Likewise, whenever the variable is set through the interpreter, the trap routine is invoked just after to the write is completed.<strong>The</strong> routine gets the current value set by the interpreter, <strong>and</strong> invokes the appropri<strong>at</strong>e set function th<strong>at</strong> sets the value of thecompiled member to the current value set within the interpreter.36


Part IISimul<strong>at</strong>or Basics37


Chapter 4<strong>The</strong> Class Simul<strong>at</strong>or<strong>The</strong> overall simul<strong>at</strong>or is described by a Tcl class Simul<strong>at</strong>or. It provides a set of interfaces for configuring a simul<strong>at</strong>ion<strong>and</strong> for choosing the type of event scheduler used to drive the simul<strong>at</strong>ion. A simul<strong>at</strong>ion script generally begi<strong>ns</strong> by cre<strong>at</strong>ing ani<strong>ns</strong>tance of this class <strong>and</strong> calling various methods to cre<strong>at</strong>e nodes, topologies, <strong>and</strong> configure other aspects of the simul<strong>at</strong>ion.A subclass of Simul<strong>at</strong>or called OldSim is used to support <strong>ns</strong> v1 backward comp<strong>at</strong>ibility.<strong>The</strong> procedures <strong>and</strong> functio<strong>ns</strong> described in this chapter can be found in ~<strong>ns</strong>/tcl/lib/<strong>ns</strong>-lib.tcl, ~<strong>ns</strong>/scheduler.{cc,h}, <strong>and</strong>,~<strong>ns</strong>/heap.h.4.1 Simul<strong>at</strong>or Initializ<strong>at</strong>ionWhen a new simul<strong>at</strong>ion object is cre<strong>at</strong>ed in tcl, the initializ<strong>at</strong>ion procedure performs the following oper<strong>at</strong>io<strong>ns</strong>:• initialize the packet form<strong>at</strong> (calls cre<strong>at</strong>e_packetform<strong>at</strong>)• cre<strong>at</strong>e a scheduler (defaults to a calendar scheduler)• cre<strong>at</strong>e a “null agent” (a discard sink used in various places)<strong>The</strong> packet form<strong>at</strong> initializ<strong>at</strong>ion sets up field offsets within packets used by the entire simul<strong>at</strong>ion. It is described in more detailin the following chapter on packets (Chapter 12). <strong>The</strong> scheduler ru<strong>ns</strong> the simul<strong>at</strong>ion in an event-driven manner <strong>and</strong> may bereplaced by altern<strong>at</strong>ive schedulers which provide somewh<strong>at</strong> different semantics (see the following section for more detail).<strong>The</strong> null agent is cre<strong>at</strong>ed with the following call:set nullAgent_ [new Agent/Null]This agent is generally useful as a sink for dropped packets or as a destin<strong>at</strong>ion for packets th<strong>at</strong> are not counted or recorded.4.2 Schedulers <strong>and</strong> Events<strong>The</strong> simul<strong>at</strong>or is an event-driven simul<strong>at</strong>or. <strong>The</strong>re are presently four schedulers available in the simul<strong>at</strong>or, each of which isimplemented using a different d<strong>at</strong>a structure: a simple linked-list, heap, calendar queue (default), <strong>and</strong> a special type called38


“real-time”. Each of these are described below. <strong>The</strong> scheduler ru<strong>ns</strong> by selecting the next earliest event, executing it tocompletion, <strong>and</strong> returning to execute the next event.Unit of time used by scheduler is seconds. Presently, the simul<strong>at</strong>or issingle-threaded, <strong>and</strong> only one event in execution <strong>at</strong> any given time. If more than one event are scheduled to execute <strong>at</strong> thesame time, their execution is performed on the first scheduled – first disp<strong>at</strong>ched manner. Simultaneous events are not reorderedanymore by schedulers (as it was in earlier versio<strong>ns</strong>) <strong>and</strong> all schedulers should yeild the same order of disp<strong>at</strong>chinggiven the same input.No partial execution of events or pre-emption is supported.An event generally comprises a “firing time” <strong>and</strong> a h<strong>and</strong>ler function. <strong>The</strong> actual definition of an event is found in ~<strong>ns</strong>/scheduler.h:class Event {public:Event* next_; /* event list */H<strong>and</strong>ler* h<strong>and</strong>ler_; /* h<strong>and</strong>ler to call when event ready */double time_; /* time <strong>at</strong> which event is ready */int uid_; /* unique ID */Event() : time_(0), uid_(0) {}};/** <strong>The</strong> base class for all event h<strong>and</strong>lers. When an event’s scheduled* time arrives, it is passed to h<strong>and</strong>le which must co<strong>ns</strong>ume it.* i.e., if it needs to be freed it, it must be freed by the h<strong>and</strong>ler.*/class H<strong>and</strong>ler {public:virtual void h<strong>and</strong>le(Event* event);};Two types of objects are derived from the base class Event: packets <strong>and</strong> “<strong>at</strong>-events”. Packets are described in detail inthe next chapter (Chapter 12.2.1). An <strong>at</strong>-event is a tcl procedure execution scheduled to occur <strong>at</strong> a particular time. This isfrequently used in simul<strong>at</strong>ion scripts. A simple example of how it is used is as follows:...set <strong>ns</strong>_ [new Simul<strong>at</strong>or]$<strong>ns</strong>_ use-scheduler Heap$<strong>ns</strong>_ <strong>at</strong> 300.5 "$self complete_sim"...This tcl code fragment first cre<strong>at</strong>es a simul<strong>at</strong>ion object, then changes the default scheduler implement<strong>at</strong>ion to be heap-based(see below), <strong>and</strong> finally schedules the function $self complete_sim to be executed <strong>at</strong> time 300.5 (seconds)(Note th<strong>at</strong>this particular code fragment expects to be encapsul<strong>at</strong>ed in an object i<strong>ns</strong>tance procedure, where the appropri<strong>at</strong>e reference to$self is correctly defined.). At-events are implemented as events where the h<strong>and</strong>ler is effectively an execution of the tclinterpreter.4.2.1 <strong>The</strong> List Scheduler<strong>The</strong> list scheduler (class Scheduler/List) implements the scheduler using a simple linked-list structure. <strong>The</strong> list iskept in time-order (earliest to l<strong>at</strong>est), so event i<strong>ns</strong>ertion <strong>and</strong> deletion require scanning the list to find the appropri<strong>at</strong>e entry.Choosing the next event for execution requires trimming the first entry off the head of the list. This implement<strong>at</strong>ion preservesevent execution in a FIFO manner for simultaneous events.39


4.2.2 the heap scheduler<strong>The</strong> heap scheduler (class Scheduler/Heap) implements the scheduler using a heap structure. This structure is superiorto the list structure for a large number of events, as i<strong>ns</strong>ertion <strong>and</strong> deletion times are in O(log n) for n events. Thisimplement<strong>at</strong>ion in <strong>ns</strong> v2 is borrowed from the MaRS-2.0 simul<strong>at</strong>or [1]; it is believed th<strong>at</strong> MaRS itself borrowed the code fromNetSim [14], although this lineage has not been completely verified.4.2.3 <strong>The</strong> Calendar Queue Scheduler<strong>The</strong> calendar queue scheduler (class Scheduler/Calendar) uses a d<strong>at</strong>a structure analogous to a one-year desk calendar,in which events on the same month/day of multiple years can be recorded in one day. It is formally described in [6],<strong>and</strong> informally described in Jain (p. 410) [15]. <strong>The</strong> implement<strong>at</strong>ion of Calendar queues in <strong>ns</strong> v2 was contributed by DavidWetherall (presently <strong>at</strong> MIT/LCS).4.2.4 <strong>The</strong> Real-Time Scheduler<strong>The</strong> real-time scheduler (class Scheduler/RealTime) <strong>at</strong>tempts to synchronize the execution of events with real-time.It is currently implemented as a subclass of the list scheduler. <strong>The</strong> real-time capability in <strong>ns</strong> is still under development,but is used to introduce an <strong>ns</strong> simul<strong>at</strong>ed network into a real-world topology to experiment with easily-configured networktopologies, cross-traffic, etc. This only works for rel<strong>at</strong>ively slow network traffic d<strong>at</strong>a r<strong>at</strong>es, as the simul<strong>at</strong>or must be able tokeep pace with the real-world packet arrival r<strong>at</strong>e, <strong>and</strong> this synchroniz<strong>at</strong>ion is not presently enforced.4.2.5 Precision of the scheduler clock used in <strong>ns</strong>Precision of the scheduler clock can be defined as the smallest time-scale of the simul<strong>at</strong>or th<strong>at</strong> can be correctly represented.<strong>The</strong> clock variable for <strong>ns</strong> is represented by a double. As per the IEEE std for flo<strong>at</strong>ing numbers, a double, co<strong>ns</strong>isting of 64 bitsmust alloc<strong>at</strong>e the following bits between its sign, exponent <strong>and</strong> mantissa fields.sign exponent mantissa1 bit 11 bits 52 bitsAny flo<strong>at</strong>ing number can be represented in the form (X ∗2 n ) where X is the mantissa <strong>and</strong> n is the exponent. Thus the precisionof timeclock in <strong>ns</strong> can be defined as (1/2 ( 52)). As simul<strong>at</strong>ion ru<strong>ns</strong> for longer times the number of remaining bits to representthe time educes thus reducing the accuracy. Given 52 bits we can safely say time upto around (2 ( 40)) can be represented withco<strong>ns</strong>iderable accuracy. Anything gre<strong>at</strong>er than th<strong>at</strong> might not be very accur<strong>at</strong>e as you have remaining 12 bits to represent thetime change. However (2 ( 40)) is a very large number <strong>and</strong> we donot anticip<strong>at</strong>e any problem regarding precision of time in <strong>ns</strong>.4.3 Other Methods<strong>The</strong> Simul<strong>at</strong>or class provides a number of methods used to set up the simul<strong>at</strong>ion. <strong>The</strong>y generally fall into three c<strong>at</strong>egories:methods to cre<strong>at</strong>e <strong>and</strong> manage the topology (which in turn co<strong>ns</strong>ists of managing the nodes (Chapter 5) <strong>and</strong> managing the links(Chapter 6)), methods to perform tracing (Chapter 26), <strong>and</strong> helper functio<strong>ns</strong> to deal with the scheduler. <strong>The</strong> following is a listof the non-topology rel<strong>at</strong>ed simul<strong>at</strong>or methods:40


Simul<strong>at</strong>or i<strong>ns</strong>tproc now;# return scheduler’s notion of current timeSimul<strong>at</strong>or i<strong>ns</strong>tproc <strong>at</strong> args;# schedule execution of code <strong>at</strong> specified timeSimul<strong>at</strong>or i<strong>ns</strong>tproc cancel args;# cancel eventSimul<strong>at</strong>or i<strong>ns</strong>tproc run args;# start schedulerSimul<strong>at</strong>or i<strong>ns</strong>tproc halt;# stop (pause) the schedulerSimul<strong>at</strong>or i<strong>ns</strong>tproc flush-trace;# flush all trace object write buffersSimul<strong>at</strong>or i<strong>ns</strong>tproc cre<strong>at</strong>e-trace type files src dst ;# cre<strong>at</strong>e trace objectSimul<strong>at</strong>or i<strong>ns</strong>tproc cre<strong>at</strong>e_packetform<strong>at</strong>;# set up the simul<strong>at</strong>or’s packet form<strong>at</strong>41


4.4 Comm<strong>and</strong>s <strong>at</strong> a glanceSynopsis:<strong>ns</strong> ..Description:Basic comm<strong>and</strong> to run a simul<strong>at</strong>ion script in <strong>ns</strong>.<strong>The</strong> simul<strong>at</strong>or (<strong>ns</strong>) is invoked via the <strong>ns</strong> interpreter, an exte<strong>ns</strong>ion of thevanilla otclsh comm<strong>and</strong> shell. A simul<strong>at</strong>ion is defined by a OTcl script(file). Several examples of OTcl scripts can be found under <strong>ns</strong>/tcl/exdirectory.<strong>The</strong> following is a list of simul<strong>at</strong>or comm<strong>and</strong>s commonly used in simul<strong>at</strong>io<strong>ns</strong>cripts:set <strong>ns</strong>_ [new Simul<strong>at</strong>or]This comm<strong>and</strong> cre<strong>at</strong>es an i<strong>ns</strong>tance of the simul<strong>at</strong>or object.set now [$<strong>ns</strong>_ now]<strong>The</strong> scheduler keeps track of time in a simul<strong>at</strong>ion. This retur<strong>ns</strong> scheduler’snotion of current time.$<strong>ns</strong>_ haltThis stops or pauses the scheduler.$<strong>ns</strong>_ runThis starts the scheduler.$<strong>ns</strong>_ <strong>at</strong> This schedules an (which is normally a piece of code) to be executed<strong>at</strong> the specified .e.g $<strong>ns</strong>_ <strong>at</strong> $opt(stop) "puts ¨NS EXITING..¨ ; $<strong>ns</strong>_ halt"or, $<strong>ns</strong>_ <strong>at</strong> 10.0 "$ftp start"42


$<strong>ns</strong>_ cancel Cancels the event. In effect, event is removed from scheduler’s list ofready to run events.$<strong>ns</strong>_ cre<strong>at</strong>e-trace This cre<strong>at</strong>es a trace-object of type between <strong>and</strong> objects<strong>and</strong> <strong>at</strong>taches trace-object to for writing trace-outputs. If op is definedas "nam", this cre<strong>at</strong>es nam tracefiles; otherwise if op is not defined, <strong>ns</strong>tracefiles are cre<strong>at</strong>ed on default.$<strong>ns</strong>_flush-traceFlushes all trace object write buffers.$<strong>ns</strong>_ gen-mapThis dumps inform<strong>at</strong>ion like nodes, node components, links etc cre<strong>at</strong>ed for agiven simul<strong>at</strong>ion. This may be broken for some scenarios (like wireless).$<strong>ns</strong>_ <strong>at</strong>-now This is in effect like comm<strong>and</strong> "$<strong>ns</strong>_ <strong>at</strong> $now $args". Note th<strong>at</strong> this functionmay not work because of tcl’s string number resolution.<strong>The</strong>se are additional simul<strong>at</strong>or (internal) helper functio<strong>ns</strong> (normally usedfor developing/changing the <strong>ns</strong> core code) :$<strong>ns</strong>_ use-scheduler Used to specify the type of scheduler to be used for simul<strong>at</strong>ion. <strong>The</strong> differenttypes of scheduler available are List, Calendar, Heap <strong>and</strong> RealTime. CurrentlyCalendar is used as default.$<strong>ns</strong>_ after Scheduling an to be executed after the lapse of time .$<strong>ns</strong>_ clearMemTraceUsed for memory debugging purposes.$<strong>ns</strong>_ is-startedThis retur<strong>ns</strong> true if simul<strong>at</strong>or has started to run <strong>and</strong> false if not.43


$<strong>ns</strong>_ dumpqComm<strong>and</strong> for dumping events queued in scheduler while scheduler is halted.$<strong>ns</strong>_ cre<strong>at</strong>e_packetform<strong>at</strong>This sets up simul<strong>at</strong>or’s packet form<strong>at</strong>.44


Chapter 5Nodes <strong>and</strong> Packet ForwardingThis chapter describes one aspect of cre<strong>at</strong>ing a topology in <strong>ns</strong>, i.e., cre<strong>at</strong>ing the nodes. In the next chapter (Chapter 6), wewill describe second aspect of cre<strong>at</strong>ing the topology, i.e., connecting the nodes to form links.Recall th<strong>at</strong> each simul<strong>at</strong>ion requires a single i<strong>ns</strong>tance of the class Simul<strong>at</strong>or to control <strong>and</strong> oper<strong>at</strong>e th<strong>at</strong> simul<strong>at</strong>ion.<strong>The</strong> class provides i<strong>ns</strong>tance procedures to cre<strong>at</strong>e <strong>and</strong> manage the topology, <strong>and</strong> internally stores references to each elementof the topology. We begin by describing the procedures in the class Simul<strong>at</strong>or (Section 5.1). We then describe the i<strong>ns</strong>tanceprocedures in the class Node (Section 5.2) to access <strong>and</strong> oper<strong>at</strong>e on individual nodes. We conclude with detailed descriptio<strong>ns</strong>of the Classifier (Section 5.4) from which the more complex node objects are formed.<strong>The</strong> procedures <strong>and</strong> functio<strong>ns</strong> described in this chapter can be found in ~<strong>ns</strong>/tcl/lib/<strong>ns</strong>-lib.tcl, ~<strong>ns</strong>/tcl/lib/<strong>ns</strong>-node.tcl,~<strong>ns</strong>/tcl/lib/<strong>ns</strong>-rtmodule.tcl, ~<strong>ns</strong>/rtmodule.{cc,h}, ~<strong>ns</strong>/classifier.{cc, h}, ~<strong>ns</strong>/classifier-addr.cc, ~<strong>ns</strong>/classifier-mcast.cc, ~<strong>ns</strong>/classifiermp<strong>at</strong>h.cc,<strong>and</strong>, ~<strong>ns</strong>/replic<strong>at</strong>or.cc.5.1 Node Basics<strong>The</strong> basic primitive for cre<strong>at</strong>ing a node isset <strong>ns</strong> [new Simul<strong>at</strong>or]$<strong>ns</strong> node<strong>The</strong> i<strong>ns</strong>tance procedure node co<strong>ns</strong>tructs a node out of more simple classifier objects (Section 5.4). <strong>The</strong> Node itself is ast<strong>and</strong>alone class in OTcl. However, most of the components of the node are themselves TclObjects. <strong>The</strong> typical structureof a (unicast) node is as shown in Figure 5.1. This simple structure co<strong>ns</strong>ists of two TclObjects: an address classifer(classifer_) <strong>and</strong> a port classifier (dmux_). <strong>The</strong> function of these classifiers is to distribute incoming packets to thecorrect agent or outgoing link.All nodes contain <strong>at</strong> least the following components:• an address or id_, monotonically increasing by 1 (from initial value 0) across the simul<strong>at</strong>ion namespace as nodes arecre<strong>at</strong>ed,• a list of neighbors (neighbor_),45


NODEPortClassifierAgentAgentAddrClassifierdmux_Agentagents_Node entryentry_classifier_LinkLinkLinkFigure 5.1: Structure of a Unicast Node. Notice th<strong>at</strong> entry_ is simply a label variable i<strong>ns</strong>tead of a real object, e.g., theclassifier_.• a list of agents (agent_),• a node type identifier (nodetype_), <strong>and</strong>• a routing module (described in Section 5.5 below)By default, nodes in <strong>ns</strong> are co<strong>ns</strong>tructed for unicast simul<strong>at</strong>io<strong>ns</strong>. In order to enable multicast simul<strong>at</strong>ion, the simul<strong>at</strong>ion shouldbe cre<strong>at</strong>ed with an option “-multicast on”, e.g.:set <strong>ns</strong> [new Simul<strong>at</strong>or -multicast on]<strong>The</strong> internal structure of a typical multicast node is shown in Figure 5.2.When a simul<strong>at</strong>ion uses multicast routing, the highest bit of the address indic<strong>at</strong>es whether the particular address is a multicastaddress or an unicast address. If the bit is 0, the address represents a unicast address, else the address represents a multicastaddress.46


MULTICASTNODEclassifier_dmux_AgentAgentagents_AgentNode entryentry_switch_MulticastClassifierReplic<strong>at</strong>orsmulticlassifier_LinkLinkLinkFigure 5.2: Internal Structure of a Multicast Node.5.2 Node Methods: Configuring the NodeProcedures to configure an individual node can be classified into:— Control functio<strong>ns</strong>— Address <strong>and</strong> Port number management, unicast routing functio<strong>ns</strong>— Agent management— Adding neighborsWe describe each of the functio<strong>ns</strong> in the following paragraphs.Control functio<strong>ns</strong>1. $node entry retur<strong>ns</strong> the entry point for a node. This is the first element which will h<strong>and</strong>le packets arriving <strong>at</strong> th<strong>at</strong>node.47


<strong>The</strong> Node i<strong>ns</strong>tance variable, entry_, stores the reference this element. For unicast nodes, this is the address classifierth<strong>at</strong> looks <strong>at</strong> the higher bits of the destin<strong>at</strong>ion address. <strong>The</strong> i<strong>ns</strong>tance variable, classifier_ contai<strong>ns</strong> the referenceto this classifier. However, for multicast nodes, the entry point is the switch_ which looks <strong>at</strong> the first bit to decidewhether it should forward the packet to the unicast classifier, or the multicast classifier as appropri<strong>at</strong>e.2. $node reset will reset all agents <strong>at</strong> the node.Address <strong>and</strong> Port number management <strong>The</strong> procedure $node id retur<strong>ns</strong> the node number of the node. This numberis autom<strong>at</strong>ically incremented <strong>and</strong> assigned to each node <strong>at</strong> cre<strong>at</strong>ion by the class Simul<strong>at</strong>or method, $<strong>ns</strong> node.<strong>The</strong> classSimul<strong>at</strong>or also stores an i<strong>ns</strong>tance variable array 1 , Node_, indexed by the node id, <strong>and</strong> contai<strong>ns</strong> a reference to the node withth<strong>at</strong> id.<strong>The</strong> procedure $node agent 〈port〉 retur<strong>ns</strong> the h<strong>and</strong>le of the agent <strong>at</strong> the specified port. If no agent <strong>at</strong> the specified portnumber is available, the procedure retur<strong>ns</strong> the null string.<strong>The</strong> procedure alloc-port retur<strong>ns</strong> the next available port number. It uses an i<strong>ns</strong>tance variable, np_, to track the nextunalloc<strong>at</strong>ed port number.<strong>The</strong> procedures, add-route <strong>and</strong> add-routes, are used by unicast routing (Chapter 29) to add routes to popul<strong>at</strong>e theclassifier_ <strong>The</strong> usage syntax is $node add-route 〈destin<strong>at</strong>ion id〉 〈TclObject〉. TclObject is theentry of dmux_, the port demultiplexer <strong>at</strong> the node, if the destin<strong>at</strong>ion id is the same as this node’s id, it is often the head of alink to send packets for th<strong>at</strong> destin<strong>at</strong>ion to, but could also be the the entry for other classifiers or types of classifiers.$node add-routes 〈destin<strong>at</strong>ion id〉 〈TclObjects〉 is used to add multiple routes to the same destin<strong>at</strong>ion th<strong>at</strong>must be used simultaneously in round robin manner to spread the b<strong>and</strong>width used to reach th<strong>at</strong> destin<strong>at</strong>ion across all linksequally. It is used only if the i<strong>ns</strong>tance variable multiP<strong>at</strong>h_ is set to 1, <strong>and</strong> detailed dynamic routing str<strong>at</strong>egies are in effect,<strong>and</strong> requires the use of a multiP<strong>at</strong>h classifier. We describe the implement<strong>at</strong>ion of the multiP<strong>at</strong>h classifier l<strong>at</strong>er in this chapter(Section 5.4); however, we defer the discussion of multip<strong>at</strong>h routing (Chapter 29) to the chapter on unicast routing.<strong>The</strong> dual of add-routes{} is delete-routes{}. It takes the id, a list of TclObjects, <strong>and</strong> a reference to the simul<strong>at</strong>or’snullagent. It removes the TclObjects in the list from the i<strong>ns</strong>talled routes in the multip<strong>at</strong>h classifier. If the route entryin the classifier does not point to a multip<strong>at</strong>h classifier, the routine simply clears the entry from classifier_, <strong>and</strong> i<strong>ns</strong>tallsthe nullagent in its place.Detailed dynamic routing also uses two additional methods: the i<strong>ns</strong>tance procedure init-routing{} sets the i<strong>ns</strong>tancevariable multiP<strong>at</strong>h_ to be equal to the class variable of the same name. It also adds a reference to the route controllerobject <strong>at</strong> th<strong>at</strong> node in the i<strong>ns</strong>tance variable, rtObject_. <strong>The</strong> procedure rtObject?{} retur<strong>ns</strong> the h<strong>and</strong>le for the routeobject <strong>at</strong> the node.Finally, the procedure intf-changed{} is invoked by the network dynamics code if a link incident on the node changesst<strong>at</strong>e. Additional details on how this procedure is used are discussed l<strong>at</strong>er in the chapter on network dynamics (Chapter 31).Agent management Given an 〈agent〉, the procedure <strong>at</strong>tach{} will add the agent to its list of agents_, assign a portnumber the agent <strong>and</strong> set its source address, set the target of the agent to be its (i.e., the node’s) entry{}, <strong>and</strong> add a pointerto the port demultiplexer <strong>at</strong> the node (dmux_) to the agent <strong>at</strong> the corresponding slot in the dmux_ classifier.Conversely, detach{}will remove the agent from agents_, <strong>and</strong> point the agent’s target, <strong>and</strong> the entry in the node dmux_to nullagent.1 i.e., an i<strong>ns</strong>tance variable of a class th<strong>at</strong> is also an array variable48


Tracking Neighbors Each node keeps a list of its adjacent neighbors in its i<strong>ns</strong>tance variable, neighbor_. <strong>The</strong> procedureadd-neighbor{} adds a neighbor to the list. <strong>The</strong> procedure neighbors{} retur<strong>ns</strong> this list.5.3 Node Configur<strong>at</strong>ion InterfaceNOTE: This API, especially its internal implement<strong>at</strong>ion which is messy <strong>at</strong> this point, is still a moving target. It may undergosignificant changes in the near future. However, we will do our best to maintain the same interface as described in this chapter.In addition, this API currently does not cover all existing nodes in the old form<strong>at</strong>, namely, nodes built using inheritance, <strong>and</strong>parts of mobile IP. It is principally oriented towards wireless <strong>and</strong> s<strong>at</strong>ellite simul<strong>at</strong>ion. [Sep 15, 2000; upd<strong>at</strong>ed June 2001].Simul<strong>at</strong>or::node-config{} accommod<strong>at</strong>es flexible <strong>and</strong> modular co<strong>ns</strong>truction of different node definitio<strong>ns</strong> within thesame base Node class. For i<strong>ns</strong>tance, to cre<strong>at</strong>e a mobile node capable of wireless communic<strong>at</strong>ion, one no longer needs aspecialized node cre<strong>at</strong>ion comm<strong>and</strong>, e.g., dsdv-cre<strong>at</strong>e-mobile-node{}; i<strong>ns</strong>tead, one changes default configur<strong>at</strong>ionparameters, such as$<strong>ns</strong> node-config -adhocRouting dsdvbefore actually cre<strong>at</strong>ing the node with the comm<strong>and</strong>: $<strong>ns</strong> node. Together with routing modules, this allows one to combine“arbitrary” routing functionalities within a single node without resorting to multiple inheritance <strong>and</strong> other fancy objectgimmicks. We will describe this in more detail in Section 5.5. <strong>The</strong> functio<strong>ns</strong> <strong>and</strong> procedures relevant to the new node APIsmay be found in ~<strong>ns</strong>/tcl/lib/<strong>ns</strong>-node.tcl.<strong>The</strong> node configur<strong>at</strong>ion interface co<strong>ns</strong>ists of two parts. <strong>The</strong> first part deals with node configur<strong>at</strong>ion, while the second partactually cre<strong>at</strong>es nodes of the specified type. We have already seen the l<strong>at</strong>ter in Section 5.1, in this section we will describe theconfigur<strong>at</strong>ion part.Node configur<strong>at</strong>ion essentially co<strong>ns</strong>ists of defining the different node characteristics before cre<strong>at</strong>ing them. <strong>The</strong>y may co<strong>ns</strong>istof the type of addressing structure used in the simul<strong>at</strong>ion, defining the network components for mobilenodes, turning on oroff the trace optio<strong>ns</strong> <strong>at</strong> Agent/Router/MAC levels, selecting the type of adhoc routing protocol for wireless nodes or definingtheir energy model.As an example, node-configur<strong>at</strong>ion for a wireless, mobile node th<strong>at</strong> ru<strong>ns</strong> AODV as its adhoc routing protocol in a hierarchicaltopology would be as shown below. We decide to turn tracing on <strong>at</strong> the agent <strong>and</strong> router level only. Also we assume a topologyhas been i<strong>ns</strong>tanti<strong>at</strong>ed with "set topo [new Topography]". <strong>The</strong> node-config comm<strong>and</strong> would look like the following:$<strong>ns</strong>_ node-config -addressType hierarchical \-adhocRouting AODV \-llType LL \-macType Mac/802_11 \-ifqType Queue/DropTail/PriQueue \-ifqLen 50 \-antType Antenna/OmniAntenna \-propType Propag<strong>at</strong>ion/TwoRayGround \-phyType Phy/WirelessPhy \-topologyI<strong>ns</strong>tance $topo \-channel Channel/WirelessChannel \-agentTrace ON \-routerTrace ON \-macTrace OFF \-movementTrace OFF49


<strong>The</strong> default values for all the above optio<strong>ns</strong> are NULL except -addressingType whose default value is fl<strong>at</strong>. <strong>The</strong> option-reset can be used to reset all node-config parameters to their default value.Note th<strong>at</strong> the config comm<strong>and</strong> can be broken down into separ<strong>at</strong>e lines like$<strong>ns</strong>_ node-config -addressingType hier$<strong>ns</strong>_ node-config -macTrace ON<strong>The</strong> optio<strong>ns</strong> th<strong>at</strong> need to be changed may only be called. For example after configuring for AODV mobilenodes as shownabove (<strong>and</strong> after cre<strong>at</strong>ing AODV mobilenodes), we may configure for AODV base-st<strong>at</strong>ion nodes in the following way:$<strong>ns</strong>_ node-config -wiredRouting ONWhile all other fe<strong>at</strong>ures for base-st<strong>at</strong>ion nodes <strong>and</strong> mobilenodes are same, the base-st<strong>at</strong>ion nodes are capable of wired routing,while mobilenodes are not. In this way we can change node-configur<strong>at</strong>ion only when it is required.All node i<strong>ns</strong>tances cre<strong>at</strong>ed after a given node-configur<strong>at</strong>ion comm<strong>and</strong> will have the same property unless a part or all of thenode-config comm<strong>and</strong> is executed with different parameter values. And all parameter values remain unchanged unless theyare expicitly changed. So after cre<strong>at</strong>ion of the AODV base-st<strong>at</strong>ion <strong>and</strong> mobilenodes, if we want to cre<strong>at</strong>e simple nodes, wewill use the following node-configur<strong>at</strong>ion comm<strong>and</strong>:$<strong>ns</strong>_ node-config -resetThis will set all parameter values to their default setting which basically defines configur<strong>at</strong>ion of a simple node.Currently, this type of node configur<strong>at</strong>ion is oriented towards wireless <strong>and</strong> s<strong>at</strong>ellite nodes. Table 5.1 lists the available optio<strong>ns</strong>for these kinds of nodes. <strong>The</strong> example scripts ~<strong>ns</strong>/tcl/ex/simple-wireless.tcl <strong>and</strong> ~<strong>ns</strong>/tcl/ex/s<strong>at</strong>-mixed.tcl provide usageexamples.5.4 <strong>The</strong> Classifier<strong>The</strong> function of a node when it receives a packet is to examine the packet’s fields, usually its destin<strong>at</strong>ion address, <strong>and</strong> onoccasion, its source address. It should then map the values to an outgoing interface object th<strong>at</strong> is the next dow<strong>ns</strong>treamrecipient of this packet.In <strong>ns</strong>, this task is performed by a simple classifier object. Multiple classifier objects, each looking <strong>at</strong> a specific portion of thepacket forward the packet through the node. A node in <strong>ns</strong> uses many different types of classifiers for different purposes. Thissection describes some of the more common, or simpler, classifier objects in <strong>ns</strong>.We begin with a description of the base class in this section. <strong>The</strong> next subsectio<strong>ns</strong> describe the address classifier (Section5.4.1), the multicast classifier (Section 5.4.2), the multip<strong>at</strong>h classifier (Section 5.4.3), the hash classifier (Section 5.4.4),<strong>and</strong> finally, the replic<strong>at</strong>or (Section 5.4.5).A classifier provides a way to m<strong>at</strong>ch a packet agai<strong>ns</strong>t some logical criteria <strong>and</strong> retrieve a reference to another simul<strong>at</strong>ionobject based on the m<strong>at</strong>ch results. Each classifier contai<strong>ns</strong> a table of simul<strong>at</strong>ion objects indexed by slot number. <strong>The</strong> job ofa classifier is to determine the slot number associ<strong>at</strong>ed with a received packet <strong>and</strong> forward th<strong>at</strong> packet to the object referencedby th<strong>at</strong> particular slot. <strong>The</strong> C++ class Classifier (defined in ~<strong>ns</strong>/classifier.h) provides a base class from which otherclassifiers are derived.50


option available values defaultgeneraladdressType fl<strong>at</strong>, hierarchical fl<strong>at</strong>MPLS ON, OFF OFFboth s<strong>at</strong>ellite- <strong>and</strong> wireless-orientedwiredRouting ON, OFF OFFllType LL, LL/S<strong>at</strong> ""macTypeMac/802_11, Mac/Csma/Ca, Mac/S<strong>at</strong>,Mac/S<strong>at</strong>/U<strong>ns</strong>lottedAloha, Mac/Tdma ""ifqType Queue/DropTail, Queue/DropTail/PriQueue ""phyType Phy/WirelessPhy, Phy/S<strong>at</strong> ""adhocRoutingwireless-orientedDIFFUSION/RATE, DIFFUSION/PROB, DSDV,DSR, FLOODING, OMNIMCAST, AODV, TORA ""propType Propag<strong>at</strong>ion/TwoRayGround, Propag<strong>at</strong>ion/Shadowing ""propI<strong>ns</strong>tance Propag<strong>at</strong>ion/TwoRayGround, Propag<strong>at</strong>ion/Shadowing ""antType Antenna/OmniAntenna ""channel Channel/WirelessChannel, Channel/S<strong>at</strong> ""topoI<strong>ns</strong>tance ""mobileIP ON, OFF OFFenergyModel EnergyModel ""initialEnergy ""rxPower ""txPower ""idlePower ""agentTrace ON, OFF OFFrouterTrace ON, OFF OFFmacTrace ON, OFF OFFmovementTrace ON, OFF OFFerrProc UniformErrorProc ""FECProc ? ?toraDebug ON, OFF OFFs<strong>at</strong>ellite-orienteds<strong>at</strong>NodeType polar, geo, terminal, geo-repe<strong>at</strong>er ""downlinkBW ""Table 5.1: Available optio<strong>ns</strong> for node configur<strong>at</strong>ion (see tcl/lib/<strong>ns</strong>-lib.tcl).class Classifier : public NsObject {public:~Classifier();void recv(Packet*, H<strong>and</strong>ler* h = 0);protected:Classifier();void i<strong>ns</strong>tall(int slot, NsObject*);void clear(int slot);virtual int comm<strong>and</strong>(int argc, co<strong>ns</strong>t char*co<strong>ns</strong>t* argv);virtual int classify(Packet *co<strong>ns</strong>t) = 0;void alloc(int);NsObject** slot_; /* table th<strong>at</strong> maps slot number to a NsObject */int <strong>ns</strong>lot_;int maxslot_;};51


<strong>The</strong> classify() method is pure virtual, indic<strong>at</strong>ing the class Classifier is to be used only as a base class. <strong>The</strong> alloc()method dynamically alloc<strong>at</strong>es enough space in the table to hold the specified number of slots. <strong>The</strong> i<strong>ns</strong>tall() <strong>and</strong> clear()methods add or remove objects from the table. <strong>The</strong> recv() method <strong>and</strong> the OTcl interface are implemented as follows in~<strong>ns</strong>/classifier.cc:/** objects only ever see "packet" events, which come either* from an incoming link or a local agent (i.e., packet source).*/void Classifier::recv(Packet* p, H<strong>and</strong>ler*){NsObject* node;int cl = classify(p);if (cl < 0 || cl >= <strong>ns</strong>lot_ || (node = slot_[cl]) == 0) {Tcl::i<strong>ns</strong>tance().evalf("%s no-slot %d", name(), cl);Packet::free(p);return;}node->recv(p);}int Classifier::comm<strong>and</strong>(int argc, co<strong>ns</strong>t char*co<strong>ns</strong>t* argv){Tcl& tcl = Tcl::i<strong>ns</strong>tance();if (argc == 3) {/** $classifier clear $slot*/if (strcmp(argv[1], "clear") == 0) {int slot = <strong>at</strong>oi(argv[2]);clear(slot);return (TCL_OK);}/** $classifier i<strong>ns</strong>tallNext $node*/if (strcmp(argv[1], "i<strong>ns</strong>tallNext") == 0) {int slot = maxslot_ + 1;NsObject* node = (NsObject*)TclObject::lookup(argv[2]);i<strong>ns</strong>tall(slot, node);tcl.resultf("%u", slot);return TCL_OK;}if (strcmp(argv[1], "slot") == 0) {int slot = <strong>at</strong>oi(argv[2]);if ((slot >= 0) || (slot < <strong>ns</strong>lot_)) {tcl.resultf("%s", slot_[slot]->name());return TCL_OK;}tcl.resultf("Classifier: no object <strong>at</strong> slot %d", slot);return (TCL_ERROR);}} else if (argc == 4) {/*52


}* $classifier i<strong>ns</strong>tall $slot $node*/if (strcmp(argv[1], "i<strong>ns</strong>tall") == 0) {int slot = <strong>at</strong>oi(argv[2]);NsObject* node = (NsObject*)TclObject::lookup(argv[3]);i<strong>ns</strong>tall(slot, node);return (TCL_OK);}}return (NsObject::comm<strong>and</strong>(argc, argv));When a classifier recv()’s a packet, it h<strong>and</strong>s it to the classify() method. This is defined differently in each type ofclassifier derived from the base class. <strong>The</strong> usual form<strong>at</strong> is for the classify() method to determine <strong>and</strong> return a slot indexinto the table of slots. If the index is valid, <strong>and</strong> points to a valid TclObject, the classifier will h<strong>and</strong> the packet to th<strong>at</strong> objectusing th<strong>at</strong> object’s recv() method. If the index is not valid, the classifier will invoke the i<strong>ns</strong>tance procedure no-slot{} to<strong>at</strong>tempt to popul<strong>at</strong>e the table correctly. However, in the base class Classifier::no-slot{} prints <strong>and</strong> error message<strong>and</strong> termin<strong>at</strong>es execution.<strong>The</strong> comm<strong>and</strong>() method provides the following i<strong>ns</strong>tproc-likes to the interpreter:• clear{〈slot〉} clears the entry in a particular slot.• i<strong>ns</strong>tallNext{〈object〉} i<strong>ns</strong>talls the object in the next available slot, <strong>and</strong> retur<strong>ns</strong> the slot number.Note th<strong>at</strong> this i<strong>ns</strong>tproc-like is overloaded by an i<strong>ns</strong>tance procedure of the same name th<strong>at</strong> stores a reference to the objectstored. This then helps quick query of the objects i<strong>ns</strong>talled in the classifier from OTcl.• slot{〈index〉} retur<strong>ns</strong> the object stored in the specified slot.• i<strong>ns</strong>tall{〈index〉, 〈object〉} i<strong>ns</strong>talls the specified 〈object〉 <strong>at</strong> the slot 〈index〉.Note th<strong>at</strong> this i<strong>ns</strong>tproc-like too is overloaded by an i<strong>ns</strong>tance procedure of the same name th<strong>at</strong> stores a reference to theobject stored. This is also to quickly query of the objects i<strong>ns</strong>talled in the classifier from OTcl.5.4.1 Address ClassifiersAn address classifier is used in supporting unicast packet forwarding. It applies a bitwise shift <strong>and</strong> mask oper<strong>at</strong>ion to apacket’s destin<strong>at</strong>ion address to produce a slot number. <strong>The</strong> slot number is returned from the classify() method. <strong>The</strong>class AddressClassifier (defined in ~<strong>ns</strong>/classifier-addr.cc) ide defined as follows:class AddressClassifier : public Classifier {public:AddressClassifier() : mask_(~0), shift_(0) {bind("mask_", (int*)&mask_);bind("shift_", &shift_);}protected:int classify(Packet *co<strong>ns</strong>t p) {IPHeader *h = IPHeader::access(p->bits());return ((h->dst() >> shift_) & mask_);}<strong>ns</strong>addr_t mask_;int shift_;53


};<strong>The</strong> class imposes no direct semantic meaning on a packet’s destin<strong>at</strong>ion address field. R<strong>at</strong>her, it retur<strong>ns</strong> some number of bitsfrom the packet’s dst_ field as the slot number used in the Classifier::recv() method. <strong>The</strong> mask_ <strong>and</strong> shift_values are set through OTcl.5.4.2 Multicast Classifiers<strong>The</strong> multicast classifier classifies packets according to both source <strong>and</strong> destin<strong>at</strong>ion (group) addresses. It maintai<strong>ns</strong> a (chainedhash) table mapping source/group pairs to slot numbers. When a packet arrives containing a source/group unknown to theclassifier, it invokes an Otcl procedure Node::new-group{} to add an entry to its table. This OTcl procedure may use themethod set-hash to add new (source, group, slot) 3-tuples to the classifier’s table. <strong>The</strong> multicast classifier is defined in~<strong>ns</strong>/classifier-mcast.cc as follows:st<strong>at</strong>ic class MCastClassifierClass : public TclClass {public:MCastClassifierClass() : TclClass("Classifier/Multicast") {}TclObject* cre<strong>at</strong>e(int argc, co<strong>ns</strong>t char*co<strong>ns</strong>t* argv) {return (new MCastClassifier());}} class_mcast_classifier;class MCastClassifier : public Classifier {public:MCastClassifier();~MCastClassifier();protected:int comm<strong>and</strong>(int argc, co<strong>ns</strong>t char*co<strong>ns</strong>t* argv);int classify(Packet *co<strong>ns</strong>t p);int findslot();void set_hash(<strong>ns</strong>addr_t src, <strong>ns</strong>addr_t dst, int slot);int hash(<strong>ns</strong>addr_t src, <strong>ns</strong>addr_t dst) co<strong>ns</strong>t {u_int32_t s = src ^ dst;s ^= s >> 16;s ^= s >> 8;return (s & 0xff);}struct hashnode {int slot;<strong>ns</strong>addr_t src;<strong>ns</strong>addr_t dst;hashnode* next;};hashnode* ht_[256];co<strong>ns</strong>t hashnode* lookup(<strong>ns</strong>addr_t src, <strong>ns</strong>addr_t dst) co<strong>ns</strong>t;};int MCastClassifier::classify(Packet *co<strong>ns</strong>t pkt){IPHeader *h = IPHeader::access(pkt->bits());<strong>ns</strong>addr_t src = h->src() >> 8; /*XXX*/54


}<strong>ns</strong>addr_t dst = h->dst();co<strong>ns</strong>t hashnode* p = lookup(src, dst);if (p == 0) {/** Didn’t find an entry.* Call tcl exactly once to i<strong>ns</strong>tall one.* If tcl doesn’t come through then fail.*/Tcl::i<strong>ns</strong>tance().evalf("%s new-group %u %u", name(), src, dst);p = lookup(src, dst);if (p == 0)return (-1);}return (p->slot);<strong>The</strong> class MCastClassifiermplements a chained hash table <strong>and</strong> applies a hash function on both the packet source<strong>and</strong> destin<strong>at</strong>ion addresses. <strong>The</strong> hash function retur<strong>ns</strong> the slot number to index the slot_ table in the underlying object. Ahash miss implies packet delivery to a previously-unknown group; OTcl is called to h<strong>and</strong>le the situ<strong>at</strong>ion. <strong>The</strong> OTcl code isexpected to i<strong>ns</strong>ert an appropri<strong>at</strong>e entry into the hash table.5.4.3 MultiP<strong>at</strong>h ClassifierThis object is devised to support equal cost multip<strong>at</strong>h forwarding, where the node has multiple equal cost routes to the samedestin<strong>at</strong>ion, <strong>and</strong> would like to use all of them simultaneously. This object does not look <strong>at</strong> any field in the packet. Withevery succeeding packet, it simply retur<strong>ns</strong> the next filled slot in round robin fashion. <strong>The</strong> definitio<strong>ns</strong> for this classifier are in~<strong>ns</strong>/classifier-mp<strong>at</strong>h.cc, <strong>and</strong> are shown below:class MultiP<strong>at</strong>hForwarder : public Classifier {public:MultiP<strong>at</strong>hForwarder() : <strong>ns</strong>_(0), Classifier() {}virtual int classify(Packet* co<strong>ns</strong>t) {int cl;int fail = <strong>ns</strong>_;do {cl = <strong>ns</strong>_++;<strong>ns</strong>_ %= (maxslot_ + 1);} while (slot_[cl] == 0 && <strong>ns</strong>_ != fail);return cl;}priv<strong>at</strong>e:int <strong>ns</strong>_; /* next slot to be used. Probably a misnomer? */};5.4.4 Hash ClassifierThis object is used to classify a packet as a member of a particular flow. As their name indic<strong>at</strong>es, hash classifiers use ahash table internally to assign packets to flows. <strong>The</strong>se objects are used where flow-level inform<strong>at</strong>ion is required (e.g. in55


flow-specific queuing disciplines <strong>and</strong> st<strong>at</strong>istics collection). Several “flow granularities” are available. In particular, packetsmay be assigned to flows based on flow ID, destin<strong>at</strong>ion address, source/destin<strong>at</strong>ion addresses, or the combin<strong>at</strong>ion ofsource/destin<strong>at</strong>ion addresses plus flow ID. <strong>The</strong> fields accessed by the hash classifier are limited to the ip header: src(),dst(), flowid() (see ip.h).<strong>The</strong> hash classifier is cre<strong>at</strong>ed with an integer argument specifying the initial size of its hash table. <strong>The</strong> current hash tablesize may be subsequently altered with the resize method (see below). When cre<strong>at</strong>ed, the i<strong>ns</strong>tance variables shift_ <strong>and</strong>mask_ are initialized with the simul<strong>at</strong>or’s current NodeShift <strong>and</strong> NodeMask values, respectively. <strong>The</strong>se values are retrievedfrom the AddrParams object when the hash classifier is i<strong>ns</strong>tanti<strong>at</strong>ed. <strong>The</strong> hash classifier will fail to oper<strong>at</strong>e properly if theAddrParams structure is not initialized. <strong>The</strong> following co<strong>ns</strong>tructors are used for the various hash classifiers:Classifier/Hash/SrcDestClassifier/Hash/DestClassifier/Hash/FidClassifier/Hash/SrcDestFid<strong>The</strong> hash classifier receives packets, classifies them according to their flow criteria, <strong>and</strong> retrieves the classifier slot indic<strong>at</strong>ingthe next node th<strong>at</strong> should receive the packet. In several circumstances with hash classifiers, most packets should be associ<strong>at</strong>edwith a single slot, while only a few flows should be directed elsewhere. <strong>The</strong> hash classifier includes a default_ i<strong>ns</strong>tancevariable indic<strong>at</strong>ing which slot is to be used for packets th<strong>at</strong> do not m<strong>at</strong>ch any of the per-flow criteria. <strong>The</strong> default_ may beset optionally.<strong>The</strong> methods for a hash classifier are as follows:$hashcl set-hash buck src dst fid slot$hashcl lookup buck src dst fid$hashcl del-hash src dst fid$hashcl resize nbuck<strong>The</strong> set-hash() method i<strong>ns</strong>erts a new entry into the hash table within the hash classifier. <strong>The</strong> buck argument specifiesthe hash table bucket number to use for the i<strong>ns</strong>ertion of this entry. When the bucket number is not known, buck may bespecified as auto. <strong>The</strong> src, dst <strong>and</strong> fid arguments specify the IP source, destin<strong>at</strong>ion, <strong>and</strong> flow IDs to be m<strong>at</strong>ched forflow classific<strong>at</strong>ion. Fields not used by a particular classifier (e.g. specifying src for a flow-id classifier) is ignored. <strong>The</strong> slotargument indic<strong>at</strong>es the index into the underlying slot table in the base Classifier object from which the hash classifier isderived. <strong>The</strong> lookup function retur<strong>ns</strong> the name of the object associ<strong>at</strong>ed with the given buck/src/dst/fid tuple. <strong>The</strong>buck argument may be auto, as for set-hash. <strong>The</strong> del-hash function removes the specified entry from the hash table.Currently, this is done by simply marking the entry as inactive, so it is possible to popul<strong>at</strong>e the hash table with unused entries.<strong>The</strong> resize function resizes the hash table to include the number of buckets specified by the argument nbuck.Provided no default is defined, a hash classifier will perform a call into OTcl when it receives a packet which m<strong>at</strong>ches no flowcriteria. <strong>The</strong> call takes the following form:$obj unknown-flow src dst flowid buckThus, when a packet m<strong>at</strong>ching no flow criteria is received, the method unknown-flow of the i<strong>ns</strong>tanti<strong>at</strong>ed hash classifierobject is invoked with the source, destin<strong>at</strong>ion, <strong>and</strong> flow id fields from the packet. In addition, the buck field indic<strong>at</strong>es the hashbucket which should contain this flow if it were i<strong>ns</strong>erted using set-hash. This arrangement avoids another hash lookupwhen performing i<strong>ns</strong>ertio<strong>ns</strong> into the classifier when the bucket is already known.56


5.4.5 Replic<strong>at</strong>or<strong>The</strong> replic<strong>at</strong>or is different from the other classifiers we have described earlier, in th<strong>at</strong> it does not use the classify function.R<strong>at</strong>her, it simply uses the classifier as a table of n slots; it overloads the recv() method to produce n copies of a packet, th<strong>at</strong>are delivered to all n objects referenced in the table.To support multicast packet forwarding, a classifier receiving a multicast packet from source S destined for group G computesa hash function h(S, G) giving a “slot number” in the classifier’s object table. In multicast delivery, the packet must be copiedonce for each link leading to nodes subscribed to G minus one. Production of additional copies of the packet is performed bya Replic<strong>at</strong>or class, defined in replic<strong>at</strong>or.cc:/** A replic<strong>at</strong>or is not really a packet classifier but* we simply find convenience in leveraging its slot table.* (this object used to implement fan-out on a multicast* router as well as broadcast LANs)*/class Replic<strong>at</strong>or : public Classifier {public:Replic<strong>at</strong>or();void recv(Packet*, H<strong>and</strong>ler* h = 0);virtual int classify(Packet* co<strong>ns</strong>t) {};protected:int ignore_;};void Replic<strong>at</strong>or::recv(Packet* p, H<strong>and</strong>ler*){IPHeader *iph = IPHeader::access(p->bits());if (maxslot_ < 0) {if (!ignore_)Tcl::i<strong>ns</strong>tance().evalf("%s drop %u %u", name(),iph->src(), iph->dst());Packet::free(p);return;}for (int i = 0; i < maxslot_; ++i) {NsObject* o = slot_[i];if (o != 0)o->recv(p->copy());}/* we know th<strong>at</strong> maxslot is non-null */slot_[maxslot_]->recv(p);}As we can see from the code, this class does not really classify packets. R<strong>at</strong>her, it replic<strong>at</strong>es a packet, one for each entry inits table, <strong>and</strong> delivers the copies to each of the nodes listed in the table. <strong>The</strong> last entry in the table gets the “original” packet.Since the classify() method is pure virtual in the base class, the replic<strong>at</strong>or defines an empty classify() method.57


5.5 Routing Module <strong>and</strong> Classifier Organiz<strong>at</strong>ionAs we have seen, a <strong>ns</strong> node is essentially a collection of classifiers. <strong>The</strong> simplest node (unicast) contai<strong>ns</strong> only one addressclassifier <strong>and</strong> one port classifier, as shown in Figure 5.1. When one extends the functionality of the node, more classifiers areadded into the base node, for i<strong>ns</strong>tance, the multicast node shown in Figure 5.2. As more function blocks is added, <strong>and</strong> each ofthese blocks requires its own classifier(s), it becomes important for the node to provide a uniform interface to organize theseclassifiers <strong>and</strong> to bridge these classifiers to the route comput<strong>at</strong>ion blocks.<strong>The</strong> classical method to h<strong>and</strong>le this case is through class inheritance. For i<strong>ns</strong>tance, if one wants a node th<strong>at</strong> supports hierarchicalrouting, one simply derive a Node/Hier from the base node <strong>and</strong> override the classifier setup methods to i<strong>ns</strong>ert hierarchicalclassifiers. This method works well when the new function blocks are independent <strong>and</strong> cannot be “arbitrarily” mixed. Fori<strong>ns</strong>tance, both hierarchical routing <strong>and</strong> ad hoc routing use their own set of classifiers. Inheritance would require th<strong>at</strong> we haveNode/Hier th<strong>at</strong> supports the former, <strong>and</strong> Node/Mobile for the l<strong>at</strong>ter. This becomes slightly problem<strong>at</strong>ic when one wants an adhoc routing node th<strong>at</strong> supports hierarchical routing. In this simple case one may use multiple inheritance to solve the problem,but this quickly becomes infeasible as the number of such function blocks increases.<strong>The</strong> only method to solve this problem is object composition. <strong>The</strong> base node needs to define a set of interfaces for classifieraccess <strong>and</strong> organiz<strong>at</strong>ion. <strong>The</strong>se interfaces should• allow individual routing modules th<strong>at</strong> implement their own classifiers to i<strong>ns</strong>ert their classifiers into the node;• allow route comput<strong>at</strong>ion blocks to popul<strong>at</strong>e routes to classifiers in all routing modules th<strong>at</strong> need this inform<strong>at</strong>ion,• provide a single point of management for existing routing modules.In addition, we should also define a uniform interface for routing modules to connect to the node interfaces, so as to providea system<strong>at</strong>ic approach to extending node functionality. In this section we will describe the design of routing modules as wellas th<strong>at</strong> of the corresponding node interfaces.5.5.1 Routing ModuleIn general, every routing implement<strong>at</strong>ion in <strong>ns</strong> co<strong>ns</strong>ists of three function blocks:• Routing agent exchanges routing packet with neighbors,• Route logic uses the inform<strong>at</strong>ion g<strong>at</strong>hered by routing agents (or the global topology d<strong>at</strong>abase in the case of st<strong>at</strong>ic routing)to perform the actual route comput<strong>at</strong>ion,• Classifiers sit i<strong>ns</strong>ide a Node. <strong>The</strong>y use the computed routing table to perform packet forwarding.Notice th<strong>at</strong> when implementing a new routing protocol, one does not necessarily implement all of these three blocks. Fori<strong>ns</strong>tance, when one implements a link st<strong>at</strong>e routing protocol, one simply implement a routing agent th<strong>at</strong> exchanges inform<strong>at</strong>ionin the link st<strong>at</strong>e manner, <strong>and</strong> a route logic th<strong>at</strong> does Dijkstra on the resulting topology d<strong>at</strong>abase. It can then use the sameclassifiers as other unicast routing protocols.When a new routing protocol implement<strong>at</strong>ion includes more than one function blocks, especially when it contai<strong>ns</strong> its ownclassifier, it is desirable to have another object, which we call a routing module, th<strong>at</strong> manages all these function blocks <strong>and</strong> tointerface with node to organize its classifiers. Figure 5.3 shows functional rel<strong>at</strong>ion among these objects. Notice th<strong>at</strong> routingmodules may have direct rel<strong>at</strong>io<strong>ns</strong>hip with route comput<strong>at</strong>ion blocks, i.e., route logic <strong>and</strong>/or routing agents. However, routecomput<strong>at</strong>ion MAY not i<strong>ns</strong>tall their routes directly through a routing module, because there may exists other modules th<strong>at</strong>58


RoutingModulesRtModule/Baseroutingadd-routedelete-routeBaseHierNoderoutingadd-routedelete-routeRouteComput<strong>at</strong>iontra<strong>ns</strong>port<strong>at</strong>tachdetachMcasttra<strong>ns</strong>port<strong>at</strong>tachdetachUserSimul<strong>at</strong>ionManagementregisterunregisterMPLS......Classifieri<strong>ns</strong>ert-entryi<strong>ns</strong>tall-entryi<strong>ns</strong>tall-demuxFigure 5.3: Interaction among node, routing module, <strong>and</strong> routing. <strong>The</strong> dashed line shows the details of one routing module.are interested in learning about the new routes. This is not a requirement, however, because it is possible th<strong>at</strong> some routecomput<strong>at</strong>ion is specific to one particular routing module, for i<strong>ns</strong>tance, label i<strong>ns</strong>tall<strong>at</strong>ion in the MPLS module.A routing module contai<strong>ns</strong> three major functionalities:1. A routing module initializes its connection to a node through register{}, <strong>and</strong> tears the connection down viaunregister{}. Usually, in register{} a routing module (1) tells the node whether it interests in knowing routeupd<strong>at</strong>es <strong>and</strong> tra<strong>ns</strong>port agent <strong>at</strong>tachments, <strong>and</strong> (2) cre<strong>at</strong>es its classifiers <strong>and</strong> i<strong>ns</strong>tall them in the node (details describedin the next subsection). In unregister{} a routing module does the exact opposite: it deletes its classifiers <strong>and</strong>removes its hooks on routing upd<strong>at</strong>e in the node.2. If a routing module is interested in knowing routing upd<strong>at</strong>es, the node will inform the module viaRtModule::add-route{dst, target} <strong>and</strong> RtModule::delete-route{dst, nullagent}.3. If a routing module is interested in learning about tra<strong>ns</strong>port agent <strong>at</strong>tachment <strong>and</strong> detachment in a node, the node willinform the module viaRtModule::<strong>at</strong>tach{agent, port} <strong>and</strong> RtModule::detach{agent, nullagent}.<strong>The</strong>re are two steps to write your own routing module:1. You need to declare the C++ part of your routing module (see ~<strong>ns</strong>/rtmodule.{cc,h}). For many modules this onlymea<strong>ns</strong> to declare a virtual method name() which retur<strong>ns</strong> a string descriptor of the module. However, you are freeto implement as much functionality as you like in C++; if necessary you may l<strong>at</strong>er move functionality from OTcl intoC++ for better performance.2. You need to look <strong>at</strong> the above interfaces implemented in the base routing module (see ~<strong>ns</strong>/tcl/lib/<strong>ns</strong>-rtmodule.tcl) <strong>and</strong>decide which one you’ll inherit, which one you’ll override, <strong>and</strong> put them in OTcl interfaces of your own module.<strong>The</strong>re are several derived routing module examples in ~<strong>ns</strong>/tcl/lib/<strong>ns</strong>-rtmodule.tcl, which may serve as templ<strong>at</strong>es for yourmodules.Currently, there are six routing modules implemented in <strong>ns</strong>:59


Module NameRtModule/BaseRtModule/McastRtModule/HierRtModule/<strong>Manual</strong>RtModule/VCRtModule/MPLSFunctionalityInterface to unicast routing protocols. Provide basic functionality to add/delete route <strong>and</strong><strong>at</strong>tach/detach agents.Interface to multicast routing protocols. Its only purpose is establishes multicast classifiers.All other multicast functionalities are implemented as i<strong>ns</strong>tprocs of Node. This should beconverted in the future.Hierarchical routing. It’s a wrapper for managing hierarchical classifiers <strong>and</strong> route i<strong>ns</strong>tall<strong>at</strong>ion.Can be combined with other routing protocols, e.g., ad hoc routing.<strong>Manual</strong> routing.Uses virtual classifier i<strong>ns</strong>tead of vanilla classifier.Implements MPLS functionality. This is the only existing module th<strong>at</strong> is completely selfcontained<strong>and</strong> does not pollute the Node namespace.Table 5.2: Available routing modules5.5.2 Node InterfaceTo connect to the above interfaces of routing module, a node provides a similar set of interfaces:• In order to know which module to register during cre<strong>at</strong>ion, the Node class keeps a list of modules as a class variable.<strong>The</strong> default value of this list contai<strong>ns</strong> only the base routing module. <strong>The</strong> Node class provides the following two procsto manipul<strong>at</strong>e this module list:Node::enable-module{[name]}Node::disable-module{[name]}If module RtModule/[name] exists, this proc puts [name] into the modulelist.If [name] is in the module list, remove it from the list.When a node is cre<strong>at</strong>ed, it goes through the module list of the Node class, cre<strong>at</strong>es all modules included in the list, <strong>and</strong>register these modules <strong>at</strong> the node.After a node is cre<strong>at</strong>ed, one may use the following i<strong>ns</strong>tprocs to list modules registered <strong>at</strong> the node, or to get a h<strong>and</strong>le ofa module with a particular name:Node::list-modules{}Node::get-module{[name]}Return a list of the h<strong>and</strong>les (shadow objects) of all registered modules.Return a h<strong>and</strong>le of the registered module whose name m<strong>at</strong>ches the given one. Noticeth<strong>at</strong> any routing module can only have a single i<strong>ns</strong>tance registered <strong>at</strong> any node.• To allow routing modules register their interests of routing upd<strong>at</strong>es, a node object provide the following i<strong>ns</strong>tprocs:Node::route-notify{module}Node::unreg-route-notify{module}Add module into route upd<strong>at</strong>e notific<strong>at</strong>ion list.Remove module from route upd<strong>at</strong>e notific<strong>at</strong>ion list.Similarly, the following i<strong>ns</strong>tprocs provide hooks on the <strong>at</strong>tachment of tra<strong>ns</strong>port agents:Node::port-notify{module}Node::unreg-port-notify{module}Add module into agent <strong>at</strong>tachment notific<strong>at</strong>ion list.Remove module from agent <strong>at</strong>tachment notific<strong>at</strong>ion list.Notice th<strong>at</strong> in all of these i<strong>ns</strong>tprocs, parameter module should be a module h<strong>and</strong>le i<strong>ns</strong>tead of a module name.• Node provides the following i<strong>ns</strong>tprocs to manipul<strong>at</strong>e its address <strong>and</strong> port classifiers:– Node::i<strong>ns</strong>ert-entry{module, clsfr, hook} i<strong>ns</strong>erts classifier clsfr into the entry point of the node. It alsoassoci<strong>at</strong>es the new classifier with module so th<strong>at</strong> if this classifier is removed l<strong>at</strong>er, module will be unregistered.If hook is specified as a number, the existing classifier will be i<strong>ns</strong>erted into slot hook of the new classifier. Inthis way, one may establish a “chain” of classifiers; see Figure 5.2 for an example. NOTE: clsfr needs NOT60


to be a classifier. In some cases one may want to put an agent, or any class derived from Connector, <strong>at</strong> the entrypoint of a node. In such cases, one simply supplies target to parameter hook.– Node::i<strong>ns</strong>tall-entry{module, clsfr, hook} differs from Node::i<strong>ns</strong>ert-entry in th<strong>at</strong> it deletes theexisting classifier <strong>at</strong> the node entry point, unregisters any associ<strong>at</strong>ed routing module, <strong>and</strong> i<strong>ns</strong>talls the new classifier<strong>at</strong> th<strong>at</strong> point. If hook is given, <strong>and</strong> the old classifier is connected into a classifier chain, it will connect the chaininto slot hook of the new classifier. As above, if hook equals to target, clsfr will be tre<strong>at</strong>ed as an objectderived from Connector i<strong>ns</strong>tead of a classifier.– Node::i<strong>ns</strong>tall-demux{demux, port} places the given classifier demux as the default demultiplexer. Ifport is given, it plugs the existing demultiplexer into slot port of the new one. Notice th<strong>at</strong> in either case it doesnot delete the existing demultiplexer.5.6 Comm<strong>and</strong>s <strong>at</strong> a glanceFollowing is a list of common node comm<strong>and</strong>s used in simul<strong>at</strong>ion scripts:$<strong>ns</strong>_ node []Comm<strong>and</strong> to cre<strong>at</strong>e <strong>and</strong> return a node i<strong>ns</strong>tance. If is given, assign the node address to be . Note th<strong>at</strong>the l<strong>at</strong>ter MUST only be used when hierarchical addressing is enabled via either set-address-form<strong>at</strong>hierarchical{} or node-config -addressType hierarchical{}.$<strong>ns</strong>_ node-config - This comm<strong>and</strong> is used to configure nodes. <strong>The</strong> different config-parameters are addressingType, different type of the networkstack components, whether tracing will be turned on or not, mobileIP flag is truned or not, energy model is being used or notetc. An option -reset maybe used to set the node configur<strong>at</strong>ion to its default st<strong>at</strong>e. <strong>The</strong> default setting of node-config, i.e if novalues are specified, cre<strong>at</strong>es a simple node (base class Node) with fl<strong>at</strong> addressing/routing. For the syntax details seeSection 5.3.$node idRetur<strong>ns</strong> the id number of the node.$node node-addrRetur<strong>ns</strong> the address of the node. In case of fl<strong>at</strong> addressing, the node address is same as its node-id. In case of hierarchicaladdressing, the node address in the form of a string (viz. "1.4.3") is returned.$node resetResets all agent <strong>at</strong>tached to this node.$node agent Retur<strong>ns</strong> the h<strong>and</strong>le of the agent <strong>at</strong> the specified port. If no agent is found <strong>at</strong> the given port, a null string is returned.$node entryRetur<strong>ns</strong> the entry point for the node. This is first object th<strong>at</strong> h<strong>and</strong>les packet receiving <strong>at</strong> this node.$node <strong>at</strong>tach Attaches the to this node. Incase no specific port number is passed, the node alloc<strong>at</strong>es a port number <strong>and</strong> binds theagent to this port. Thus once the agent is <strong>at</strong>tached, it receives packets destined for this host (node) <strong>and</strong> port.$node detach This is the dual of "<strong>at</strong>tach" described above. It detaches the agent from this node <strong>and</strong> i<strong>ns</strong>talls a null-agent to the port thisagent was <strong>at</strong>tached. This is done to h<strong>and</strong>le tra<strong>ns</strong>it packets th<strong>at</strong> may be destined to the detached agent. <strong>The</strong>se on-the-flypackets are then sinked <strong>at</strong> the null-agent.61


$node neighborsThis retur<strong>ns</strong> the list of neighbors for the node.$node add-neighbor This is a comm<strong>and</strong> to add to the list of neighbors maintained by the node.Following is a list of internal node methods:$node add-route This is used in unicast routing to popul<strong>at</strong>e the classifier. <strong>The</strong> target is a Tcl object, which may be the entry of dmux_ (portdemultiplexer in the node) incase the is same as this node-id. Otherwise it is usually the head of thelink for th<strong>at</strong> destin<strong>at</strong>ion. It could also be the entry for other classifiers.$node alloc-port This retur<strong>ns</strong> the next available port number.$node incr-rtgtable-size<strong>The</strong> i<strong>ns</strong>tance variable rtsize_ is used to keep track of size of routing-table in each node. This comm<strong>and</strong> is used toincrease the routing-table size every time an routing-entry is added to the classifiers.<strong>The</strong>re are other node comm<strong>and</strong>s th<strong>at</strong> supports hierarchical routing, detailed dynamic routing, equal cost multip<strong>at</strong>h routing,manual routing, <strong>and</strong> energy model for mobile nodes. <strong>The</strong>se <strong>and</strong> other methods described earlier can be found in~<strong>ns</strong>/tcl/lib/<strong>ns</strong>-node.tcl <strong>and</strong> ~<strong>ns</strong>/tcl/lib/<strong>ns</strong>-mobilenode.tcl.62


Chapter 6Links: Simple LinksThis is the second aspect of defining the topology. In the previous chapter (Chapter 5), we had described how to cre<strong>at</strong>e thenodes in the topology in <strong>ns</strong>. We now describe how to cre<strong>at</strong>e the links to connect the nodes <strong>and</strong> complete the topology. In thischapter, we restrict ourselves to describing the simple point to point links. <strong>ns</strong> supports a variety of other media, including anemul<strong>at</strong>ion of a multi-access LAN using a mesh of simple links, <strong>and</strong> other true simul<strong>at</strong>ion of wireless <strong>and</strong> broadcast media.<strong>The</strong>y will be described in a separ<strong>at</strong>e chapter. <strong>The</strong> CBQlink is derived from simple links <strong>and</strong> is a co<strong>ns</strong>iderably more complexform of link th<strong>at</strong> is also not described in this chapter.We begin by describing the comm<strong>and</strong>s to cre<strong>at</strong>e a link in this section. As with the node being composed of classifiers, a simplelink is built up from a sequence of connectors. We also briefly describe some of the connectors in a simple link. We thendescribe the i<strong>ns</strong>tance procedures th<strong>at</strong> oper<strong>at</strong>e on the various components of defined by some of these connectors (Section 6.1).We conclude the chapter with a description the connector object (Section 6.2), including brief descriptio<strong>ns</strong> of the commonlink connectors.<strong>The</strong> class Link is a st<strong>and</strong>alone class in OTcl, th<strong>at</strong> provides a few simple primitives. <strong>The</strong> class SimpleLink providesthe ability to connect two nodes with a point to point link. <strong>ns</strong> provides the i<strong>ns</strong>tance procedure simplex-link{} to form aunidirectional link from one node to another. <strong>The</strong> link is in the class SimpleLink. <strong>The</strong> following describes the syntax of thesimplex link:set <strong>ns</strong> [new Simul<strong>at</strong>or]$<strong>ns</strong> simplex-link 〈node0〉 〈node1〉 〈b<strong>and</strong>width〉 〈delay〉 〈queue_type〉<strong>The</strong> comm<strong>and</strong> cre<strong>at</strong>es a link from 〈node0〉 to 〈node1〉, with specified 〈b<strong>and</strong>width〉 <strong>and</strong> 〈delay〉 characteristics. <strong>The</strong>link uses a queue of type 〈queue_type〉. <strong>The</strong> procedure also adds a TTL checker to the link. Five i<strong>ns</strong>tance variables definethe link:head_ Entry point to the link, it points to the first object in the link.queue_ Reference to the main queue element of the link. Simple links usuallyhave one queue per link. Other more complex types of links may havemultiple queue elements in the link.link_ A reference to the element th<strong>at</strong> actually models the link, in terms of thedelay <strong>and</strong> b<strong>and</strong>width characteristics of the link.ttl_ Reference to the element th<strong>at</strong> manipul<strong>at</strong>es the ttl in every packet.drophead_ Reference to an object th<strong>at</strong> is the head of a queue of elements th<strong>at</strong> processlink drops.In addition, if the simul<strong>at</strong>or i<strong>ns</strong>tance variable, $traceAllFile_, is defined, the procedure will add trace elements th<strong>at</strong>63


Linkhead_enqT_queue_ deqT_ link_ ttl_rcvT_drophead_drpT_Figure 6.1: Composite Co<strong>ns</strong>truction of a Unidirectional Linktrack when a packet is enqueued <strong>and</strong> dequeued from queue_. Furthermore, tracing interposes a drop trace element after thedrophead_. <strong>The</strong> following i<strong>ns</strong>tance variables track the trace elements:enqT_ Reference to the element th<strong>at</strong> traces packets entering queue_.deqT_ Reference to the element th<strong>at</strong> traces packets leaving queue_.drpT_ Reference to the element th<strong>at</strong> traces packets dropped from queue_.rcvT_ Reference to the element th<strong>at</strong> traces packets received by the next node.Note however, th<strong>at</strong> if the user enable tracing multiple times on the link, these i<strong>ns</strong>tance variables will only store a reference tothe last elements i<strong>ns</strong>erted.Other configur<strong>at</strong>ion mechanisms th<strong>at</strong> add components to a simple link are network interfaces (used in multicast routing),link dynamics models, <strong>and</strong> tracing <strong>and</strong> monitors. We give a brief overview of the rel<strong>at</strong>ed objects <strong>at</strong> the end of this chapter(Section 6.2), <strong>and</strong> discuss their functionality/implement<strong>at</strong>ion in other chapters.<strong>The</strong> i<strong>ns</strong>tance procedure duplex-link{} co<strong>ns</strong>tructs a bi-directional link from two simplex links.6.1 I<strong>ns</strong>tance Procedures for Links <strong>and</strong> SimpleLinksLink procedures <strong>The</strong> class Link is implemented entirely in Otcl. <strong>The</strong> OTcl SimpleLink class uses the C++LinkDelay class to simul<strong>at</strong>e packet delivery delays. <strong>The</strong> i<strong>ns</strong>tance procedures in the class Link are:64


head{}queue{}link{}up{}down{}up?{}all-connectors{}cost{}cost?{}retur<strong>ns</strong> the h<strong>and</strong>le for head_.retur<strong>ns</strong> the h<strong>and</strong>le for queue_.retur<strong>ns</strong> the h<strong>and</strong>le for the delay element, link_.set link st<strong>at</strong>us to “up” in the dynamics_ element. Also, writes out a trace line to each filespecified through the procedure trace-dynamics{}.As with up{}, set link st<strong>at</strong>us to “down” in the dynamics_ element. Also, writes out a traceline to each file specified through the procedure trace-dynamics{}.retur<strong>ns</strong> st<strong>at</strong>us of the link. St<strong>at</strong>us is “up” or “down”; st<strong>at</strong>us is “up” if link dynamics is not enabled.Apply specified oper<strong>at</strong>ion to all connectors on the link.p An example of such usage is linkall-connectors reset.set link cost to value specified.retur<strong>ns</strong> the cost of the link. Default cost of link is 1, if no cost has been specified earlier.SimpleLink Procedures <strong>The</strong> Otcl class SimpleLink implements a simple point-to-point link with an associ<strong>at</strong>edqueue <strong>and</strong> delay 1 . It is derived from the base Otcl class Link as follows:Class SimpleLink -superclass LinkSimpleLink i<strong>ns</strong>tproc init { src dst bw delay q { lltype "DelayLink" } } {$self next $src $dst$self i<strong>ns</strong>tvar link_ queue_ head_ toNode_ ttl_...set queue_ $qset link_ [new Delay/Link]$link_ set b<strong>and</strong>width_ $bw$link_ set delay_ $delay$queue_ target $link_$link_ target [$toNode_ entry]}...# XXX# put the ttl checker after the delay# so we don’t have to worry about accounting# for ttl-drops within the trace <strong>and</strong>/or monitor# fabric#set ttl_ [new TTLChecker]$ttl_ target [$link_ target]$link_ target $ttl_Notice th<strong>at</strong> when a SimpleLink object is cre<strong>at</strong>ed, new Delay/Link <strong>and</strong> TTLChecker objects are also cre<strong>at</strong>ed. Notealso th<strong>at</strong>, the Queue object must have already been cre<strong>at</strong>ed.<strong>The</strong>re are two additional methods implemented (in OTcl) as part of the SimpleLink class: trace <strong>and</strong> init-monitor.<strong>The</strong>se functio<strong>ns</strong> are described in further detail in the section on tracing (Chapter 26).1 <strong>The</strong> current version also includes an object to examine the network layer “ttl” field <strong>and</strong> discard packets if the field reaches zero.65


6.2 ConnectorsConnectors, unlink classifiers, only gener<strong>at</strong>e d<strong>at</strong>a for one recipient; either the packet is delivered to the target_ neighbor,or it is sent to he drop-target_.A connector will receive a packet, perform some function, <strong>and</strong> deliver the packet to its neighbor, or drop the packet. <strong>The</strong>reare a number of different types of connectors in <strong>ns</strong>. Each connector performs a different function.networkinterfaceDynaLinkDelayLinkQueuesTTLCheckerlabels packets with incoming interface identifier—it is used by some multicast routing protocols. <strong>The</strong>class variable “Simul<strong>at</strong>or NumberInterfaces_ 1” tells <strong>ns</strong> to add these interfaces, <strong>and</strong> then, it is addedto either end of the simplex link. Multicast routing protocols are discussed in a separ<strong>at</strong>e chapter(Chapter 30).Object th<strong>at</strong> g<strong>at</strong>es traffic depending on whether the link is up or down. It expects to be <strong>at</strong> the head of thelink, <strong>and</strong> is i<strong>ns</strong>erted on the link just prior to simul<strong>at</strong>ion start. It’s st<strong>at</strong>us_ variable control whetherthe link is up or down. <strong>The</strong> description of how the DynaLink object is used is in a separ<strong>at</strong>e chapter(Chapter 31).Object th<strong>at</strong> models the link’s delay <strong>and</strong> b<strong>and</strong>width characteristics. If the link is not dynamic, then thisobject simply schedules receive events for the dow<strong>ns</strong>tream object for each packet it receives <strong>at</strong> theappropri<strong>at</strong>e time for th<strong>at</strong> packet. However, if the link is dynamic, then it queues the packets internally,<strong>and</strong> schedules one receives event for itself for the next packet th<strong>at</strong> must be delivered. Thus, if thelink goes down <strong>at</strong> some point, this object’s reset() method is invoked, <strong>and</strong> the object will drop allpackets in tra<strong>ns</strong>it <strong>at</strong> the i<strong>ns</strong>tant of link failure. We discuss the specifics of this class in another chapter(Chapter 8).model the output buffers <strong>at</strong>tached to a link in a “real” router in a network. In <strong>ns</strong>, they are <strong>at</strong>tached to,<strong>and</strong> are co<strong>ns</strong>idered as part of the link. We discuss the details of queues <strong>and</strong> different types of queuesin <strong>ns</strong>in another chapter (Chapter 7).will decrement the ttl in each packet th<strong>at</strong> it receives. If th<strong>at</strong> ttl then has a positive value, the packet isforwarded to the next element on the link. In the simple links, TTLCheckers are autom<strong>at</strong>ically added,<strong>and</strong> are placed as the last element on the link, between the delay element, <strong>and</strong> the entry for the nextnode.6.3 Object hierarchy<strong>The</strong> base class used to represent links is called Link. Methods for this class are listed in the next section. Other link objectsderived from the base class are given as follows:• SimpleLink Object A SimpleLink object is used to represent a simple unidirectional link. <strong>The</strong>re are no st<strong>at</strong>e variablesor configur<strong>at</strong>ion parameters associ<strong>at</strong>ed with this object. Methods for this class are: $simplelink enable-mcast This tur<strong>ns</strong> on multicast for the link by cre<strong>at</strong>ing an incoming network interface for the destin<strong>at</strong>ion <strong>and</strong> adds an outgoinginterface for the source.$simplelink trace Build trace objects for this link <strong>and</strong> upd<strong>at</strong>e object linkage. If op is specified as "nam" cre<strong>at</strong>e nam trace files.$simplelink nam-trace Sets up nam tracing in the link.$simplelink trace-dynamics This sets up tracing specially for dynamic links. allows setting up of nam tracing as well.66


$simplelink init-monitor I<strong>ns</strong>ert objects th<strong>at</strong> allow us to monitor the queue size of this link. Return the name of the object th<strong>at</strong> can be queried todetermine the average queue size.$simplelink <strong>at</strong>tach-monitors This is similar to init-monitor, but allows for specific<strong>at</strong>ion of more of the items.$simplelink dynamicSets up the dynamic flag for this link.$simplelink errormodule I<strong>ns</strong>erts an error module before the queue.$simpleilnk i<strong>ns</strong>ert-linkloss I<strong>ns</strong>erts the error module after the queue.//Other link objects derived from class SimpleLink are FQLink, CBQLink <strong>and</strong> IntServLink.Configur<strong>at</strong>ion parameters for FQLink are:queueManagement_ <strong>The</strong> type of queue management used in the link. Default value is DropTail.No configur<strong>at</strong>ion parameters are specified for CBQLink <strong>and</strong> IntServLink objects.• DelayLink Object <strong>The</strong> DelayLink Objects determine the amount of time required for a packet to traverse a link. This isdefined to be size/bw + delay where size is the packet size, bw is the link b<strong>and</strong>width <strong>and</strong> delay is the link propag<strong>at</strong>iondelay. <strong>The</strong>re are no methods or st<strong>at</strong>e variables associ<strong>at</strong>ed with this object.Configur<strong>at</strong>ion Parameters are:b<strong>and</strong>width_ Link b<strong>and</strong>width in bits per second.delay_ Link propag<strong>at</strong>ion delay in seconds.6.4 Comm<strong>and</strong>s <strong>at</strong> a glanceFollowing is a list of common link comm<strong>and</strong>s used in simul<strong>at</strong>ion scripts:$<strong>ns</strong>_ simplex-link This comm<strong>and</strong> cre<strong>at</strong>es an unidirectional link between node1 <strong>and</strong> node2 with specified b<strong>and</strong>width (BW) <strong>and</strong> delaycharacteristics. <strong>The</strong> link uses a queue type of <strong>and</strong> depending on the queue type different arguments are passedthrough .$<strong>ns</strong>_ duplex-link This cre<strong>at</strong>es a bi-directional link between node1 <strong>and</strong> node2. This procedure essentially cre<strong>at</strong>es a duplex-link from twosimplex links, one from node1 to node2 <strong>and</strong> the other from node2 to node1. <strong>The</strong> syntax for duplex-link is same as th<strong>at</strong> ofsimplex-link described above.$<strong>ns</strong>_ duplex-intserv-link This cre<strong>at</strong>es a duplex-link between n1 <strong>and</strong> n2 with queue type of intserv, with specified BW <strong>and</strong> delay. This type of queueimplements a scheduler with two level services priority. <strong>The</strong> type of intserv queue is given by , with admissioncontrol unit type of <strong>and</strong> signal module of type .$<strong>ns</strong>_ simplex-link-op This is used to set <strong>at</strong>tributes for a simplex link. <strong>The</strong> <strong>at</strong>tributes may be the orient<strong>at</strong>ion, color, label, or queue-position.$<strong>ns</strong>_ duplex-link-op This comm<strong>and</strong> is used to set link <strong>at</strong>tributes (like orient<strong>at</strong>ion of the links, color, label, or queue-position) for duplex links.67


$<strong>ns</strong>_ link-lossmodel This function gener<strong>at</strong>es losses (using the loss model i<strong>ns</strong>erted in the link between node <strong>and</strong> node) inthe link th<strong>at</strong> can be visualized by nam.$<strong>ns</strong>_ lossmodel This is used to i<strong>ns</strong>ert a loss module in regular links.Following is a list of internal link-rel<strong>at</strong>ed procedures:$<strong>ns</strong>_ register-nam-linkconfig This is an internal procedure used by "$link orient" to register/upd<strong>at</strong>e the order in which links should be cre<strong>at</strong>ed innam.$<strong>ns</strong>_ remove-nam-linkconfig This procedure is used to remove any duplic<strong>at</strong>e links (duplic<strong>at</strong>e links may be cre<strong>at</strong>ed by GT-ITM topology gener<strong>at</strong>or).$link headRetur<strong>ns</strong> the i<strong>ns</strong>tance variable head_ for the link. <strong>The</strong> head_ is the entry pont to the link <strong>and</strong> it points to the first object inthe link.$link add-to-head This allows the object to be now pointed by the head_ element in the link, i.e, now becomes thefirst object in the link.$link linkRetur<strong>ns</strong> the i<strong>ns</strong>tance variable link_. <strong>The</strong> link_ is the element in the link th<strong>at</strong> actually models the link in terms of delay<strong>and</strong> b<strong>and</strong>width characteristics of the link.$link queueRetur<strong>ns</strong> the i<strong>ns</strong>tance variable queue_. queue_ is queue element in the link. <strong>The</strong>re may be one or more queue elements ina particular link.$link cost This sets a link cost of .$link cost?Retur<strong>ns</strong> the cost value for the link. Default cost of link is set to 1.$link if-label?Retur<strong>ns</strong> the network interfaces associ<strong>at</strong>ed with the link (for multicast routing).$link upThis sets the link st<strong>at</strong>us to "up". This comm<strong>and</strong> is a part of network dynamics support in <strong>ns</strong>.$link downSimilar to up, this comm<strong>and</strong> marks the link st<strong>at</strong>us as "down".$link up?Retur<strong>ns</strong> the link st<strong>at</strong>us. <strong>The</strong> st<strong>at</strong>us is always "up" as default, if link dynamics is not enabled.$link all-connectors opThis comm<strong>and</strong> applies the specified oper<strong>at</strong>ion to all connectors in the link. Like, $link all-connectorsreset or $link all-connectors isDynamic.68


$link i<strong>ns</strong>tall-error This i<strong>ns</strong>talls an error module after the link_ element.In addition to the Link <strong>and</strong> link-rel<strong>at</strong>ed comm<strong>and</strong>s listed above, there are other procedures to support the specificrequirements of different types of links derived from the base class "Link" like simple-link (SimpleLink), integr<strong>at</strong>ed service(IntServLink), class-based queue (CBQLink), fair queue (FQLink) <strong>and</strong> procedures to support multicast routing, sessio<strong>ns</strong>im,nam etc. <strong>The</strong>se <strong>and</strong> the above procedures may be found in <strong>ns</strong>/tcl/lib(<strong>ns</strong>-lib.tcl, <strong>ns</strong>-link.tcl, <strong>ns</strong>-intserv.tcl, <strong>ns</strong>-namsupp.tcl,<strong>ns</strong>-queue.tcl), <strong>ns</strong>/tcl/mcast/(McastMonitor.tcl, <strong>ns</strong>-mcast.tcl), <strong>ns</strong>/tcl/session/session.tcl.69


Chapter 7Queue Management <strong>and</strong> Packet SchedulingQueues represent loc<strong>at</strong>io<strong>ns</strong> where packets may be held (or dropped). Packet scheduling refers to the decision process usedto choose which packets should be serviced or dropped. Buffer management refers to any particular discipline used toregul<strong>at</strong>e the occupancy of a particular queue. At present, support is included for drop-tail (FIFO) queueing, RED buffermanagement, CBQ (including a priority <strong>and</strong> round-robin scheduler), <strong>and</strong> variants of Fair Queueing including, Fair Queueing(FQ), Stochastic Fair Queueing (SFQ), <strong>and</strong> Deficit Round-Robin (DRR). In the common case where a delay element isdow<strong>ns</strong>tream from a queue, the queue may be blocked until it is re-enabled by its dow<strong>ns</strong>tream neighbor. This is the mechanismby which tra<strong>ns</strong>mission delay is simul<strong>at</strong>ed. In addition, queues may be forcibly blocked or unblocked <strong>at</strong> arbitrary times bytheir neighbors (which is used to implement multi-queue aggreg<strong>at</strong>e queues with inter-queue flow control). Packet drops areimplemented in such a way th<strong>at</strong> queues contain a “drop destin<strong>at</strong>ion”; th<strong>at</strong> is, an object th<strong>at</strong> receives all packets dropped by aqueue. This can be useful to (for example) keep st<strong>at</strong>istics on dropped packets.7.1 <strong>The</strong> C++ Queue Class<strong>The</strong> Queue class is derived from a Connector base class. It provides a base class used by particular types of (derived)queue classes, as well as a call-back function to implement blocking (see next section). <strong>The</strong> following definitio<strong>ns</strong> are providedin queue.h:class Queue : public Connector {public:virtual void enque(Packet*) = 0;virtual Packet* deque() = 0;void recv(Packet*, H<strong>and</strong>ler*);void resume();int blocked();void unblock();void block();protected:Queue();int comm<strong>and</strong>(int argc, co<strong>ns</strong>t char*co<strong>ns</strong>t* argv);int qlim_; /* maximum allowed pkts in queue */int blocked_;int unblock_on_resume_; /* unblock q on idle? */QueueH<strong>and</strong>ler qh_;70


};<strong>The</strong> enque <strong>and</strong> deque functio<strong>ns</strong> are pure virtual, indic<strong>at</strong>ing the Queue class is to be used as a base class; particular queuesare derived from Queue <strong>and</strong> implement these two functio<strong>ns</strong> as necessary. Particular queues do not, in general, override therecv function because it invokes the the particular enque <strong>and</strong> deque.<strong>The</strong> Queue class does not contain much internal st<strong>at</strong>e. Often these are special monitoring objects (Chapter 26). <strong>The</strong> qlim_member is co<strong>ns</strong>tructed to dict<strong>at</strong>e a bound on the maximum queue occupancy, but this is not enforced by the Queue classitself; it must be used by the particular queue subclasses if they need this value. <strong>The</strong> blocked_ member is a booleanindic<strong>at</strong>ing whether the queue is able to send a packet immedi<strong>at</strong>ely to its dow<strong>ns</strong>tream neighbor. When a queue is blocked, it isable to enqueue packets but not send them.7.1.1 Queue blockingA queue may be either blocked or unblocked <strong>at</strong> any given time. Generally, a queue is blocked when a packet is in tra<strong>ns</strong>itbetween it <strong>and</strong> its dow<strong>ns</strong>tream neighbor (most of the time if the queue is occupied). A blocked queue will remain blocked aslong as it dow<strong>ns</strong>tream link is busy <strong>and</strong> the queue has <strong>at</strong> least one packet to send. A queue becomes unblocked only when itsresume function is invoked (by mea<strong>ns</strong> of a dow<strong>ns</strong>tream neighbor scheduling it via a callback), usually when no packets arequeued. <strong>The</strong> callback is implemented by using the following class <strong>and</strong> methods:class QueueH<strong>and</strong>ler : public H<strong>and</strong>ler {public:inline QueueH<strong>and</strong>ler(Queue& q) : queue_(q) {}void h<strong>and</strong>le(Event*); /* calls queue_.resume() */priv<strong>at</strong>e:Queue& queue_;};void QueueH<strong>and</strong>ler::h<strong>and</strong>le(Event*){queue_.resume();}Queue::Queue() : drop_(0), blocked_(0), qh_(*this){Tcl& tcl = Tcl::i<strong>ns</strong>tance();bind("limit_", &qlim_);}void Queue::recv(Packet* p, H<strong>and</strong>ler*){enque(p);if (!blocked_) {/** We’re not block. Get a packet <strong>and</strong> send it on.* We perform an extra check because the queue* might drop the packet even if it was* previously empty! (e.g., RED can do this.)*/p = deque();if (p != 0) {blocked_ = 1;target_->recv(p, &qh_);71


}}}void Queue::resume(){Packet* p = deque();if (p != 0)target_->recv(p, &qh_);else {if (unblock_on_resume_)blocked_ = 0;elseblocked_ = 1;}}<strong>The</strong> h<strong>and</strong>ler management here is somewh<strong>at</strong> subtle. When a new Queue object is cre<strong>at</strong>ed, it includes a QueueH<strong>and</strong>lerobject (qh_) which is initialized to contain a reference to the new Queue object (Queue& QueueH<strong>and</strong>ler::queue_).This is performed by the Queue co<strong>ns</strong>tructor using the expression qh_(*this). When a Queue receives a packet it callsthe subclass (i.e. queueing discipline-specific) version of the enque function with the packet. If the queue is not blocked,it is allowed to send a packet <strong>and</strong> calls the specific deque function which determines which packet to send, blocks thequeue (because a packet is now in tra<strong>ns</strong>it), <strong>and</strong> sends the packet to the queue’s dow<strong>ns</strong>tream neighbor. Note th<strong>at</strong> any futurepackets received from upstream neighbors will arrive to a blocked queue. When a dow<strong>ns</strong>tream neighbor wishes to causethe queue to become unblocked it schedules the QueueH<strong>and</strong>ler’s h<strong>and</strong>le function by passing &qh_ to the simul<strong>at</strong>or scheduler.<strong>The</strong> h<strong>and</strong>le function invokes resume, which will send the next-scheduled packet dow<strong>ns</strong>tream (<strong>and</strong> leave the queueblocked), or unblock the queue when no packet is ready to be sent. This process is made more clear by also referring to theLinkDelay::recv() method (Section 8.1).7.1.2 PacketQueue Class<strong>The</strong> Queue class may implement buffer management <strong>and</strong> scheduling but do not implement the low-level oper<strong>at</strong>io<strong>ns</strong> on aparticular queue. <strong>The</strong> PacketQueue class is used for this purpose, <strong>and</strong> is defined as follows (see queue.h):class PacketQueue {public:PacketQueue();int length(); /* queue length in packets */void enque(Packet* p);Packet* deque();Packet* lookup(int n);/* remove a specific packet, which must be in the queue */void remove(Packet*);protected:Packet* head_;Packet** tail_;int len_;// packet count};This class maintai<strong>ns</strong> a linked-list of packets, <strong>and</strong> is commonly used by particular scheduling <strong>and</strong> buffer management disciplinesto hold an ordered set of packets. Particular scheduling or buffer management schemes may make use of several72


PacketQueue objects. <strong>The</strong> PacketQueue class maintai<strong>ns</strong> current counts of the number of packets held in the queuewhich is returned by the length() method. <strong>The</strong> enque function places the specified packet <strong>at</strong> the end of the queue <strong>and</strong>upd<strong>at</strong>es the len_ member variable. <strong>The</strong> deque function retur<strong>ns</strong> the packet <strong>at</strong> the head of the queue <strong>and</strong> removes it fromthe queue (<strong>and</strong> upd<strong>at</strong>es the counters), or retur<strong>ns</strong> NULL if the queue is empty. <strong>The</strong> lookup function retur<strong>ns</strong> the nth packetfrom the head of the queue, or NULL otherwise. <strong>The</strong> remove function deletes the packet stored in the given address fromthe queue (<strong>and</strong> upd<strong>at</strong>es the counters). It causes an abnormal program termin<strong>at</strong>ion if the packet does not exist.7.2 Example: Drop Tail<strong>The</strong> following example illustr<strong>at</strong>es the implement<strong>at</strong>ion of the Queue/DropTail object, which implements FIFO scheduling<strong>and</strong> drop-on-overflow buffer management typical of most present-day Internet routers. <strong>The</strong> following definitio<strong>ns</strong> declare theclass <strong>and</strong> its OTcl linkage:/** A bounded, drop-tail queue*/class DropTail : public Queue {protected:void enque(Packet*);Packet* deque();PacketQueue q_;};<strong>The</strong> base class Queue, from which DropTail is derived, provides most of the needed functionality. <strong>The</strong> drop-tail queuemaintai<strong>ns</strong> exactly one FIFO queue, implemented by including an object of the PacketQueue class. Drop-tail implementsits own versio<strong>ns</strong> of enque <strong>and</strong> deque as follows:/** drop-tail*/void DropTail::enque(Packet* p){q_.enque(p);if (q_.length() >= qlim_) {q_.remove(p);drop(p);}}Packet* DropTail::deque(){return (q_.deque());}Here, the enque function first stores the packet in the internal packet queue (which has no size restrictio<strong>ns</strong>), <strong>and</strong> then checksthe size of the packet queue versus qlim_. Drop-on-overflow is implemented by dropping the packet most recently addedto the packet queue if the limit is reached or exceeded. Note: in the implement<strong>at</strong>ion of enque above, setting qlim_ to nactually mea<strong>ns</strong> a queue size of n-1. Simple FIFO scheduling is implemented in the deque function by always returning thefirst packet in the packet queue.73


7.3 Different types of Queue objectsA queue object is a general class of object capable of holding <strong>and</strong> possibly marking or discarding packets as they travelthrough the simul<strong>at</strong>ed topology. Configur<strong>at</strong>ion Parameters used for queue objects are:limit_ <strong>The</strong> queue size in packets.blocked_ Set to false by default, this is true if the queue is blocked (unable to send a packet to its dow<strong>ns</strong>tream neighbor).unblock_on_resume_ Set to true by default, indic<strong>at</strong>es a queue should unblock itself <strong>at</strong> the time the last packet packet senthas been tra<strong>ns</strong>mitted (but not necessarily received).Other queue objects derived from the base class Queue are drop-tail, FQ, SFQ, DRR, RED <strong>and</strong> CBQ queue objects. Each aredescribed as follows:• Drop-tail objects: Drop-tail objects are a subclass of Queue objects th<strong>at</strong> implement simple FIFO queue. <strong>The</strong>re are nomethods, configur<strong>at</strong>ion parameter, or st<strong>at</strong>e variables th<strong>at</strong> are specific to drop-tail objects.• FQ objects: FQ objects are a subclass of Queue objects th<strong>at</strong> implement Fair queuing. <strong>The</strong>re are no methods th<strong>at</strong> arespecific to FQ objects. Configur<strong>at</strong>ion Parameters are:secsPerByte_<strong>The</strong>re are no st<strong>at</strong>e variables associ<strong>at</strong>ed with this object.• SFQ objects: SFQ objects are a subclass of Queue objects th<strong>at</strong> implement Stochastic Fair queuing. <strong>The</strong>re are nomethods th<strong>at</strong> are specific to SFQ objects. Configur<strong>at</strong>ion Parameters are:maxqueue_buckets_<strong>The</strong>re are no st<strong>at</strong>e variables associ<strong>at</strong>ed with this object.• DRR objects: DRR objects are a subclass of Queue objects th<strong>at</strong> implement deficit round robin scheduling. <strong>The</strong>seobjects implement deficit round robin scheduling amongst different flows ( A particular flow is one which has packetswith the same node <strong>and</strong> port id OR packets which have the same node id alone). Also unlike other multi-queue objects,this queue object implements a single shared buffer space for its different flows. Configur<strong>at</strong>ion Parameters are:buckets_ Indic<strong>at</strong>es the total number of buckets to be used for hashing each of the flows.blimit_ Indic<strong>at</strong>es the shared buffer size in bytes.quantum_ Indic<strong>at</strong>es (in bytes) how much each flow can send during its turn.mask_ mask_, when set to 1, mea<strong>ns</strong> th<strong>at</strong> a particular flow co<strong>ns</strong>ists of packets having the same node id (<strong>and</strong> possiblydifferent port ids), otherwise a flow co<strong>ns</strong>ists of packets having the same node <strong>and</strong> port ids.• RED objects: RED objects are a subclass of Queue objects th<strong>at</strong> implement r<strong>and</strong>om early-detection g<strong>at</strong>eways. <strong>The</strong>object can be configured to either drop or “mark” packets. <strong>The</strong>re are no methods th<strong>at</strong> are specific to RED objects.Configur<strong>at</strong>ion Parameters are:bytes_ Set to "true" to enable “byte-mode” RED, where the size of arriving packets affect the likelihood of marking(dropping) packets.queue-in-bytes_ Set to "true" to measure the average queue size in bytes r<strong>at</strong>her than packets. Enabling this option alsocauses thresh_ <strong>and</strong> maxthresh_ to be autom<strong>at</strong>ically scaled by mean_pktsize_ (see below).thresh_ <strong>The</strong> minimum threshold for the average queue size in packets.74


maxthresh_ <strong>The</strong> maximum threshold for the average queue size in packets.mean_pktsize_ A rough estim<strong>at</strong>e of the average packet size in bytes. Used in upd<strong>at</strong>ing the calcul<strong>at</strong>ed average queuesize after an idle period.q_weight_ <strong>The</strong> queue weight, used in the exponential-weighted moving average for calcul<strong>at</strong>ing the average queue size.wait_ Set to true to maintain an interval between dropped packets.linterm_ As the average queue size varies between "thresh_" <strong>and</strong> "maxthresh_", the packet dropping probability variesbetween 0 <strong>and</strong> "1/linterm".setbit_ Set to "true" to mark packets by setting the congestion indic<strong>at</strong>ion bit in packet headers r<strong>at</strong>her than drop packets.drop-tail_ Set to true to use drop-tail r<strong>at</strong>her than r<strong>and</strong>omdrop when the queue overflows or the average queue sizeexceeds "maxthresh_". For a further explan<strong>at</strong>ion of these variables, see [2].None of the st<strong>at</strong>e variables of the RED implement<strong>at</strong>ion are accessible.• CBQ objects: CBQ objects are a subclass of Queue objects th<strong>at</strong> implement class-based queueing.$cbq i<strong>ns</strong>ert I<strong>ns</strong>ert traffic class class into the link-sharing structure associ<strong>at</strong>ed with link object cbq.$cbq bind [$id2]Cause packets containing flow id id1 (or those in the range id1 to id2 inclusive) to be associ<strong>at</strong>ed with the traffic classcbqclass.$cbq algorithm Select the CBQ internal algorithm. may be set to one of: "ancestor-only", "top-level", or "formal".• CBQ/WRR objects: CBQ/WRR objects are a subclass of CBQ objects th<strong>at</strong> implement weighted round-robin schedulingamong classes of the same priority level. In contrast, CBQ objects implement packet-by-packet round-robin schedulingamong classes of the same priority level. Configur<strong>at</strong>ion Parameters are:maxpkt_ <strong>The</strong> maximum size of a packet in bytes. This is used only by CBQ/WRR objects in computing maximumb<strong>and</strong>width alloc<strong>at</strong>io<strong>ns</strong> for the weighted round-robin scheduler.CBQCLASS OBJECTSCBQClass objects implement the traffic classes associ<strong>at</strong>ed with CBQ objects.$cbqclass setparams Sets several of the configur<strong>at</strong>ion parameters for the CBQ traffic class (see below).$cbqclass parent specify the parent of this class in the link-sharing tree. <strong>The</strong> parent may be specified as “none” to indic<strong>at</strong>e this class is a root.$cbqclass newallot Change the link alloc<strong>at</strong>ion of this class to the specified amount (in range 0.0 to 1.0). Note th<strong>at</strong> only the specified class isaffected.$cbqclass i<strong>ns</strong>tall-queue I<strong>ns</strong>tall a Queue object into the compound CBQ or CBQ/WRR link structure. When a CBQ object is initially cre<strong>at</strong>ed, itincludes no internal queue (only a packet classifier <strong>and</strong> scheduler).Configur<strong>at</strong>ion Parameters are:okborrow_ is a boolean indic<strong>at</strong>ing the class is permitted to borrow b<strong>and</strong>width from its parent.allot_ is the maximum fraction of link b<strong>and</strong>width alloc<strong>at</strong>ed to the class expressed as a real number between 0.0 <strong>and</strong> 1.0.75


maxidle_ is the maximum amount of time a class may be required to have its packets queued before they are permitted to beforwardedpriority_ is the class’ priority level with respect to other classes. This value may range from 0 to 10, <strong>and</strong> more than one classmay exist <strong>at</strong> the same priority. Priority 0 is the highest priority.level_ is the level of this class in the link-sharing tree. Leaf nodes in the tree are co<strong>ns</strong>idered to be <strong>at</strong> level 1; their parents are<strong>at</strong> level 2, etc.extradelay_ increase the delay experienced by a delayed class by the specified timeQUEUE-MONITOR OBJECTSQueueMonitor Objects are used to monitor a set of packet <strong>and</strong> byte arrival, departure <strong>and</strong> drop counters. It also includessupport for aggreg<strong>at</strong>e st<strong>at</strong>istics such as average queue size, etc.$queuemonitorreset all the cumul<strong>at</strong>ive counters described below (arrivals, departures, <strong>and</strong> drops) to zero. Also, reset the integr<strong>at</strong>ors <strong>and</strong>delay sampler, if defined.$queuemonitor set-delay-samples Set up the Samples object delaySamp_ to record st<strong>at</strong>istics about queue delays. delaySamp_ is a h<strong>and</strong>le to a Samples objecti.e the Samples object should have already been cre<strong>at</strong>ed.$queuemonitor get-bytes-integr<strong>at</strong>orRetur<strong>ns</strong> an Integr<strong>at</strong>or object th<strong>at</strong> can be used to find the integral of the queue size in bytes.$queuemonitor get-pkts-integr<strong>at</strong>orRetur<strong>ns</strong> an Integr<strong>at</strong>or object th<strong>at</strong> can be used to find the integral of the queue size in packets.$queuemonitor get-delay-samplesRetur<strong>ns</strong> a Samples object delaySamp_ to record st<strong>at</strong>istics about queue delays.<strong>The</strong>re are no configur<strong>at</strong>ion parameters specific to this object.St<strong>at</strong>e Variables are:size_ I<strong>ns</strong>tantaneous queue size in bytes.pkts_ I<strong>ns</strong>tantaneous queue size in packets.parrivals_ Running total of packets th<strong>at</strong> have arrived.barrivals_ Running total of bytes contained in packets th<strong>at</strong> have arrived.pdepartures_ Running total of packets th<strong>at</strong> have departed (not dropped).bdepartures_ Running total of bytes contained in packets th<strong>at</strong> have departed (not dropped).pdrops_ Total number of packets dropped.bdrops_ Total number of bytes dropped.bytesInt_ Integr<strong>at</strong>or object th<strong>at</strong> computes the integral of the queue size in bytes. <strong>The</strong> sum_ variable of this object has therunning sum (integral) of the queue size in bytes.pktsInt_ Integr<strong>at</strong>or object th<strong>at</strong> computes the integral of the queue size in packets. <strong>The</strong> sum_ variable of this object has therunning sum (integral) of the queue size in packets.76


QUEUEMONITOR/ED OBJECTSThis derived object is capable of differenti<strong>at</strong>ing regular packet drops from early drops. Some queues distinguish regular drops(e.g. drops due to buffer exhaustion) from other drops (e.g. r<strong>and</strong>om drops in RED queues). Under some circumstances, it isuseful to distinguish these two types of drops.St<strong>at</strong>e Variables are:epdrops_ <strong>The</strong> number of packets th<strong>at</strong> have been dropped “early”.ebdrops_ <strong>The</strong> number of bytes comprising packets th<strong>at</strong> have been dropped “early”.Note: because this class is a subclass of QueueMonitor, objects of this type also have fields such as pdrops_ <strong>and</strong> bdrops_.<strong>The</strong>se fields describe the total number of dropped packets <strong>and</strong> bytes, including both early <strong>and</strong> non-early drops.QUEUEMONITOR/ED/FLOWMON OBJECTS<strong>The</strong>se objects may be used in the place of a conventional QueueMonitor object when wishing to collect per-flow counts <strong>and</strong>st<strong>at</strong>istics in addition to the aggreg<strong>at</strong>e counts <strong>and</strong> st<strong>at</strong>istics provided by the basic QueueMonitor.$fmon classifier This i<strong>ns</strong>erts (read) the specified classifier into (from) the flow monitor object. This is used to map incoming packets to whichflows they are associ<strong>at</strong>ed with.$fmon dumpDump the current per-flow counters <strong>and</strong> st<strong>at</strong>istics to the I/O channel specified in a previous <strong>at</strong>tach oper<strong>at</strong>ion.$fmon flowsReturn a character string containing the names of all flow objects known by this flow monitor. Each of these objects are oftype QueueMonitor/ED/Flow.$fmon <strong>at</strong>tach Attach a tcl I/O channel to the flow monitor. Flow st<strong>at</strong>istics are written to the channel when the dump oper<strong>at</strong>ion is executed.Configur<strong>at</strong>ion Parameters are:enable_in_ Set to true by default, indic<strong>at</strong>es th<strong>at</strong> per-flow arrival st<strong>at</strong>e should be kept by the flow monitor. If set to false, onlythe aggreg<strong>at</strong>e arrival inform<strong>at</strong>ion is kept.enable_out_ Set to true by default, indic<strong>at</strong>es th<strong>at</strong> per-flow departure st<strong>at</strong>e should be kept by the flow monitor. If set to false,only the aggreg<strong>at</strong>e departure inform<strong>at</strong>ion is kept.enable_drop_ Set to true by default, indic<strong>at</strong>es th<strong>at</strong> per-flow drop st<strong>at</strong>e should be kept by the flow monitor. If set to false,only the aggreg<strong>at</strong>e drop inform<strong>at</strong>ion is kept.enable_edrop_ Set to true by default, indic<strong>at</strong>es th<strong>at</strong> per-flow early drop st<strong>at</strong>e should be kept by the flow monitor. If set tofalse, only the aggreg<strong>at</strong>e early drop inform<strong>at</strong>ion is kept.QUEUEMONITOR/ED/FLOW OBJECTS<strong>The</strong>se objects contain per-flow counts <strong>and</strong> st<strong>at</strong>istics managed by a QueueMonitor/ED/Flowmon object. <strong>The</strong>y are generallycre<strong>at</strong>ed in an OTcl callback procedure when a flow monitor is given a packet it cannot map on to a known flow. Note th<strong>at</strong> theflow monitor’s classifier is respo<strong>ns</strong>ible for mapping packets to flows in some arbitrary way. Thus, depending on the type ofclassifier used, not all of the st<strong>at</strong>e variables may be relevant (e.g. one may classify packets based only on flow id, in whichcase the source <strong>and</strong> destin<strong>at</strong>ion addresses may not be significant). St<strong>at</strong>e Variables are:src_ <strong>The</strong> source address of packets belonging to this flow.77


dst_ <strong>The</strong> destin<strong>at</strong>ion address of packets belonging to this flow.flowid_ <strong>The</strong> flow id of packets belonging to this flow.7.4 Comm<strong>and</strong>s <strong>at</strong> a glanceFollowing is a list of queue comm<strong>and</strong>s used in simul<strong>at</strong>ion scripts:$<strong>ns</strong>_ queue-limit This sets a limit on the maximum buffer size of the queue in the link between nodes <strong>and</strong> .$<strong>ns</strong>_ trace-queue This sets up trace objects to log events in the queue. If tracefile is not passed, it uses traceAllFile_ to write the events.$<strong>ns</strong>_ namtrace-queue Similar to trace-queue above, this sets up nam-tracing in the queue.$<strong>ns</strong>_ monitor-queue This comm<strong>and</strong> i<strong>ns</strong>erts objects th<strong>at</strong> allows us to monitor the queue size. This retur<strong>ns</strong> a h<strong>and</strong>le to the object th<strong>at</strong> may bequeried to determine the average queue size. <strong>The</strong> default value for sampleinterval is 0.1.7.5 Queue/JoBSJoBS is developed <strong>and</strong> contributed by Nicolas Christin This chapter describes the implement<strong>at</strong>ion of the Joint Buffer Management <strong>and</strong> Scheduling (JoBS) algorithm in <strong>ns</strong>. Thischapter is in three parts. <strong>The</strong> first part summarizes the objectives of the JoBS algorithm. <strong>The</strong> second part explai<strong>ns</strong> how toconfigure a JoBS queue in <strong>ns</strong>. <strong>The</strong> third part focuses on the tracing mechanisms implemented for JoBS.<strong>The</strong> procedures <strong>and</strong> functio<strong>ns</strong> described in this chapter can be found in <strong>ns</strong>/jobs.{cc, h}, <strong>ns</strong>/marker.{cc, h}, <strong>ns</strong>/demarker.{cc,h}. Example scripts can be found in <strong>ns</strong>/tcl/ex/jobs-{lossdel, cn2002}.tcl.Additional inform<strong>at</strong>ion can be found <strong>at</strong> http://qosbox.cs.virginia.edu.7.5.1 <strong>The</strong> JoBS algorithmThis section gives an overview of the objectives the JoBS algorithm aims <strong>at</strong> achieving, <strong>and</strong> of the mechanisms employed toreach these objectives. <strong>The</strong> original JoBS algorithm, as described in [20], was using the solution to a non-linear optimiz<strong>at</strong>ionproblem. This <strong>ns</strong>-2 implement<strong>at</strong>ion uses the feedback-control based heuristic described in [8].Important Note: This <strong>ns</strong>-2 implement<strong>at</strong>ion results from the merge between old code for <strong>ns</strong>-2.1b5, <strong>and</strong> code derived from theBSD kernel-level implement<strong>at</strong>ion of the JoBS algorithm. It is still co<strong>ns</strong>idered experimental. Due to the absence of bindingfacilities for arrays between Tcl <strong>and</strong> C++ in tclcl <strong>at</strong> the moment, the number of traffic classes is st<strong>at</strong>ically set to 4 <strong>and</strong> cannotbe changed without modifying the C++ code.78


Objective<strong>The</strong> objective of the JoBS algorithm is to provide absolute <strong>and</strong> rel<strong>at</strong>ive (proportional) loss <strong>and</strong> delay differenti<strong>at</strong>ion independently<strong>at</strong> each node for classes of traffic. JoBS therefore provides service guarantees on a per-hop basis. <strong>The</strong> set ofperformance requirements are specified to the algorithm as a set of per-class Qualtiy of Service (QoS) co<strong>ns</strong>traints. As anexample, for three classes, the QoS co<strong>ns</strong>traints could be of the form:• Class-1 Delay ≈ 2 · Class-2 Delay,• Class-2 Loss R<strong>at</strong>e ≈ 10 −1 · Class-3 Loss R<strong>at</strong>e, or• Class-3 Delay ≤ 5 ms.Here, the first two co<strong>ns</strong>traints are rel<strong>at</strong>ive co<strong>ns</strong>traints <strong>and</strong> the last one is an absolute co<strong>ns</strong>traint. <strong>The</strong> set of co<strong>ns</strong>traints can beany mix of rel<strong>at</strong>ive <strong>and</strong> absolute co<strong>ns</strong>traints. More specifically, JoBS supports the five following types of co<strong>ns</strong>traints:• Rel<strong>at</strong>ive delay co<strong>ns</strong>traints (RDC) specify a proportional delay differenti<strong>at</strong>ion between classes. As an example, fortwo classes 1 <strong>and</strong> 2, the RDC enforces a rel<strong>at</strong>io<strong>ns</strong>hipDelay of Class 2Delay of Class 1 ≈ co<strong>ns</strong>tant .• Absolute delay co<strong>ns</strong>traints (ADC): An ADC on class i requires th<strong>at</strong> the delays of class i s<strong>at</strong>isfy a worst-case boundd i .• Rel<strong>at</strong>ive loss co<strong>ns</strong>traints (RLC) specify a proportional loss differenti<strong>at</strong>ion between classes.• Absolute loss co<strong>ns</strong>traints (ALC): An ALC on class i requires th<strong>at</strong> the loss r<strong>at</strong>e of class i be bounded by an upperbound L i .• Absolute r<strong>at</strong>e co<strong>ns</strong>traints (ARC): An ARC on class i mea<strong>ns</strong> th<strong>at</strong> the throughput of class i is bounded by a lowerbound µ i .JoBS does not rely on admission control or traffic policing, nor does it make any assumption on traffic arrivals. <strong>The</strong>refore, asystem of co<strong>ns</strong>traints may become infeasible, <strong>and</strong> some co<strong>ns</strong>traints may need to be relaxed. QoS co<strong>ns</strong>traints are prioritized inthe following order.ALC > ADC, ARC > Rel<strong>at</strong>ive Co<strong>ns</strong>traints .Th<strong>at</strong> is, if JoBS is unable to s<strong>at</strong>isfy both absolute <strong>and</strong> rel<strong>at</strong>ive co<strong>ns</strong>traints, it will give preference to the absolute co<strong>ns</strong>traints.MechanismsJoBS performs scheduling <strong>and</strong> buffer management in a single pass. JoBS dynamically alloc<strong>at</strong>es service r<strong>at</strong>es to classes inorder to s<strong>at</strong>isfy the delay co<strong>ns</strong>traints. <strong>The</strong> service r<strong>at</strong>es needed for enforcing absolute delay co<strong>ns</strong>traints are alloc<strong>at</strong>ed upon eachpacket arrival, while service r<strong>at</strong>es derived from rel<strong>at</strong>ive delay co<strong>ns</strong>traints are computed only every N packet arrivals. If nofeasible service r<strong>at</strong>e alloc<strong>at</strong>ion exists 1 , or if the packet buffer overflows, packets are dropped according to the loss co<strong>ns</strong>traints.<strong>The</strong> service r<strong>at</strong>es are tra<strong>ns</strong>l<strong>at</strong>ed into packet scheduling decisio<strong>ns</strong> by an algorithm resembling Deficit Round Robin. Th<strong>at</strong> is,the scheduler tries to achieve the desired service r<strong>at</strong>es by keeping track of the difference between the actual tra<strong>ns</strong>mission r<strong>at</strong>efor each class <strong>and</strong> the desired service r<strong>at</strong>e for each class. Scheduling in JoBS is work-co<strong>ns</strong>erving.1 For i<strong>ns</strong>tance, if the sum of the service r<strong>at</strong>es needed is gre<strong>at</strong>er than the output link capacity.79


7.5.2 Configur<strong>at</strong>ionRunning a JoBS simul<strong>at</strong>ion requires to cre<strong>at</strong>e <strong>and</strong> configure the JoBS “link(s)”, to cre<strong>at</strong>e <strong>and</strong> configure the Markers <strong>and</strong>Demarkers in charge of marking/demarking the traffic, to <strong>at</strong>tach an applic<strong>at</strong>ion-level d<strong>at</strong>a source (traffic gener<strong>at</strong>or), <strong>and</strong> tostart the traffic gener<strong>at</strong>or.Initial Setupset <strong>ns</strong> [new Simul<strong>at</strong>or]Queue/JoBS set drop_front_ falseQueue/JoBS set trace_hop_ trueQueue/JoBS set adc_resolution_type_ 0Queue/JoBS set shared_buffer_ 1Queue/JoBS set mean_pkt_size_ 4000Queue/Demarker set demarker_arrvs1_ 0Queue/Demarker set demarker_arrvs2_ 0Queue/Demarker set demarker_arrvs3_ 0Queue/Demarker set demarker_arrvs4_ 0Queue/Marker set marker_arrvs1_ 0Queue/Marker set marker_arrvs2_ 0Queue/Marker set marker_arrvs3_ 0Queue/Marker set marker_arrvs4_ 0set router(1) [$<strong>ns</strong> node]set router(2) [$<strong>ns</strong> node]set source [$<strong>ns</strong> node]set sink [$<strong>ns</strong> node]set bw 10000000set delay 0.001set buff 500;# preamble initializ<strong>at</strong>ion;# use drop-tail;# enable st<strong>at</strong>istic traces;# see ‘‘comm<strong>and</strong>s <strong>at</strong> a glance’’;# all classes share a common buffer;# we expect to receive 500-Byte pkts;# reset arrivals everywhere;# set first router;# set second router;# set source;# set traffic sink;# 10 Mbps;# 1 ms;# 500 packetsCre<strong>at</strong>ing the JoBS links$<strong>ns</strong> duplex-link $router(1) $router(2) $bw $delay JoBS;# Cre<strong>at</strong>es the JoBS link$<strong>ns</strong>_ queue-limit $router(1) $router(2) $buffset l [$<strong>ns</strong>_ get-link $router(1) $router(2)]set q [$l queue]$q init-rdcs -1 2 2 2 ;# Classes 2, 3 <strong>and</strong> 4 are bound by proportional delay differenti<strong>at</strong>ion with a factor of 2$q init-rlcs -1 2 2 2 ;# Classes 2, 3 <strong>and</strong> 4 are bound by proportional loss differenti<strong>at</strong>ion with a factor of 2$q init-alcs 0.01 -1 -1 -1 ;# Class 1 is provided with a loss r<strong>at</strong>e bound of 1%$q init-adcs 0.005 -1 -1 -1 ;# Class 1 is provided with a delay bound of 5 ms$q init-arcs -1 -1 -1 500000 ;# Class 4 is provided with a minimumthroughput of 500 Kbps$q link [$l link] ;# <strong>The</strong> link is <strong>at</strong>tached to the queue (required)$q trace-file jobstrace ;# Trace per-hop, per-class metrics to the file jobstrace$q sampling-period 1 ;# Reevalu<strong>at</strong>e r<strong>at</strong>e alloc<strong>at</strong>ion upon each arrival$q id 1 ;# Assig<strong>ns</strong> an ID of 1 to the JoBS queue$q initialize ;# Proceed with the initializ<strong>at</strong>ion80


Marking the trafficMarking the traffic is h<strong>and</strong>led by Marker objects. Markers are FIFO queues th<strong>at</strong> set the class index of each packet. To e<strong>ns</strong>ureaccuracy of the simul<strong>at</strong>io<strong>ns</strong>, it is best to configure these queues to have a very large buffer, so th<strong>at</strong> no packets are dropped inthe Marker. Demarkers are used to g<strong>at</strong>her end-to-end delay st<strong>at</strong>istics.$<strong>ns</strong>_ simplex-link $source $router(1) $bw $delay Marker;# set-up marker$<strong>ns</strong>_ queue-limit $source $router(1) [expr $buff*10];# Select huge buffers for markers$<strong>ns</strong>_ queue-limit $router(1) $source [expr $buff*10];# to avoid traffic dropsset q [$<strong>ns</strong>_ get-queue $source $router(1)];#in the marker$q marker_type 2 ;# St<strong>at</strong>istical marker$q marker_frc 0.1 0.2 0.3 0.4 ;# 10% Class 1, 20% Class 2, 30% Class 3, 40% Class 4.$<strong>ns</strong>_ simplex-link $router(2) $sink $bw $delay Demarker;# set-up demarker$<strong>ns</strong>_ queue-limit $router(2) $sink [expr $buff*10]$q trace-file e2e ;# trace end-to-end delays to file e2e<strong>The</strong> remaining steps (<strong>at</strong>taching agents <strong>and</strong> traffic gener<strong>at</strong>ors or applic<strong>at</strong>io<strong>ns</strong> to the nodes) are explained in Chapters 10 <strong>and</strong>38, <strong>and</strong> are h<strong>and</strong>led as usual. We refer to these chapters <strong>and</strong> the example scripts provided with your <strong>ns</strong> distribution.7.5.3 TracingTracing in JoBS is h<strong>and</strong>led internally, by the scheduler. Each JoBS queue can gener<strong>at</strong>e a trace file containing the followinginform<strong>at</strong>ion. Each line of the tracefile co<strong>ns</strong>ists of 17 colum<strong>ns</strong>. <strong>The</strong> first column is the simul<strong>at</strong>ion time, colum<strong>ns</strong> 2 to 5 representthe loss r<strong>at</strong>es over the current busy period for classes 1 to 4, colum<strong>ns</strong> 6 to 9 represent the delays for each class (average overa 0.5 seconds sliding window), colum<strong>ns</strong> 10 to 13 represent the average service r<strong>at</strong>es alloc<strong>at</strong>ed to each class over the last 0.5seconds, <strong>and</strong> colum<strong>ns</strong> 14 to 17 represent the i<strong>ns</strong>tantaneous queue length in packets. Additionally, Demarkers can be used totrace end-to-end delays.7.5.4 VariablesThis section summarizes the variables th<strong>at</strong> are used by JoBS, Marker <strong>and</strong> Demarker objects.JoBS objectstrace_hop_ Can be true or false. If set to true, per-hop, per-class metrics will be traced. (Trace files have then to be specified,using trace-file .) Defaults to false.drop_front_ Can be true or false. If set to true, traffic will be dropped from the front of the queue. Defaults to false(drop-tail).adc_resolution_type_ Can be 0 or 1. If set to 0, traffic will be dropped from classes th<strong>at</strong> have an ADC if the ADC cannotbe met by adjusting the service r<strong>at</strong>es. If set to 1, traffic will be dropped from all classes. A resolution mode set to 1 istherefore fairer, in the se<strong>ns</strong>e th<strong>at</strong> the pain is shared by all classes, but can lead to more deadline viol<strong>at</strong>io<strong>ns</strong>. Defaults to0.shared_buffer_ Can be 0 or 1. If set to 0, all classes use a separ<strong>at</strong>e per-class buffer (which is required if only r<strong>at</strong>e guaranteesare to provided). All per-class buffers have the same size. If set to 1, all classes share the same buffer (which is requiredif loss differenti<strong>at</strong>ion is to be provided). Defaults to 1.81


mean_pkt_size_ Used to set the expected mean packet size of packets arriving <strong>at</strong> a JoBS link. Setting this variable is requiredto e<strong>ns</strong>ure proper delay differenti<strong>at</strong>ion.Marker objectsmarker_arrvs1_ Number of Class-1 packets to have entered a Marker link.marker_arrvs2_ Number of Class-2 packets to have entered a Marker link.marker_arrvs3_ Number of Class-3 packets to have entered a Marker link.marker_arrvs4_ Number of Class-4 packets to have entered a Marker link.Demarker objectsdemarker_arrvs1_ Number of Class-1 packets to have entered a Demarker link.demarker_arrvs2_ Number of Class-2 packets to have entered a Demarker link.demarker_arrvs3_ Number of Class-3 packets to have entered a Demarker link.demarker_arrvs4_ Number of Class-4 packets to have entered a Demarker link.7.5.5 Comm<strong>and</strong>s <strong>at</strong> a glance<strong>The</strong> following is a list of comm<strong>and</strong>s used to configure the JoBS, Marker <strong>and</strong> Demarker objects.JoBS objectsset q [new Queue/JoBS]This cre<strong>at</strong>es an i<strong>ns</strong>tance of the JoBS queue.$q init-rdcs This assig<strong>ns</strong> the RDCs for the four JoBS classes. For i<strong>ns</strong>tance, using a value of 4 for k2 mea<strong>ns</strong> th<strong>at</strong> Class-3 delays will beroughly equal to four times Class-2 delays. A value of -1 indic<strong>at</strong>es th<strong>at</strong> the class is not concerned by RDCs.Important Note: Since RDCs bound two classes, one would expect only three parameters to be passed (k1, k2, <strong>and</strong> k3, sincek4 theoretically binds Classes 4 <strong>and</strong> 5, <strong>and</strong> Class 5 does not exist). However, in this prototype implement<strong>at</strong>ion, it isimper<strong>at</strong>ive to specify a value different from 0 <strong>and</strong> -1 to k4 if Class 4 is to be concerned by RDCs.Examples: $q init-rdcs -1 2 1 -1 specifies th<strong>at</strong> classes 2 <strong>and</strong> 3 are bound by a delay differenti<strong>at</strong>ion factor of 2, $qinit-rdcs 4 4 4 4 specifies th<strong>at</strong> all classes are bound by a delay differenti<strong>at</strong>ion factor of 4 <strong>and</strong> is equivalent to $qinit-rdcs 4 4 4 1, since the last coefficient is only used to specify th<strong>at</strong> Class 4 is to be bound by proportionaldifferenti<strong>at</strong>ion.$q init-rlcs This assig<strong>ns</strong> the RLCs for the four JoBS classes. For i<strong>ns</strong>tance, using a value of 3 for k1 mea<strong>ns</strong> th<strong>at</strong> Class-2 loss r<strong>at</strong>es will beroughly equal to four times Class-2 loss r<strong>at</strong>es. A value of -1 indic<strong>at</strong>es th<strong>at</strong> the class is not concerned by RLCs. As withRDCs, each RLC binds two classes, thus, one would expect only three parameters to be passed (k’1, k’2, <strong>and</strong> k’3, since k’482


theoretically bounds Classes 4 <strong>and</strong> 5, <strong>and</strong> Class 5 does not exist). As explained above, it is imper<strong>at</strong>ive to specify a valuedifferent from 0 <strong>and</strong> -1 to k’4 if Class 4 is to be concerned by RLCs.$q init-alcs This assig<strong>ns</strong> the absolute loss guarantees (ALCs) to all four classes. L1 to L4 are given in fraction of 1. For i<strong>ns</strong>tance, settingL1 to 0.05 mea<strong>ns</strong> th<strong>at</strong> Class-1 loss r<strong>at</strong>e will be guarantees to be less than 5%. A value of -1 indic<strong>at</strong>es th<strong>at</strong> the correspondingclass is not subject to an ALC.$q init-adcs This assig<strong>ns</strong> the absolute loss guarantees (ADCs) to all four classes. D1 to D4 are given in milliseconds. A value of -1indic<strong>at</strong>es th<strong>at</strong> the corresponding class is not subject to an ADC.$q trace-file This specifies the trace file for all per-hop metrics. JoBS uses an internal module to trace loss <strong>and</strong> delays, service r<strong>at</strong>es, <strong>and</strong>per-class queue lengths in packets. If filename is set to null, no trace will be provided.$q link [ link]This comm<strong>and</strong> is required to bind a link to a JoBS queue. Note th<strong>at</strong> JoBS needs to know the capacity of the link. Thus, thiscomm<strong>and</strong> has to be issued before the simul<strong>at</strong>ion is started.$q sampling-period This comm<strong>and</strong> specifies the sampling interval (in packets) <strong>at</strong> which the service r<strong>at</strong>e adjustments for proportionaldifferenti<strong>at</strong>ion will be performed. <strong>The</strong> default is a sampling interval of 1 packet, meaning th<strong>at</strong> the r<strong>at</strong>e alloc<strong>at</strong>ion isreevalu<strong>at</strong>ed upon each packet arrival. Larger sampling intervals speed up the simul<strong>at</strong>io<strong>ns</strong>, but typically result in poorerproportional differenti<strong>at</strong>ion.$q id This comm<strong>and</strong> affects a numerical ID to the JoBS queue.$q initializeThis comm<strong>and</strong> is required, <strong>and</strong> should be run after all configur<strong>at</strong>ion oper<strong>at</strong>io<strong>ns</strong> have been performed. This comm<strong>and</strong> willperform the final checks <strong>and</strong> configur<strong>at</strong>ion of the JoBS queue.$q copyright-infoDisplays authors <strong>and</strong> copyright inform<strong>at</strong>ion.A simple example script (with nam output), fully annot<strong>at</strong>ed <strong>and</strong> commented can be found in <strong>ns</strong>/tcl/ex/jobs-lossdel.tcl. Amore realistic example of a simul<strong>at</strong>ion with JoBS queues can be found in <strong>ns</strong>/tcl/ex/jobs-cn2002.tcl. This script is verysimilar to wh<strong>at</strong> was used in a simul<strong>at</strong>ion presented in [21]. Associ<strong>at</strong>ed tracefiles <strong>and</strong> gnuplot scripts for visualiz<strong>at</strong>ion (in caseyou favor gnuplot over xgraph can be found in <strong>ns</strong>/tcl/ex/jobs-lossdel, <strong>and</strong> <strong>ns</strong>/tcl/ex/jobs-cn2002.Marker objects$q marker_type Selects the type of marker. 1 is DETERMINISTIC, 2 is STATISTICAL.$q marker_class For a deterministic marker, selects which class packets should be marked with.$q marker_frc For a st<strong>at</strong>istical marker, gives the fraction of packets th<strong>at</strong> should be marked from each class. For i<strong>ns</strong>tance, using 0.1 for f1mea<strong>ns</strong> th<strong>at</strong> 10 percent of the traffic coming to the Marker link will be marked as Class 1.83


Demarker objects$q trace-file This comm<strong>and</strong> specifies the trace file used for the demarker object. filename.1 will contain the end-to-end delays of eachClass-1 packet to have reached the Demarker link, filename.2 will contain the end-to-end delays of each Class-2 packet tohave reached the Demarker link, <strong>and</strong> so forth. (<strong>The</strong>re will of course be 4 trace files, one for each class.)84


Chapter 8Delays <strong>and</strong> LinksDelays represent the time required for a packet to traverse a link. A special form of this object (“dynamic link”) also capturesthe possibility of a link failure. <strong>The</strong> amount of time required for a packet to traverse a link is defined to be s/b + d where sis the packet size (as recorded in its IP header), b is the speed of the link in bits/sec, <strong>and</strong> d is the link delay in seconds. <strong>The</strong>implement<strong>at</strong>ion of link delays is closely associ<strong>at</strong>ed with the blocking procedures described for Queues in Section7.1.1.8.1 <strong>The</strong> LinkDelay Class<strong>The</strong> class LinkDelay is derived from the base class Connector. Its definition is in ~<strong>ns</strong>/delay.cc, <strong>and</strong> is brieflyexcerpted below:class LinkDelay : public Connector {public:LinkDelay();void recv(Packet* p, H<strong>and</strong>ler*);void send(Packet* p, H<strong>and</strong>ler*);void h<strong>and</strong>le(Event* e);double delay(); /* line l<strong>at</strong>ency on this link */double b<strong>and</strong>width(); /* b<strong>and</strong>width on this link */inline double txtime(Packet* p) { /* time to send pkt p on this link */hdr_cmn* hdr = (hdr_cmn*) p->access(off_cmn_);return (hdr->size() * 8. / b<strong>and</strong>width_);}protected:double b<strong>and</strong>width_; /* b<strong>and</strong>width of underlying link (bits/sec) */double delay_; /* line l<strong>at</strong>ency */int dynamic_; /* indic<strong>at</strong>es whether or not link is ~ */Event inTra<strong>ns</strong>it_;PacketQueue* itq_; /* internal packet queue for dynamic links */Packet* nextPacket_; /* to be delivered for a dynamic link. */Event intr_;};85


<strong>The</strong> recv() method overrides the base class Connector version. It is defined as follows:void LinkDelay::recv(Packet* p, H<strong>and</strong>ler* h){double txt = txtime(p);Scheduler& s = Scheduler::i<strong>ns</strong>tance();if (dynamic_) {Event* e = (Event*)p;e->time_ = s.clock() + txt + delay_;itq_->enque(p);schedule_next();} else {s.schedule(target_, p, txt + delay_);}/* XXX only need one intr_ since upstream object should* block until it’s h<strong>and</strong>ler is called** This only holds if the link is not dynamic. If it is, then* the link itself will hold the packet, <strong>and</strong> call the upstream* object <strong>at</strong> the appropri<strong>at</strong>e time. This second interrupt is* called inTra<strong>ns</strong>it_, <strong>and</strong> is invoked through schedule_next()*/s.schedule(h, &intr_, txt);}This object supports one i<strong>ns</strong>tproc-like, $object dynamic, to set its variable, dynamic_. This variable determineswhether the link is dynamic or not (i.e., prone to fail/recover <strong>at</strong> appropri<strong>at</strong>e times). <strong>The</strong> internal behavior of the link in eachcase is different.For “non-dynamic” links, this method oper<strong>at</strong>es by receiving a packet, p, <strong>and</strong> scheduling two events. Assume these two eventsare called E 1 <strong>and</strong> E 2 , <strong>and</strong> th<strong>at</strong> event E 1 is scheduled to occur before E 2 . E 1 is scheduled to occur when the upstream node<strong>at</strong>tached to this delay element has completed sending the current packet (which takes time equal to the packet size dividedby the link b<strong>and</strong>width). E 1 is usually associ<strong>at</strong>ed with a Queue object, <strong>and</strong> will cause it to (possibly) become unblocked (seesection 7.1.1). E 2 represents the packet arrival event <strong>at</strong> the dow<strong>ns</strong>tream neighbor of the delay element. Event E 2 occurs anumber of seconds l<strong>at</strong>er than E 1 equal to the link delay.Altern<strong>at</strong>ely, when the link is dynamic, <strong>and</strong> receives p, then it will schedule E 1 to possibly unblock the queue <strong>at</strong> the appropri<strong>at</strong>etime. However, E 2 is scheduled only if p is the only packet currently in tra<strong>ns</strong>it. Otherwise, there is <strong>at</strong> least one packet intra<strong>ns</strong>it on the link th<strong>at</strong> must be delivered before p <strong>at</strong> E 2 . <strong>The</strong>refore, packet p is held in the object’s inTra<strong>ns</strong>it queue, itq_.When the packet just before p in tra<strong>ns</strong>it on the link is delivered <strong>at</strong> the neighbor node, the DelayLink object will schedule anevent for itself to fire <strong>at</strong> E 2 . At th<strong>at</strong> appropri<strong>at</strong>e time then, it’s h<strong>and</strong>le() method will directly send p to its target. <strong>The</strong> object’sinternal schedule_next() method will schedule these events for packet sin tra<strong>ns</strong>it <strong>at</strong> the appropri<strong>at</strong>e time.8.2 Comm<strong>and</strong>s <strong>at</strong> a glance<strong>The</strong> LinkDelay object represents the time required by a packet to tra<strong>ns</strong>verse the link <strong>and</strong> is used internally within a Link.Hence we donot list any linkdelay rel<strong>at</strong>ed comm<strong>and</strong>s suitable for simul<strong>at</strong>ion scripts here.86


Chapter 9Differenti<strong>at</strong>ed Services Module in <strong>ns</strong>Note: <strong>The</strong> Differenti<strong>at</strong>ed Services module described in this chapter has been integr<strong>at</strong>ed into <strong>ns</strong>-2.1b8.Differenti<strong>at</strong>ed Services, or DiffServ, is an IP QoS architecture based on packet marking th<strong>at</strong> allows packets to be prioritizedaccording to user requirements. During the time of congestion, more low priority packets are discarded than high prioritypackets. This chapter describes the DiffServ module th<strong>at</strong> was originally implemented by the Advanced IP Networks group inNortel Networks [28].9.1 Overview<strong>The</strong> DiffServ architecture provides QoS by dividing traffic into different c<strong>at</strong>egories, marking each packet with a code pointth<strong>at</strong> indic<strong>at</strong>es its c<strong>at</strong>egory, <strong>and</strong> scheduling packets according accordingly. <strong>The</strong> DiffServ module in <strong>ns</strong>can support four classesof traffic, each of which has three dropping precedences allowing differential tre<strong>at</strong>ment of traffic within a single class. Packetsin a single class of traffic are enqueued into one corresponding physical RED queue, which contai<strong>ns</strong> three virtual queues (onefor each drop precedence).Different RED parameters can be configured for virtual queues, causing packets from one virtual queue to be dropped morefrequently than packets from another. A packet with a lower dropping precedence is given better tre<strong>at</strong>ment in times ofcongestion because it is assigned a code point th<strong>at</strong> corresponds to a virtual queue with rel<strong>at</strong>ively lenient RED parameters.<strong>The</strong> DiffServ module in <strong>ns</strong>has three major components:Policy: Policy is specified by network administr<strong>at</strong>or about the level of service a class of traffic should receive in the network.Edge router: Edge router marks packets with a code point according to the policy specified.Core router: Core router examines packets’ code point marking <strong>and</strong> forwarding them accordingly.DiffServ <strong>at</strong>tempts to restrict complexity to only the edge routers.87


9.2 Implement<strong>at</strong>ion<strong>The</strong> procedures <strong>and</strong> functio<strong>ns</strong> described in this section can be found in ~<strong>ns</strong>/diffserv/dsred, dsredq, dsEdge, dsCore, dsPolicy.{cc,h}.9.2.1 RED queue in DiffServ moduleA DiffServ queue (in class dsREDQueue) derived from the base class Queue is implemented in DiffServ module to providethe basic DiffServ router functionality, see dsred.{h,cc}). dsREDQueue has the following abilities:• to implement multiple physical RED queues along a single link;• to implement multiple virtual queues within a physical queue, with individual set of parameters for each virtual queue;• to determine in which physical <strong>and</strong> virtual queue a packet is enqueued according to its code point;• to determine in from which physical <strong>and</strong> virtual queue a packet is dequeued according to the scheduling scheme chosen.<strong>The</strong> class dsREDQueue co<strong>ns</strong>ists of four physical RED queues, each containing three virtual queues. <strong>The</strong> number of physical<strong>and</strong> virtual queues are defined in numPrec <strong>and</strong> numQueues_. Each combin<strong>at</strong>ion of physical <strong>and</strong> virtual queue number isassoci<strong>at</strong>ed with a code point (or a drop preference), which specifies a certain level of service.<strong>The</strong> physical queue is defined in class redQueue, which enables traffic differenti<strong>at</strong>ion by defining virtual queues withindependent configur<strong>at</strong>ion <strong>and</strong> st<strong>at</strong>e parameters, see dsredq.{h,cc}. For example, the length of each virtual queue iscalcul<strong>at</strong>ed only on packets mapped to th<strong>at</strong> queue. Thus, packet dropping decisio<strong>ns</strong> can be applied based on the st<strong>at</strong>e <strong>and</strong>configur<strong>at</strong>ion parameters of th<strong>at</strong> virtual queues. Class redQueue is not equivalent to class REDQueue, which was alreadypresent in <strong>ns</strong>. I<strong>ns</strong>tead, it is a modified version of RED implement<strong>at</strong>ion with the notion of virtual queues <strong>and</strong> is only used byclass redQueue to realize physical queues. All user interaction with class redQueue is h<strong>and</strong>led through the comm<strong>and</strong>interface of class dsREDQueue.Class dsREDQueue contai<strong>ns</strong> a d<strong>at</strong>a structure known as the Per Hop Behavior (PHB) Table In DiffServ, edge routers markpackets with code points <strong>and</strong> core routers simply respond to existing code points; both of them use PHB table to map a codepoint to a particular physical <strong>and</strong> virtual queue. <strong>The</strong> PHB Table is defined as an array with three fields:struct phbParam {int codePt_; // corresponding code pointint queue_; // physical queueint prec_; // virtual queue (drop precedence)};9.2.2 Edge <strong>and</strong> core routers<strong>The</strong> DiffServ edge <strong>and</strong> core routers are defined in class edgeQueue <strong>and</strong> class coreQueue, which are derived fromclass dsREDQueue, see dsEdge, dsCore.{h,cc}.Packet marking is implemented in class edgeQueue. A packet is marked with a code point according to the policy specifiedbefore it is put into the corresponding physical <strong>and</strong> virtual queue. Class edgeQueue has a reference to an i<strong>ns</strong>tance ofclass PolicyClassifier, which contai<strong>ns</strong> policies for packet marking.88


9.2.3 PolicyClass Policy <strong>and</strong> its sub-classes (see dsPolicy.{cc, h}) define the policies used by edge routers to mark incomingpackets. A policy is established between a source <strong>and</strong> destin<strong>at</strong>ion node. All flows m<strong>at</strong>ching th<strong>at</strong> source-destin<strong>at</strong>ion pair aretre<strong>at</strong>ed as a single traffic aggreg<strong>at</strong>e. Policy for each different traffic aggreg<strong>at</strong>e has an associ<strong>at</strong>ed policer type, meter type, <strong>and</strong>initial code point. <strong>The</strong> meter type specifies the method for measuring the st<strong>at</strong>e variables needed by the policer. For example,the TSW Tagger is a meter th<strong>at</strong> measures the average traffic r<strong>at</strong>e, using a specified time window.When a packet arrives <strong>at</strong> an edge router, it is examined to determine to which aggreg<strong>at</strong>e it belongs. <strong>The</strong> meter specified bythe corresponding policy is invoked to upd<strong>at</strong>e all st<strong>at</strong>e variables. <strong>The</strong> policer is invoked to determine how to mark the packetdepending on the aggreg<strong>at</strong>e’s st<strong>at</strong>e variables: the specified initial code point or a downgraded code point. <strong>The</strong>n the packet isenqueued accordingly.Currently, six different policy models are defined:1. Time Sliding Window with 2 Color Marking (TSW2CMPolicer): uses a CIR <strong>and</strong> two drop precedences. <strong>The</strong> lowerprecedence is used probabilistically when the CIR is exceeded.2. Time Sliding Window with 3 Color Marking (TSW3CMPolicer): uses a CIR, a PIR, <strong>and</strong> three drop precedences. <strong>The</strong>medium drop precedence is used probabilistically when the CIR is exceeded <strong>and</strong> the lowest drop precedence is usedprobabilistic ally when the PIR is exceeded.3. Token Bucket (tokenBucketPolicer): uses a CIR <strong>and</strong> a CBS <strong>and</strong> two drop precedences. An arriving packet is markedwith the lower precedence if <strong>and</strong> only if it is larger than the token bucket.4. Single R<strong>at</strong>e Three Color Marker (srTCMPolicer): uses a CIR, CBS, <strong>and</strong> an EBS to choose from three drop precedences.5. Two R<strong>at</strong>e Three Color Marker (trTCMPolicer): uses a CIR, CBS, PIR, <strong>and</strong> a PBS to choose from three drop precedences.6. NullPolicer: does not downgrade any packets<strong>The</strong> policies above are defined as a sub-classes of dsPolicy. <strong>The</strong> specific meter <strong>and</strong> policer are implemented in functio<strong>ns</strong>applyMeter <strong>and</strong> applyPolicer, which are defined as virtual functio<strong>ns</strong> in class dsPolicy. User specified policy canbe added in the similar way. Please refer to NullPolicy as the simplest example.All policies are stored in the policy table in class PolicyClassifier. This table is an array th<strong>at</strong> includes fields for thesource <strong>and</strong> destin<strong>at</strong>ion nodes, a policer type, a meter type, an initial code point, <strong>and</strong> various st<strong>at</strong>e inform<strong>at</strong>ion as shown below:<strong>The</strong> r<strong>at</strong>es CIR <strong>and</strong> PIR are specified in bits per second:CIR: committed inform<strong>at</strong>ion r<strong>at</strong>ePIR: peak inform<strong>at</strong>ion r<strong>at</strong>e<strong>The</strong> buckets CBS, EBS, <strong>and</strong> PBS are specified in bytes:CBS: committed burst sizeEBS: excess burst sizePBS: peak burst sizeC bucket: current size of the committed bucketE bucket: current size of the excess bucketP bucket: current size of the peak bucketArrival time of last packet89


Average sending r<strong>at</strong>eTSW window lengthClass PolicyClassifier also contai<strong>ns</strong> a Policer Table to store the mappings from a policy type <strong>and</strong> initial code pointpair to its associ<strong>at</strong>ed downgraded code point(s).9.3 Configur<strong>at</strong>ion<strong>The</strong> number of physical <strong>and</strong> virtual queues can be configured as:$dsredq set numQueues_ 1$dsredq setNumPrec 2Variable numQueues_ in class dsREDQueue specifies the number of physical queues. It has a default value as 4 definedin ~<strong>ns</strong>/tcl/lib/<strong>ns</strong>-default.tcl <strong>and</strong> can be changed as shown in the example above. Variable setNumPrec sets the number ofvirtual queues within one physical queue.RED parameters can be configured for each virtual queue as follows:$dsredq configQ 0 1 10 20 0.10<strong>The</strong> mean packet size (in bytes) is also needed for the average RED queue length calcul<strong>at</strong>ion.$dsredq meanPktSize 1500<strong>The</strong> variant of MRED used to calcul<strong>at</strong>e queue sizes can be configured.$dsredq setMREDMode RIO-C 0<strong>The</strong> above comm<strong>and</strong> sets the MRED mode of physical queue 0 to RIO-C. If the second argument was not included, all queueswould be set to RIO-C which is the default.<strong>The</strong> various MRED modes supported in DiffServ module are:RIO-C (RIO Coupled): <strong>The</strong> probability of dropping an out-of-profile packet is based on the weighted average lengths of allvirtual queues; while the probability of dropping an in-profile packet is based solely on the weighted average length ofits virtual queue.RIO-D (RIO De-coupled): Similar to RIO-C; except the probability of dropping an out-of-profile packet is based on thesize of its virtual queue.WRED (Weighted RED): All probabilities are based on a single queue length.DROP: Same as a drop tail queue with queue limit set by RED minimum threshold: when the queue size reaches theminimum threshold, all packets are dropped regardless of marking.<strong>The</strong> following comm<strong>and</strong> adds an entry to the PHB Table <strong>and</strong> maps code point 11 to physical queue 0 <strong>and</strong> virtual queue 1.$dsredq addPHBEntry 11 0 190


In <strong>ns</strong>, packets are defaulted to a code point of zero. <strong>The</strong>refore, user must add a PHB entry for the zero code point in order toh<strong>and</strong>le best effort traffic.In addition, comm<strong>and</strong>s are available to allow the user to choose the scheduling mode between physical queues. For example:$dsredq setSchedularMode WRR$dsredq addQueueWeights 1 5<strong>The</strong> above pair of comm<strong>and</strong>s sets the scheduling mode to Weighted Round Robin <strong>and</strong> the weight for queue 1 to 5. Otherscheduling modes supported are Weighted Interleaved Round Robin (WIRR), Round Robin (RR), <strong>and</strong> Priority (PRI). <strong>The</strong>default scheduling mode is Round Robin.For Priority scheduling, priority is arranged in sequential order with queue 0 having the highest priority. Also, one can set thea limit on the maximum b<strong>and</strong>width a particular queue can get using as follows:$dsredq setSchedularMode PRI$dsredq addQueueR<strong>at</strong>e 0 5000000<strong>The</strong>se comm<strong>and</strong>s specify the maximum b<strong>and</strong>width th<strong>at</strong> queue 0 can co<strong>ns</strong>ume is 5Mb.<strong>The</strong> addPolicyEntry comm<strong>and</strong> is used to add an entry to the Policy Table. It takes different parameters depending onwh<strong>at</strong> policer type is used. <strong>The</strong> first two parameters after the comm<strong>and</strong> name are always the source <strong>and</strong> destin<strong>at</strong>ion node IDs,<strong>and</strong> the next parameter is the policer type. Following the policer type are the parameters needed by th<strong>at</strong> policer as summarizedbelow:Null Initial code pointTSW2CM Initial code point CIRTSW3CM Initial code point CIR PIRTokenBucket Initial code point CIR CBSsrTCM Initial code point CIR CBS EBStrTCM Initial code point CIR CBS PIR PBSNote th<strong>at</strong> the Null policer requires only the initial code point. Since this policer does not downgrade packets, other inform<strong>at</strong>ionis not necessary. Co<strong>ns</strong>ider a Tcl script for which $q is a variable for an edge queue, <strong>and</strong> $s <strong>and</strong> $d are source <strong>and</strong> destin<strong>at</strong>ionnodes. <strong>The</strong> following comm<strong>and</strong> adds a TSW2CM policer for traffic going from the source to the destin<strong>at</strong>ion:$q addPolicyEntry [$s id] [$d id] TSW2CM 10 2000000Other parameters could be used for different policers in place of "TSW2CM":Null 10TSW3CM 10 2000000 3000000TokenBucket 10 2000000 10000srTCM 10 2000000 10000 20000trTCM 10 2000000 10000 3000000 10000Note, however, th<strong>at</strong> only one policy can be applied to any source destin<strong>at</strong>ion pair.91


<strong>The</strong> following comm<strong>and</strong> adds an entry to the Policer Table, specifying th<strong>at</strong> the trTCM has initial (green) code point 10,downgraded (yellow) code point 11 <strong>and</strong> further downgraded (red) code point 12:$dsredq addPolicerEntry trTCM 10 11 12<strong>The</strong>re must be a Policer Table entry in place for every policer type <strong>and</strong> initial code point pair. It should be noticed th<strong>at</strong> theNull policer is added in the following way:$dsredq addPolicerEntry Null 10Downgrade code points are not specified because the Null policy does not meter traffic characteristics.Queries supported:Output entires in Policy Table, one line <strong>at</strong> a time:$dsredq printPolicyTableOutput entires in Policer Table, one line <strong>at</strong> a time:$dsredq printPolicerTableOutput entries in PHB table, one line <strong>at</strong> a time:$dsredq printPHBTablePackets st<strong>at</strong>istic results:$dsredq printSt<strong>at</strong>sSample output:Packets St<strong>at</strong>isticsCP TotPkts TxPkts ldrops edropsAll 249126 249090 21 1510 150305 150300 0 520 98821 98790 21 10CP: code pointTotPkts: packets receivedTxPkts: packets sentldrops: packets are dropped due to link overflowedrops: RED early dropping).Retur<strong>ns</strong> the RED weighted average size of the specified physical queue:$dsredq getAverage 0Retur<strong>ns</strong> the current size of the C Bucket (in bytes):$dsredq getCBucket9.4 Comm<strong>and</strong>s <strong>at</strong> a glance<strong>The</strong> following is a list of rel<strong>at</strong>ed comm<strong>and</strong>s commonly used in simul<strong>at</strong>ion scripts:92


$<strong>ns</strong> simplex-link $edge $core 10Mb 5ms dsRED/edge$<strong>ns</strong> simplex-link $core $edge 10Mb 5ms dsRED/core<strong>The</strong>se two comm<strong>and</strong>s cre<strong>at</strong>e the queues along the link between an edge router <strong>and</strong> a core router.set qEC [[$<strong>ns</strong> link $edge $core] queue]# Set DS RED parameters from Edge to Core:$qEC meanPktSize $packetSize$qEC set numQueues_ 1$qEC setNumPrec 2$qEC addPolicyEntry [$s1 id] [$dest id] TokenBucket 10 $cir0 $cbs0$qEC addPolicyEntry [$s2 id] [$dest id] TokenBucket 10 $cir1 $cbs1$qEC addPolicerEntry TokenBucket 10 11$qEC addPHBEntry 10 0 0$qEC addPHBEntry 11 0 1$qEC configQ 0 0 20 40 0.02$qEC configQ 0 1 10 20 0.10This block of code obtai<strong>ns</strong> h<strong>and</strong>le to the DiffServ queue from an edge router to a core router <strong>and</strong> configures all of theparameters for it.<strong>The</strong> meanPktSize comm<strong>and</strong> is required for the RED st<strong>at</strong>e variables to be calcul<strong>at</strong>ed accur<strong>at</strong>ely. Setting the number of physicalqueues <strong>and</strong> precedence levels is optional, but it aids efficiency. Because neither the scheduling or MRED mode type are set,they default to Round Robin scheduling <strong>and</strong> RIO-C Active Queue Management.<strong>The</strong> addPolicyEntry comm<strong>and</strong>s establish two policies <strong>at</strong> the edge queue: one between nodes S1 <strong>and</strong> Dest <strong>and</strong> one betweennodes S2 <strong>and</strong> Dest. Note th<strong>at</strong> the [$s1 id] comm<strong>and</strong> retur<strong>ns</strong> the ID value needed by addPolicyEntry. <strong>The</strong> CIR <strong>and</strong>CBS values used in the policies are the ones set <strong>at</strong> the beginning of the script.<strong>The</strong> addPolicerEntry line is required because each policer type <strong>and</strong> initial code point pair requires an entry in the PolicerTable. Each of the policies uses the same policer <strong>and</strong> initial code point, so only one entry is needed.<strong>The</strong> addPHBEntry comm<strong>and</strong>s map each code point to a combin<strong>at</strong>ion of physical <strong>and</strong> virtual queue. Although each codepoint in this example maps to a unique combin<strong>at</strong>ion of physical <strong>and</strong> virtual queue, multiple code points could receive identicaltre<strong>at</strong>ment.Finally, the configQ comm<strong>and</strong>s set the RED parameters for each virtual queue. It specifies the virtual queue by firsttwo parameters, for example, 0 <strong>and</strong> 1. <strong>The</strong> next three parameters are the minimum threshold, maximum threshold, <strong>and</strong> themaximum dropping probability. Note th<strong>at</strong> as the precedence value increases, the RED parameters become harsher.set qCE [[$<strong>ns</strong> link $core $e1] queue]# Set DS RED parameters from Core to Edge:$qCE meanPktSize $packetSize$qCE set numQueues_ 1$qCE setNumPrec 2$qCE addPHBEntry 10 0 0$qCE addPHBEntry 11 0 1$qCE configQ 0 0 20 40 0.0293


$qCE configQ 0 1 10 20 0.10Note th<strong>at</strong> the configur<strong>at</strong>ion of a core queue m<strong>at</strong>ches th<strong>at</strong> of an edge queue, except th<strong>at</strong> there is no Policy Table or Policer Tableto configure <strong>at</strong> a core router. A core router’s chief requirement is th<strong>at</strong> it has a PHB entry for all code points th<strong>at</strong> it will see.$qE1C printPolicyTable$qCE2 printCoreSt<strong>at</strong>s<strong>The</strong>se methods output the policy or policer tables on link <strong>and</strong> different st<strong>at</strong>istics.For further inform<strong>at</strong>ion, please refer to the example scripts under ~<strong>ns</strong>/tcl/ex/diffserv.94


%95


Chapter 10AgentsAgents represent endpoints where network-layer packets are co<strong>ns</strong>tructed or co<strong>ns</strong>umed, <strong>and</strong> are used in the implement<strong>at</strong>ionof protocols <strong>at</strong> various layers. <strong>The</strong> class Agent has an implement<strong>at</strong>ion partly in OTcl <strong>and</strong> partly in C++. <strong>The</strong> C++implement<strong>at</strong>ion is contained in ~<strong>ns</strong>/agent.cc <strong>and</strong> ~<strong>ns</strong>/agent.h, <strong>and</strong> the OTcl support is in ~<strong>ns</strong>/tcl/lib/<strong>ns</strong>-agent.tcl.10.1 Agent st<strong>at</strong>e<strong>The</strong> C++ class Agent includes enough internal st<strong>at</strong>e to assign various fields to a simul<strong>at</strong>ed packet before it is sent. Thisst<strong>at</strong>e includes the following:addr_dst_size_type_fid_prio_flags_defttl_node address of myself (source address in packets)where I am sending packets topacket size in bytes (placed into the common packet header)type of packet (in the common header, see packet.h)the IP flow identifier (<strong>formerly</strong> class in <strong>ns</strong>-1)the IP priority fieldpacket flags (similar to <strong>ns</strong>-1)default IP ttl value<strong>The</strong>se variables may be modified by any class derived from Agent, although not all of them may be needed by any particularagent.10.2 Agent methods<strong>The</strong> class Agent supports packet gener<strong>at</strong>ion <strong>and</strong> reception. <strong>The</strong> following member functio<strong>ns</strong> are implemented by theC++ Agent class, <strong>and</strong> are generally not over-ridden by derived classes:Packet* allocpkt()Packet* allocpkt(int)alloc<strong>at</strong>e new packet <strong>and</strong> assign its fieldsalloc<strong>at</strong>e new packet with a d<strong>at</strong>a payload of n bytes <strong>and</strong> assign its fields96


<strong>The</strong> following member functio<strong>ns</strong> are also defined by the class Agent, but are intended to be over-ridden by classes derivingfrom Agent:void timeout(timeout number)void recv(Packet*, H<strong>and</strong>ler*)subclass-specific time out methodreceiving agent main receive p<strong>at</strong>h<strong>The</strong> allocpkt() method is used by derived classes to cre<strong>at</strong>e packets to send. <strong>The</strong> function fills in the following fields inthe common packet header (Section 12): uid, ptype, size, <strong>and</strong> the following fields in the IP header: src, dst,flowid, prio, ttl. It also zero-fills in the following fields of the Flags header: ecn, pri, usr1, usr2. Anypacket header inform<strong>at</strong>ion not included in these lists must be must be h<strong>and</strong>led in the classes derived from Agent.<strong>The</strong> recv() method is the main entry point for an Agent which receives packets, <strong>and</strong> is invoked by upstream nodes whe<strong>ns</strong>ending a packet. In most cases, Agents make no use of the second argument (the h<strong>and</strong>ler defined by upstream nodes).10.3 Protocol Agents<strong>The</strong>re are several agents supported in the simul<strong>at</strong>or. <strong>The</strong>se are their names in OTcl:TCPTCP/RenoTCP/NewrenoTCP/Sack1TCP/FackTCP/FullTcpTCP/VegasTCP/Vegas/RBPTCP/Vegas/RBPTCP/AsymTCP/Reno/AsymTCP/Newreno/AsymTCPSinkTCPSink/DelAckTCPSink/AsymTCPSink/Sack1TCPSink/Sack1/DelAcka “Tahoe” TCP sender (cwnd = 1 on any loss)a “Reno” TCP sender (with fast recovery)a modified Reno TCP sender (changes fast recovery)a SACK TCP sendera “forward” SACK sender TCPa more full-functioned TCP with 2-way traffica “Vegas” TCP sendera Vegas TCP with “r<strong>at</strong>e based pacing”a Reno TCP with “r<strong>at</strong>e based pacing”an experimental Tahoe TCP for asymmetric linksan experimental Reno TCP for asymmetric linksan experimental Newreno TCP for asymmetric linksa Reno or Tahoe TCP receiver (not used for FullTcp)a TCP delayed-ACK receiveran experimental TCP sink for asymmetric linksa SACK TCP receivera delayed-ACK SACK TCP receiverUDPa basic UDP agentRTPRTCPan RTP sender <strong>and</strong> receiveran RTCP sender <strong>and</strong> receiverLossMonitora packet sink which checks for lossesIVS/SourceIVS/Receiveran IVS sourcean IVS receiver97


CtrMcast/EncapCtrMcast/DecapMessageMessage/PruneSRMSRM/AdaptiveTapNullrtProto/DVa “centralised multicast” encapsul<strong>at</strong>ora “centralised multicast” de-encapsul<strong>at</strong>ora protocol to carry textual messagesprocesses multicast routing prune messagesan SRM agent with non-adaptive timersan SRM agent with adaptive timersinterfaces the simul<strong>at</strong>or to a live networka degener<strong>at</strong>e agent which discards packetsdistance-vector routing protocol agentAgents are used in the implement<strong>at</strong>ion of protocols <strong>at</strong> various layers. Thus, for some tra<strong>ns</strong>port protocols (e.g. UDP) thedistribution of packet sizes <strong>and</strong>/or inter-departure times may be dict<strong>at</strong>ed by some separ<strong>at</strong>e object representing the dem<strong>and</strong>sof an applic<strong>at</strong>ion. To this end, agents expose an applic<strong>at</strong>ion programming interface (API) to the applic<strong>at</strong>ion. For agents usedin the implement<strong>at</strong>ion of lower-layer protocols (e.g. routing agents), size <strong>and</strong> departure timing is generally dict<strong>at</strong>ed by theagent’s own processing of protocol messages.10.4 OTcl LinkageAgents may be cre<strong>at</strong>ed within OTcl <strong>and</strong> an agent’s internal st<strong>at</strong>e can be modified by use of Tcl’s set function <strong>and</strong> any Tclfunctio<strong>ns</strong> an Agent (or its base classes) implements. Note th<strong>at</strong> some of an Agent’s internal st<strong>at</strong>e may exist only within OTcl,<strong>and</strong> is thus is not directly accessible from C++.10.4.1 Cre<strong>at</strong>ing <strong>and</strong> Manipul<strong>at</strong>ing Agents<strong>The</strong> following example illustr<strong>at</strong>es the cre<strong>at</strong>ion <strong>and</strong> modific<strong>at</strong>ion of an Agent in OTcl:set newtcp [new Agent/TCP];# cre<strong>at</strong>e new object (<strong>and</strong> C++ shadow object)$newtcp set window_ 20 ;# sets the tcp agent’s window to 20$newtcp target $dest;# target is implemented in Connector class$newtcp set portID_ 1;# exists only in OTcl, not in C++10.4.2 Default ValuesDefault values for member variables, those visible in OTcl only <strong>and</strong> those linked between OTcl <strong>and</strong> C++ with bind areinitialized in the ~<strong>ns</strong>/tcl/lib/<strong>ns</strong>-default.tcl file. For example, Agent is initialized as follows:Agent set fid_ 0Agent set prio_ 0Agent set addr_ 098


Agent set dst_ 0Agent set flags_ 0Generally these initializ<strong>at</strong>io<strong>ns</strong> are placed in the OTcl namespace before any objects of these types are cre<strong>at</strong>ed. Thus, when anAgent object is cre<strong>at</strong>ed, the calls to bind in the objects’ co<strong>ns</strong>tructors will causes the corresponding member variables to beset to these specified defaults.10.4.3 OTcl Methods<strong>The</strong> i<strong>ns</strong>tance procedures defined for the OTcl Agent class are currently found in ~<strong>ns</strong>/tcl/lib/<strong>ns</strong>-agent.tcl. <strong>The</strong>y are as follows:port the agent’s port identifierdst-port the destin<strong>at</strong>ion’s port identifier<strong>at</strong>tach-source 〈stype〉 cre<strong>at</strong>e <strong>and</strong> <strong>at</strong>tach a Source object to an agent10.5 Examples: Tcp, TCP Sink Agents<strong>The</strong> class TCP represents a simplified TCP sender. It sends d<strong>at</strong>a to a TCPSink agent <strong>and</strong> processes its acknowledgments.It has a separ<strong>at</strong>e object associ<strong>at</strong>ed with it which represents an applic<strong>at</strong>ion’s dem<strong>and</strong>. By looking <strong>at</strong> the class TCPAgent<strong>and</strong> class TCPSinkAgent, we may see how rel<strong>at</strong>ively complex agents are co<strong>ns</strong>tructed. An example from the Tahoe TCPagent TCPAgent is also given to illustr<strong>at</strong>e the use of timers.10.5.1 Cre<strong>at</strong>ing the Agent<strong>The</strong> following OTcl code fragment cre<strong>at</strong>es a TCP agent <strong>and</strong> sets it up:set tcp [new Agent/TCP];# cre<strong>at</strong>e sender agent$tcp set fid_ 2;# set IP-layer flow IDset sink [new Agent/TCPSink];# cre<strong>at</strong>e receiver agent$<strong>ns</strong> <strong>at</strong>tach-agent $n0 $tcp ;# put sender on node $n0$<strong>ns</strong> <strong>at</strong>tach-agent $n3 $sink ;# put receiver on node $n3$<strong>ns</strong> connect $tcp $sink;# establish TCP connectio<strong>ns</strong>et ftp [new Applic<strong>at</strong>ion/FTP];# cre<strong>at</strong>e an FTP source "applic<strong>at</strong>ion"$ftp <strong>at</strong>tach-agent $tcp;# associ<strong>at</strong>e FTP with the TCP sender$<strong>ns</strong> <strong>at</strong> 1.2 "$ftp start";#arrange for FTP to start <strong>at</strong> time 1.2 sec<strong>The</strong> OTcl i<strong>ns</strong>truction new Agent/TCP results in the cre<strong>at</strong>ion of a C++ TcpAgent class object. Its co<strong>ns</strong>tructor first invokesthe co<strong>ns</strong>tructor of the Agent base class <strong>and</strong> then performs its own bindings. <strong>The</strong>se two co<strong>ns</strong>tructors appear as follows:<strong>The</strong> TcpSimpleAgent co<strong>ns</strong>tructor (~<strong>ns</strong>/tcp.cc):TcpAgent::TcpAgent() : Agent(PT_TCP), rtt_active_(0), rtt_seq_(-1),rtx_timer_(this), delsnd_timer_(this){bind("window_", &wnd_);bind("windowInit_", &wnd_init_);99


}bind("windowOption_", &wnd_option_);bind("windowCo<strong>ns</strong>tant_", &wnd_co<strong>ns</strong>t_);...bind("off_ip_", &off_ip_);bind("off_tcp_", &off_tcp_);...<strong>The</strong> Agent co<strong>ns</strong>tructor (~<strong>ns</strong>/agent.cc):Agent::Agent(int pkttype) :addr_(-1), dst_(-1), size_(0), type_(pkttype), fid_(-1),prio_(-1), flags_(0){memset(pending_, 0, sizeof(pending_)); /* timers */// this is really an IP agent, so set up// for gener<strong>at</strong>ing the appropri<strong>at</strong>e IP fields. . .bind("addr_", (int*)&addr_);bind("dst_", (int*)&dst_);bind("fid_", (int*)&fid_);bind("prio_", (int*)&prio_);bind("flags_", (int*)&flags_);...}<strong>The</strong>se code fragments illustr<strong>at</strong>e the common case where an agent’s co<strong>ns</strong>tructor passes a packet type identifier to the Agentco<strong>ns</strong>tructor. <strong>The</strong> values for the various packet types are used by the packet tracing facility (Section 26.5) <strong>and</strong> are defined in~<strong>ns</strong>/trace.h. <strong>The</strong> variables which are bound in the TcpAgent co<strong>ns</strong>tructor are ordinary i<strong>ns</strong>tance/member variables for theclass with the exception of the special integer values off_tcp_ <strong>and</strong> off_ip_. <strong>The</strong>se are needed in order to access a TCPheader <strong>and</strong> IP header, respectively. Additional details are in the section on packet headers (Section 12.1).Note th<strong>at</strong> the TcpAgent co<strong>ns</strong>tructor contai<strong>ns</strong> initializ<strong>at</strong>io<strong>ns</strong> for two timers, rtx_timer_ <strong>and</strong> delsnd_timer_.TimerH<strong>and</strong>ler objects are initialized by providing a pointer (the this pointer) to the relevant agent.10.5.2 Starting the Agent<strong>The</strong> TcpAgent agent is started in the example when its FTP source receives the start directive <strong>at</strong> time 1.2. <strong>The</strong> startoper<strong>at</strong>ion is an i<strong>ns</strong>tance procedure defined on the class Applic<strong>at</strong>ion/FTP (Section 38.4). It is defined in ~<strong>ns</strong>/tcl/lib/<strong>ns</strong>-source.tclas follows:Applic<strong>at</strong>ion/FTP i<strong>ns</strong>tproc start {} {[$self agent] send -1}In this case, agent refers to our simple TCP agent <strong>and</strong> send -1 is analogous to sending an arbitrarily large file.<strong>The</strong> call to send eventually results in the simple TCP sender gener<strong>at</strong>ing packets. <strong>The</strong> following function output performsthis:void TcpAgent::output(int seqno, int reason)100


{}Packet* p = allocpkt();hdr_tcp *tcph = (hdr_tcp*)p->access(off_tcp_);double now = Scheduler::i<strong>ns</strong>tance().clock();tcph->seqno() = seqno;tcph->ts() = now;tcph->reason() = reason;Connector::send(p, 0);...if (!(rtx_timer_.st<strong>at</strong>us() == TIMER_PENDING))/* No timer pending. Schedule one. */set_rtx_timer();Here we see an illustr<strong>at</strong>ion of the use of the Agent::allocpkt() method. This output routine first alloc<strong>at</strong>es a new packet(with its common <strong>and</strong> IP headers already filled in), but then must fill in the appropri<strong>at</strong>e TCP-layer header fields. To findthe TCP header in a packet (assuming it has been enabled (Section 12.2.4)) the off_tcp_ must be properly initialized, asillustr<strong>at</strong>ed in the co<strong>ns</strong>tructor. <strong>The</strong> packet access() method retur<strong>ns</strong> a pointer to the TCP header, its sequence number <strong>and</strong>time stamp fields are filled in, <strong>and</strong> the send() method of the class Connector is called to send the packet dow<strong>ns</strong>tream one hop.Note th<strong>at</strong> the C++ :: scoping oper<strong>at</strong>or is used here to avoid calling TcpSimpleAgent::send() (which is also defined).<strong>The</strong> check for a pending timer uses the timer method st<strong>at</strong>us() which is defined in the base class TimerH<strong>and</strong>ler. It is usedhere to set a retra<strong>ns</strong>mission timer if one is not already set (a TCP sender only sets one timer per window of packets on eachconnection).10.5.3 Processing Input <strong>at</strong> ReceiverMany of the TCP agents can be used with the class TCPSink as the peer. This class defines the recv() <strong>and</strong> ack()methods as follows:void TcpSink::recv(Packet* pkt, H<strong>and</strong>ler*){hdr_tcp *th = (hdr_tcp*)pkt->access(off_tcp_);acker_->upd<strong>at</strong>e(th->seqno());ack(pkt);Packet::free(pkt);}void TcpSink::ack(Packet* opkt){Packet* npkt = allocpkt();hdr_tcp *otcp = (hdr_tcp*)opkt->access(off_tcp_);hdr_tcp *ntcp = (hdr_tcp*)npkt->access(off_tcp_);ntcp->seqno() = acker_->Seqno();ntcp->ts() = otcp->ts();hdr_ip* oip = (hdr_ip*)opkt->access(off_ip_);hdr_ip* nip = (hdr_ip*)npkt->access(off_ip_);nip->flowid() = oip->flowid();hdr_flags* of = (hdr_flags*)opkt->access(off_flags_);101


hdr_flags* nf = (hdr_flags*)npkt->access(off_flags_);nf->ecn_ = of->ecn_;}acker_->append_ack((hdr_cmn*)npkt->access(off_cmn_),ntcp, otcp->seqno());send(npkt, 0);<strong>The</strong> recv() method overrides the Agent::recv() method (which merely discards the received packet). It upd<strong>at</strong>es someinternal st<strong>at</strong>e with the sequence number of the received packet (<strong>and</strong> therefore requires the off_tcp_ variable to be properlyinitialized. It then gener<strong>at</strong>es an acknowledgment for the received packet. <strong>The</strong> ack() method makes liberal use of access topacket header fields including separ<strong>at</strong>e accesses to the TCP header, IP header, Flags header, <strong>and</strong> common header. <strong>The</strong> call tosend() invokes the Connector::send() method.10.5.4 Processing Respo<strong>ns</strong>es <strong>at</strong> the SenderOnce the simple TCP’s peer receives d<strong>at</strong>a <strong>and</strong> gener<strong>at</strong>es an ACK, the sender must (usually) process the ACK. In theTcpAgent agent, this is done as follows:/** main reception p<strong>at</strong>h - should only see acks, otherwise the* network connectio<strong>ns</strong> are misconfigured*/void TcpAgent::recv(Packet *pkt, H<strong>and</strong>ler*){hdr_tcp *tcph = (hdr_tcp*)pkt->access(off_tcp_);hdr_ip* iph = (hdr_ip*)pkt->access(off_ip_);...if (((hdr_flags*)pkt->access(off_flags_))->ecn_)quench(1);if (tcph->seqno() > last_ack_) {newack(pkt);opencwnd();} else if (tcph->seqno() == last_ack_) {if (++dupacks_ == NUMDUPACKS) {...}}Packet::free(pkt);send(0, 0, maxburst_);}This routine is invoked when an ACK arrives <strong>at</strong> the sender. In this case, once the inform<strong>at</strong>ion in the ACK is processed (bynewack) the packet is no longer needed <strong>and</strong> is returned to the packet memory alloc<strong>at</strong>or. In addition, the receipt of the ACKindic<strong>at</strong>es the possibility of sending additional d<strong>at</strong>a, so the TcpSimpleAgent::send() method is invoked which <strong>at</strong>temptsto send more d<strong>at</strong>a if the TCP window allows.102


10.5.5 Implementing TimersAs described in the following chapter (Chapter 11), specific timer classes must be derived from an abstract base classTimerH<strong>and</strong>ler defined in ~<strong>ns</strong>/timer-h<strong>and</strong>ler.h. I<strong>ns</strong>tances of these subclasses can then be used as various agent timers. Anagent may wish to override the Agent::timeout() method (which does nothing). In the case of the Tahoe TCP agent,two timers are used: a delayed send timer delsnd_timer_ <strong>and</strong> a retra<strong>ns</strong>mission timer rtx_timer_. We describe theretra<strong>ns</strong>mission timer in TCP (Section 11.1.2) as an example of timer usage.10.6 Cre<strong>at</strong>ing a New AgentTo cre<strong>at</strong>e a new agent, one has to do the following:1. decide its inheritance structure (Section 10.6.1), <strong>and</strong> cre<strong>at</strong>e the appropri<strong>at</strong>e class definitio<strong>ns</strong>,2. define the recv() <strong>and</strong> timeout() methods (Section 10.6.2),3. define any necessary timer classes,4. define OTcl linkage functio<strong>ns</strong> (Section 10.6.3),5. write the necessary OTcl code to access the agent (Section 10.6.4).<strong>The</strong> action required to cre<strong>at</strong>e <strong>and</strong> agent can be illustr<strong>at</strong>ed by mea<strong>ns</strong> of a very simple example. Suppose we wish to co<strong>ns</strong>tructan agent which performs the ICMP ECHO REQUEST/REPLY (or “ping”) oper<strong>at</strong>io<strong>ns</strong>.10.6.1 Example: A “ping” requestor (Inheritance Structure)Deciding on the inheritance structure is a m<strong>at</strong>ter of personal choice, but is likely to be rel<strong>at</strong>ed to the layer <strong>at</strong> which the agentwill oper<strong>at</strong>e <strong>and</strong> its assumptio<strong>ns</strong> on lower layer functionality. <strong>The</strong> simplest type of Agent, connectionless d<strong>at</strong>agram-orientedtra<strong>ns</strong>port, is the Agent/UDP base class. Traffic gener<strong>at</strong>ors can easily be connected to UDP Agents. For protocols wishing touse a connection-oriented stream tra<strong>ns</strong>port (like TCP), the various TCP Agents could be used. Finally, if a new tra<strong>ns</strong>port or“sub-tra<strong>ns</strong>port” protocol is to be developed, using Agent as the base class would likely be the best choice. In our example,we’ll use Agent as the base class, given th<strong>at</strong> we are co<strong>ns</strong>tructing an agent logically belonging to the IP layer (or just above it).We may use the following class definitio<strong>ns</strong>:class ECHO_Timer;class ECHO_Agent : public Agent {public:ECHO_Agent();int comm<strong>and</strong>(int argc, co<strong>ns</strong>t char*co<strong>ns</strong>t* argv);protected:void timeout(int);void sendit();double interval_;ECHO_Timer echo_timer_;};class ECHO_Timer : public TimerH<strong>and</strong>ler {103


public:ECHO_Timer(ECHO_Agent *a) : TimerH<strong>and</strong>ler() { a_ = a; }protected:virtual void expire(Event *e);ECHO_Agent *a_;};10.6.2 <strong>The</strong> recv() <strong>and</strong> timeout() Methods<strong>The</strong> recv() method is not defined here, as this agent represents a request function <strong>and</strong> will generally not be receiving eventsor packets 1 . By not defining the recv() method, the base class version of recv() (i.e., Connector::recv()) is used. <strong>The</strong>timeout() method is used to periodically send request packets. <strong>The</strong> following timeout() method is used, along with ahelper method, sendit():void ECHO_Agent::timeout(int){sendit();echo_timer_.resched(interval_);}void ECHO_Agent::sendit(){Packet* p = allocpkt();ECHOHeader *eh = ECHOHeader::access(p->bits());eh->timestamp() = Scheduler::i<strong>ns</strong>tance().clock();send(p, 0); // Connector::send()}void ECHO_Timer::expire(Event *e){a_->timeout(0);}<strong>The</strong> timeout() method simply arranges for sendit() to be executed every interval_ seconds. <strong>The</strong> sendit() methodcre<strong>at</strong>es a new packet with most of its header fields already set up by allocpkt(). <strong>The</strong> packet is only lacks the current timestamp. <strong>The</strong> call to access() provides for a structured interface to the packet header fields, <strong>and</strong> is used to set the timestampfield. Note th<strong>at</strong> this agent uses its own special header (“ECHOHeader”). <strong>The</strong> cre<strong>at</strong>ion <strong>and</strong> use of packet headers is describedin l<strong>at</strong>er chapter (Chapter 12); to send the packet to the next dow<strong>ns</strong>tream node, Connector::send() is invoked without ah<strong>and</strong>ler.10.6.3 Linking the “ping” Agent with OTclWe have the methods <strong>and</strong> mechanisms for establishing OTcl Linkage earlier (Chapter 3). This section is a brief review of theessential fe<strong>at</strong>ures of th<strong>at</strong> earlier chapter, <strong>and</strong> describes the minimum functionality required to cre<strong>at</strong>e the ping agent.<strong>The</strong>re are three items we must h<strong>and</strong>le to properly link our agent with Otcl. First we need to establish a mapping between theOTcl name for our class <strong>and</strong> the actual object cre<strong>at</strong>ed when an i<strong>ns</strong>tanti<strong>at</strong>ion of the class is requested in OTcl. This is done asfollows:1 This is perhaps unrealistically simple. An ICMP ECHO REQUEST agent would likely wish to process ECHO REPLY messages.104


st<strong>at</strong>ic class ECHOClass : public TclClass {public:ECHOClass() : TclClass("Agent/ECHO") {}TclObject* cre<strong>at</strong>e(int argc, co<strong>ns</strong>t char*co<strong>ns</strong>t* argv) {return (new ECHO_Agent());}} class_echo;Here, a st<strong>at</strong>ic object “class_echo” is cre<strong>at</strong>ed. It’s co<strong>ns</strong>tructor (executed immedi<strong>at</strong>ely when the simul<strong>at</strong>or is executed) placesthe class name “Agent/ECHO” into the OTcl name space. <strong>The</strong> mixing of case is by convention; recall from Section 3.5 in theearlier chapters th<strong>at</strong> the “/” character is a hierarchy delimiter for the interpreted hierarchy. <strong>The</strong> definition of the cre<strong>at</strong>e()method specifies how a C++ shadow object should be cre<strong>at</strong>ed when the OTcl interpreter is i<strong>ns</strong>tructed to cre<strong>at</strong>e an objectof class “Agent/ECHO”. In this case, a dynamically-alloc<strong>at</strong>ed object is returned. This is the normal way new C++ shadowobjects are cre<strong>at</strong>ed.Once we have the object cre<strong>at</strong>ion set up, we will want to link C++ member variables with corresponding variables in the OTclnname space, so th<strong>at</strong> accesses to OTcl variables are actually backed by member variables in C++. Assume we would likeOTcl to be able to adjust the sending interval <strong>and</strong> the packet size. This is accomplished in the class’s co<strong>ns</strong>tructor:ECHO_Agent::ECHO_Agent() : Agent(PT_ECHO){bind_time("interval_", &interval_);bind("packetSize_", &size_);}Here, the C++ variables interval_ <strong>and</strong> size_ are linked to the OTcl i<strong>ns</strong>tance variables interval_ <strong>and</strong> packetSize_,respectively. Any read or modify oper<strong>at</strong>ion to the Otcl variables will result in a corresponding access to the underlying C++variables. <strong>The</strong> details of the bind() methods are described elsewhere (Section 3.4.2). <strong>The</strong> defined co<strong>ns</strong>tant PT_ECHO ispassed to the Agent() co<strong>ns</strong>tuctor so th<strong>at</strong> the Agent::allocpkt() method may set the packet type field used by the tracesupport (Section 26.5). In this case, PT_ECHO represents a new packet type <strong>and</strong> must be defined in ~<strong>ns</strong>/trace.h (Section 26.4).Once object cre<strong>at</strong>ion <strong>and</strong> variable binding is set up, we may want to cre<strong>at</strong>e methods implemented in C++ but which can beinvoked from OTcl (Section 3.4.4). <strong>The</strong>se are often control functio<strong>ns</strong> th<strong>at</strong> initi<strong>at</strong>e, termin<strong>at</strong>e or modify behavior. In our presentexample, we may wish to be able to start the ping query agent from OTcl using a “start” directive. This may be implementedas follows:int ECHO_Agent::comm<strong>and</strong>(int argc, co<strong>ns</strong>t char*co<strong>ns</strong>t* argv){if (argc == 2) {if (strcmp(argv[1], "start") == 0) {timeout(0);return (TCL_OK);}}return (Agent::comm<strong>and</strong>(argc, argv));}Here, the start() method available to OTcl simply calls the C++ member function timeout() which initi<strong>at</strong>es the firstpacket gener<strong>at</strong>ion <strong>and</strong> schedules the next. Note this class is so simple it does not even include a way to be stopped.105


10.6.4 Using the agent through OTcl<strong>The</strong> agent we have cre<strong>at</strong>ed will have to be i<strong>ns</strong>tanti<strong>at</strong>ed <strong>and</strong> <strong>at</strong>tached to a node. Note th<strong>at</strong> a node <strong>and</strong> simul<strong>at</strong>or object isassumed to have already been cre<strong>at</strong>ed. <strong>The</strong> following OTcl code performs these functio<strong>ns</strong>:set echoagent [new Agent/ECHO]$simul<strong>at</strong>or <strong>at</strong>tach-agent $node $echoagentTo set the interval <strong>and</strong> packet size, <strong>and</strong> start packet gener<strong>at</strong>ion, the following OTcl code is executed:$echoagent set dst_ $dest$echoagent set fid_ 0$echoagent set prio_ 0$echoagent set flags_ 0$echoagent set interval_ 1.5$echoagent set packetSize_ 1024$echoagent startThis will cause our agent to gener<strong>at</strong>e one 1024-byte packet destined for node $dest every 1.5 seconds.10.7 <strong>The</strong> Agent APISimul<strong>at</strong>ed applic<strong>at</strong>io<strong>ns</strong> may be implemented on top of protocol agents. Chapter 38 describes the API used by applic<strong>at</strong>io<strong>ns</strong> toaccess the services provided by the protocol agent.10.8 Different agent objectsClass Agent forms the base class from which different types of objects like Nullobject, TCP etc are derived. <strong>The</strong> methods forAgent class are described in the next section. Configur<strong>at</strong>ion parameters for:fid_ Flowid.prio_ Priority.agent_addr_ Address of this agent.agent_port_ Port adress of this agent.dst_addr_Destin<strong>at</strong>ion address for the agent.dst_port_ Destin<strong>at</strong>ion port address for the agent.flags_ttl_ TTL defaults to 32.<strong>The</strong>re are no st<strong>at</strong>e variables specific to the generic agent class. Other objects derived from Agent are given below:106


Null Objects Null objects are a subclass of agent objects th<strong>at</strong> implement a traffic sink. <strong>The</strong>y inherit all of the generic agentobject functionality. <strong>The</strong>re are no methods specific to this object. <strong>The</strong> st<strong>at</strong>e variables are:• sport_• dport_LossMonitor Objects LossMonitor objects are a subclass of agent objects th<strong>at</strong> implement a traffic sink which also maintai<strong>ns</strong>some st<strong>at</strong>istics about the received d<strong>at</strong>a e.g., number of bytes received, number of packets lost etc. <strong>The</strong>y inherit all ofthe generic agent object functionality.$lossmonitor clearResets the expected sequence number to -1.St<strong>at</strong>e Variables are:nlost_ Number of packets lost.npkts_ Number of packets received.bytes_ Number of bytes received.lastPktTime_ Time <strong>at</strong> which the last packet was received.expected_ <strong>The</strong> expected sequence number of the next packet.TCP objects TCP objects are a subclass of agent objects th<strong>at</strong> implement the BSD Tahoe TCP tra<strong>ns</strong>port protocol as describedin paper: "Fall, K., <strong>and</strong> Floyd, S. Compariso<strong>ns</strong> of Tahoe, Reno, <strong>and</strong> Sack TCP. December 1995." URL ftp://ftp.ee.lbl.gov/papers/sacks.ps.Z. <strong>The</strong>y inherit all of the generic agent functionality. Configur<strong>at</strong>ion Parameters are:window_ <strong>The</strong> upper bound on the advertised window for the TCP connection.maxcwnd_ <strong>The</strong> upper bound on the congestion window for the TCP connection. Set to zero to ignore. (This is thedefault.)windowInit_ <strong>The</strong> initial size of the congestion window on slow-start.windowOption_ <strong>The</strong> algorithm to use for managing the congestion window.windowThresh_ Gain co<strong>ns</strong>tant to exponential averaging filter used to compute awnd (see below). For investig<strong>at</strong>io<strong>ns</strong>of different window-increase algorithms.overhead_ <strong>The</strong> range of a uniform r<strong>and</strong>om variable used to delay each output packet. <strong>The</strong> idea is to i<strong>ns</strong>ert r<strong>and</strong>omdelays <strong>at</strong> the source in order to avoid phase effects, when desired [see Floyd, S., <strong>and</strong> Jacobson, V. On Traffic PhaseEffects in Packet-Switched G<strong>at</strong>eways. Internetworking: Research <strong>and</strong> Experience, V.3 N.3, September 1992. pp.115-156 ]. This has only been implemented for the Tahoe ("tcp") version of tcp, not for tcp-reno. This is notintended to be a realistic model of CPU processing overhead.ecn_ Set to true to use explicit congestion notific<strong>at</strong>ion in addition to packet drops to signal congestion. This allows aFast Retra<strong>ns</strong>mit after a quench() due to an ECN (explicit congestion notific<strong>at</strong>ion) bit.packetSize_ <strong>The</strong> size in bytes to use for all packets from this source.tcpTick_ <strong>The</strong> TCP clock granularity for measuring roundtrip times. Note th<strong>at</strong> it is set by default to the non-st<strong>and</strong>ardvalue of 100ms.bugFix_ Set to true to remove a bug when multiple fast retra<strong>ns</strong>mits are allowed for packets dropped in a single windowof d<strong>at</strong>a.maxburst_ Set to zero to ignore. Otherwise, the maximum number of packets th<strong>at</strong> the source can send in respo<strong>ns</strong>e toa single incoming ACK.slow_start_restart_ Set to 1 to slow-start after the connection goes idle. On by default.Defined Co<strong>ns</strong>tants are:MWS <strong>The</strong> Maximum Window Size in packets for a TCP connection. MWS determines the size of an array in tcpsink.cc.<strong>The</strong> default for MWS is 1024 packets. For Tahoe TCP, the "window" parameter, representing the receiver’sadvertised window, should be less than MWS-1. For Reno TCP, the "window" parameter should be lessthan (MWS-1)/2.107


St<strong>at</strong>e Variables are:dupacks_ Number of duplic<strong>at</strong>e acks seen since any new d<strong>at</strong>a was acknowledged.seqno_ Highest sequence number for d<strong>at</strong>a from d<strong>at</strong>a source to TCP.t_seqno_ Current tra<strong>ns</strong>mit sequence number.ack_ Highest acknowledgment seen from receiver. cwnd_ Current value of the congestion window.awnd_ Current value of a low-pass filtered version of the congestion window. For investig<strong>at</strong>io<strong>ns</strong> of different windowincreasealgorithms.ssthresh_ Current value of the slow-start threshold.rtt_ Round-trip time estim<strong>at</strong>e.srtt_ Smoothed round-trip time estim<strong>at</strong>e.rttvar_ Round-trip time mean devi<strong>at</strong>ion estim<strong>at</strong>e.backoff_ Round-trip time exponential backoff co<strong>ns</strong>tant.TCP/Reno Objects TCP/Reno objects are a subclass of TCP objects th<strong>at</strong> implement the Reno TCP tra<strong>ns</strong>port protocol describedin paper: "Fall, K., <strong>and</strong> Floyd, S. Compariso<strong>ns</strong> of Tahoe, Reno, <strong>and</strong> Sack TCP. December 1995." URL ftp://ftp.ee.lbl.gov/papers/sacks.ps.Z. <strong>The</strong>re are no methods, configur<strong>at</strong>ion parameters or st<strong>at</strong>e variables specific to this object.TCP/Newreno Objects TCP/Newreno objects are a subclass of TCP objects th<strong>at</strong> implement a modified version of the BSDReno TCP tra<strong>ns</strong>port protocol. <strong>The</strong>re are no methods or st<strong>at</strong>e variables specific to this object.Configur<strong>at</strong>ion Parameters are:newreno_changes_ Set to zero for the default New Reno described in "Fall, K., <strong>and</strong> Floyd, S. Compariso<strong>ns</strong> of Tahoe,Reno, <strong>and</strong> Sack TCP. December 1995". Set to 1 for additional New Reno algorithms [see Hoe, J., Improving theStart-up Behavior of a Congestion Control Scheme for TCP. in SIGCOMM 96, August 1996, pp. 270-280. URLhttp://www.acm.org/sigcomm/sigcomm96/papers/hoe.html.]; this includes the estim<strong>at</strong>ion of the ssthresh parameterduring slow-start.TCP/Vegas Objects <strong>The</strong>re are no methods or configur<strong>at</strong>ion parameters specific to this object. St<strong>at</strong>e variables are:• v_alpha_• v_beta_• v_gamma_• v_rtt_TCP/Sack1 Objects TCP/Sack1 objects are a subclass of TCP objects th<strong>at</strong> implement the BSD Reno TCP tra<strong>ns</strong>port protocolwith Selective Acknowledgement Exte<strong>ns</strong>io<strong>ns</strong> described in "Fall, K., <strong>and</strong> Floyd, S. Compariso<strong>ns</strong> of Tahoe, Reno, <strong>and</strong>Sack TCP. December 1995". URL ftp:// ftp.ee.lbl.gov/papers/sacks.ps.Z. <strong>The</strong>y inherit all of the TCP object functionality.<strong>The</strong>re are no methods, configur<strong>at</strong>ion parameters or st<strong>at</strong>e variables specific to this object.TCP/FACK Objects TCP/Fack objects are a subclass of TCP objects th<strong>at</strong> implement the BSD Reno TCP tra<strong>ns</strong>port protocolwith Forward Acknowledgement congestion control. <strong>The</strong>y inherit all of the TCP object functionality. <strong>The</strong>re are nomethods or st<strong>at</strong>e variables specific to this object.Configur<strong>at</strong>ion Parameters are:ss-div4 Overdamping algorithm. Divides ssthresh by 4 (i<strong>ns</strong>tead of 2) if congestion is detected within 1/2 RTT ofslow-start. (1=Enable, 0=Disable)rampdown Rampdown d<strong>at</strong>a smoothing algorithm. Slowly reduces congestion window r<strong>at</strong>her than i<strong>ns</strong>tantly halving it.(1=Enable, 0=Disable)TCP/FULLTCP Objects This section has not yet been added here. <strong>The</strong> implement<strong>at</strong>ion <strong>and</strong> the configur<strong>at</strong>ion parametersare described in paper: "Fall, K., Floyd, S., <strong>and</strong> Henderson, T., Ns Simul<strong>at</strong>or Tests for Reno FullTCP. July, 1997." URLftp://ftp.ee.lbl.gov/papers/fulltcp.ps.108


TCPSINK Objects TCPSink objects are a subclass of agent objects th<strong>at</strong> implement a receiver for TCP packets. <strong>The</strong> simul<strong>at</strong>oronly implements "one-way" TCP connectio<strong>ns</strong>, where the TCP source sends d<strong>at</strong>a packets <strong>and</strong> the TCP sink sendsACK packets. TCPSink objects inherit all of the generic agent functionality. <strong>The</strong>re are no methods or st<strong>at</strong>e variablesspecific to the TCPSink object. Configur<strong>at</strong>ion Parameters arepacketSize_ <strong>The</strong> size in bytes to use for all acknowledgment packets.maxSackBlocks_ <strong>The</strong> maximum number of blocks of d<strong>at</strong>a th<strong>at</strong> can be acknowledged in a SACK option. For a receiverth<strong>at</strong> is also using the time stamp option [RFC 1323], the SACK option specified in RFC 2018 has room to includethree SACK blocks. This is only used by the TCPSink/Sack1 subclass. This value may not be increased withinany particular TCPSink object after th<strong>at</strong> object has been alloc<strong>at</strong>ed. (Once a TCPSink object has been alloc<strong>at</strong>ed,the value of this parameter may be decreased but not increased).TCPSINK/DELACK Objects DelAck objects are a subclass of TCPSink th<strong>at</strong> implement a delayed-ACK receiver for TCPpackets. <strong>The</strong>y inherit all of the TCPSink object functionality. <strong>The</strong>re are no methods or st<strong>at</strong>e variables specific to theDelAck object. Configur<strong>at</strong>ion Parameters are:interval_ <strong>The</strong> amount of time to delay before gener<strong>at</strong>ing an acknowledgment for a single packet. If another packetarrives before this time expires, gener<strong>at</strong>e an acknowledgment immedi<strong>at</strong>ely.TCPSINK/SACK1 Objects TCPSink/Sack1 objects are a subclass of TCPSink th<strong>at</strong> implement a SACK receiver for TCPpackets. <strong>The</strong>y inherit all of the TCPSink object functionality. <strong>The</strong>re are no methods, configur<strong>at</strong>ion parameters or st<strong>at</strong>evariables specific to this object.TCPSINK/SACK1/DELACK Objects TCPSink/Sack1/DelAck objects are a subclass of TCPSink/Sack1 th<strong>at</strong> implement adelayed-SACK receiver for TCP packets. <strong>The</strong>y inherit all of the TCPSink/Sack1 object functionality. <strong>The</strong>re are nomethods or st<strong>at</strong>e variables specific to this object. Configur<strong>at</strong>ion Parameters are:interval_ <strong>The</strong> amount of time to delay before gener<strong>at</strong>ing an acknowledgment for a single packet. If another packetarrives before this time expires, gener<strong>at</strong>e an acknowledgment immedi<strong>at</strong>ely.10.9 Comm<strong>and</strong>s <strong>at</strong> a glanceFollowing are the agent rel<strong>at</strong>ed comm<strong>and</strong>s used in simul<strong>at</strong>ion scripts:<strong>ns</strong>_ <strong>at</strong>tach-agent This comm<strong>and</strong> <strong>at</strong>taches the to the . We assume here th<strong>at</strong> the has already been cre<strong>at</strong>ed. An agent istypically cre<strong>at</strong>ed by set agent [new Agent/AgentType] where Agent/AgentType defines the class definiton of thespecified agent type.$agent portThis retur<strong>ns</strong> the port number to which the agent is <strong>at</strong>tached.$agent dst-portThis retur<strong>ns</strong> the port number of the destin<strong>at</strong>ion. When any connection is setup between 2 nodes, each agent stores thedestin<strong>at</strong>ion port in its i<strong>ns</strong>tance variable called dst_port_.$agent <strong>at</strong>tach-app This comm<strong>and</strong>s <strong>at</strong>taches an applic<strong>at</strong>ion of type to the agent. A h<strong>and</strong>le to the applic<strong>at</strong>ion object is returned. Alsonote th<strong>at</strong> the applic<strong>at</strong>ion type must be defined as a packet type in packet.h.$agent <strong>at</strong>tach-source This used to be the procedure to <strong>at</strong>tach source of type to the agent. But this is obsolete now. Use <strong>at</strong>tach-app(described above) i<strong>ns</strong>tead.109


$agent <strong>at</strong>tach-tbf Attaches a token bucket filter (tbf) to the agent.$<strong>ns</strong>_ connect Sets up a connection between the src <strong>and</strong> dst agents.$<strong>ns</strong>_ cre<strong>at</strong>e-connection This sets up a complete connection between two agents. First cre<strong>at</strong>es a source of type <strong>and</strong> binds it to . <strong>The</strong>ncre<strong>at</strong>es a destin<strong>at</strong>ion of type <strong>and</strong> binds it to . Finally connects the src <strong>and</strong> dst agents <strong>and</strong> retur<strong>ns</strong> a h<strong>and</strong>le tothe source agent.$<strong>ns</strong>_ cre<strong>at</strong>e-connection-list This comm<strong>and</strong> is exactly similar to cre<strong>at</strong>e-connection described above. But i<strong>ns</strong>tead of returning only the source-agent, thisretur<strong>ns</strong> a list of source <strong>and</strong> destin<strong>at</strong>ion agents.Internal procedures:$<strong>ns</strong>_ simplex-connect This is an internal method th<strong>at</strong> actually sets up an unidirectional connection between the agent <strong>and</strong> agent. Itsimply sets the destin<strong>at</strong>ion address <strong>and</strong> destin<strong>at</strong>ion port of the as ’s agent-address <strong>and</strong> agent-port. <strong>The</strong> "connect"described above calls this method twice to set up a bi-directional connection between the src <strong>and</strong> dst.$agent set This is an internal procedure used to inform users of the backward comp<strong>at</strong>ibility issues resulting from the upgrade to 32-bitaddressing space currently used in <strong>ns</strong>.$agent <strong>at</strong>tach-trace This <strong>at</strong>taches the to the agent to allow nam-tracing of the agent events.In addition to the agent rel<strong>at</strong>ed procedures described here, there are additional methods th<strong>at</strong> support different type of agentslike Agent/Null, Agent/TCP, Agent/CBR, Agent/TORA, Agent/mcast etc. <strong>The</strong>se additional methods along with theprocedures described here can be found in <strong>ns</strong>/tcl/lib/(<strong>ns</strong>-agent.tcl, <strong>ns</strong>-lib.tcl, <strong>ns</strong>-mip.tcl, <strong>ns</strong>-mobilenode.tcl, <strong>ns</strong>-namsupp.tcl,<strong>ns</strong>-queue.tcl, <strong>ns</strong>-route.tcl, <strong>ns</strong>-s<strong>at</strong>.tcl, <strong>ns</strong>-source.tcl). <strong>The</strong>y are also described in the previous section.110


Chapter 11TimersTimers may be implemented in C++ or OTcl. In C++, timers are based on an abstract base class defined in ~<strong>ns</strong>/timer-h<strong>and</strong>ler.h.<strong>The</strong>y are most often used in agents, but the framework is general enough to be used by other objects. <strong>The</strong> discussion below isoriented towards the use of timers in agents.<strong>The</strong> procedures <strong>and</strong> functio<strong>ns</strong> described in this chapter can be found in ~<strong>ns</strong>/tcl/ex/timer.tcl, <strong>and</strong> ~<strong>ns</strong>/timer-h<strong>and</strong>ler.{cc, h}.In OTcl, a simple timer class is defined in ~<strong>ns</strong>/tcl/ex/timer.tcl. Subclasses can be derived to provide a simple mechanism forscheduling events <strong>at</strong> the OTcl level.11.1 C++ abstract base class TimerH<strong>and</strong>ler<strong>The</strong> abstract base class TimerH<strong>and</strong>ler contai<strong>ns</strong> the following public member functio<strong>ns</strong>:void sched(double delay) schedule a timer to expire delay seconds in the futurevoid resched(double delay) reschedule a timer (similar to sched(), but timer may be pending)void cancel() cancel a pending timerint st<strong>at</strong>us() retur<strong>ns</strong> timer st<strong>at</strong>us (either TIMER_IDLE, TIMER_PENDING, orTIMER_HANDLING)<strong>The</strong> abstract base class TimerH<strong>and</strong>ler contai<strong>ns</strong> the following protected members:virtual void expire(Event* e) =0 this method must be filled in by the timer clientvirtual void h<strong>and</strong>le(Event* e) co<strong>ns</strong>umes an event; invokes expire() <strong>and</strong> sets st<strong>at</strong>us_ of the timer appropri<strong>at</strong>elyint st<strong>at</strong>us_ keeps track of the current timer st<strong>at</strong>usEvent event_ event to be co<strong>ns</strong>umed upon timer expir<strong>at</strong>ion<strong>The</strong> pure virtual function expire() must be defined by the timer classes deriving from this abstract base class.Finally, two priv<strong>at</strong>e inline functio<strong>ns</strong> are defined:inline void _sched(double delay) {111


(void)Scheduler::i<strong>ns</strong>tance().schedule(this, &event_, delay);}inline void _cancel() {(void)Scheduler::i<strong>ns</strong>tance().cancel(&event_);}From this code we can see th<strong>at</strong> timers make use of methods of the Scheduler class.11.1.1 Definition of a new timerTo define a new timer, subclass this function <strong>and</strong> define h<strong>and</strong>le() if needed (h<strong>and</strong>le() is not always required):class MyTimer : public TimerH<strong>and</strong>ler {public:MyTimer(MyAgentClass *a) : TimerH<strong>and</strong>ler() { a_ = a; }virtual double expire(Event *e);protected:MyAgentClass *a_;};<strong>The</strong>n define expire:doubleMyTimer::expire(Event *e){// do the work// return TIMER_HANDLED; // => do not reschedule timer// return delay; // => reschedule timer after delay}Note th<strong>at</strong> expire() can return either the flag TIMER_HANDLED or a delay value, depending on the requirements for thistimer.Often MyTimer will be a friend of MyAgentClass, or expire() will only call a public function of MyAgentClass.Timers are not directly accessible from the OTcl level, although users are free to establish method bindings if they so desire.11.1.2 Example: Tcp retra<strong>ns</strong>mission timerTCP is an example of an agent which requires timers. <strong>The</strong>re are three timers defined in the basic Tahoe TCP agent defined intcp.cc:rtx_timer_; /* Retra<strong>ns</strong>mission timer */delsnd_timer_; /* Delays sending of packets by a small r<strong>and</strong>om amount of time, *//* to avoid phase effects */burstsnd_timer_; /* Helps TCP to stagger the tra<strong>ns</strong>mission of a large window *//* into several smaller bursts */112


In ~<strong>ns</strong>/tcp.h, three classes are derived from the base class class TimerH<strong>and</strong>ler:class RtxTimer : public TimerH<strong>and</strong>ler {public:RtxTimer(TcpAgent *a) : TimerH<strong>and</strong>ler() { a_ = a; }protected:virtual void expire(Event *e);TcpAgent *a_;};class DelSndTimer : public TimerH<strong>and</strong>ler {public:DelSndTimer(TcpAgent *a) : TimerH<strong>and</strong>ler() { a_ = a; }protected:virtual void expire(Event *e);TcpAgent *a_;};class BurstSndTimer : public TimerH<strong>and</strong>ler {public:BurstSndTimer(TcpAgent *a) : TimerH<strong>and</strong>ler() { a_ = a; }protected:virtual void expire(Event *e);TcpAgent *a_;};In the co<strong>ns</strong>tructor for TcpAgent in tcp.cc, each of these timers is initialized with the this pointer, which is assigned tothe pointer a_.TcpAgent::TcpAgent() : Agent(PT_TCP), rtt_active_(0), rtt_seq_(-1),...rtx_timer_(this), delsnd_timer_(this), burstsnd_timer_(this){...}In the following, we will focus only on the retra<strong>ns</strong>mission timer. Various helper methods may be defined to schedule timerevents; e.g.,/** Set retra<strong>ns</strong>mit timer using current rtt estim<strong>at</strong>e. By calling resched()* it does not m<strong>at</strong>ter whether the timer was already running.*/void TcpAgent::set_rtx_timer(){rtx_timer_.resched(rtt_timeout());}/** Set new retra<strong>ns</strong>mission timer if not all outst<strong>and</strong>ing* d<strong>at</strong>a has been acked. Otherwise, if a timer is still113


* outst<strong>and</strong>ing, cancel it.*/void TcpAgent::newtimer(Packet* pkt){hdr_tcp *tcph = (hdr_tcp*)pkt->access(off_tcp_);if (t_seqno_ > tcph->seqno())set_rtx_timer();else if (rtx_timer_.st<strong>at</strong>us() == TIMER_PENDING)rtx_timer_.cancel();}In the above code, the set_rtx_timer() method reschedules the retra<strong>ns</strong>mission timer by calling rtx_timer_.resched().Note th<strong>at</strong> if it is unclear whether or not the timer is already running, calling resched() elimin<strong>at</strong>es the need to explicitly cancelthe timer. In the second function, examples are given of the use of the st<strong>at</strong>us() <strong>and</strong> cancel(void) methods.Finally, the expire(void) method for class RtxTimer must be defined. In this case, expire(void) calls the timeout(void)method for TcpAgent. This is possible because timeout() is a public member function; if it were not, then RtxTimerwould have had to have been declared a friend class of TcpAgent.void TcpAgent::timeout(int tno){/* retra<strong>ns</strong>mit timer */if (tno == TCP_TIMER_RTX) {if (highest_ack_ == maxseq_ && !slow_start_restart_) {/** TCP option:* If no outst<strong>and</strong>ing d<strong>at</strong>a, then don’t do anything.*/return;};recover_ = maxseq_;recover_cause_ = 2;closecwnd(0);reset_rtx_timer(0,1);send_much(0, TCP_REASON_TIMEOUT, maxburst_);} else {/** delayed-send timer, with r<strong>and</strong>om overhead* to avoid phase effects*/send_much(1, TCP_REASON_TIMEOUT, maxburst_);}}void RtxTimer::expire(Event *e) {a_->timeout(TCP_TIMER_RTX);}<strong>The</strong> various TCP agents contain additional examples of timers.114


11.2 OTcl Timer classA simple timer class is defined in ~<strong>ns</strong>/tcl/mcast/timer.tcl. Subclasses of Timer can be defined as needed. Unlike the C++timer API, where a sched() aborts if the timer is already set, sched() <strong>and</strong> resched() are the same; i.e., no st<strong>at</strong>e is kept forthe OTcl timers. <strong>The</strong> following methods are defined in the Timer base class:$self sched $delay$self resched $delay$self cancel$self destroy$self expire;# causes "$self timeout" to be called $delay seconds in the future;# same as "$self sched $delay";# cancels any pending scheduled callback;# same as "$self cancel";# calls "$self timeout" immedi<strong>at</strong>ely11.3 Comm<strong>and</strong>s <strong>at</strong> a glanceFollowing is a list of methods for the class Timer. Note th<strong>at</strong> many different types of timers have been derived from this baseclass (viz. LogTimer, Timer/Iface, Timer/Iface/Prune, CacheTimer, Timer/Scuba etc).$timer sched This comm<strong>and</strong> cancels any other event th<strong>at</strong> may have been scheduled <strong>and</strong> re-schedules another event after time .$timer resched Similar to "sched" described above. Added to have similar APIs as th<strong>at</strong> of the C++ timers.$timer cancelThis cancels any scheduled event.$timer destroyThis is similar to cancel. Cancels any scheduled event.$timer expireThis comm<strong>and</strong> calls for a time-out. However the time-out procedure needs to be defined in the sub-classes.All these procedures can be found in <strong>ns</strong>/tcl/mcast/timer.tcl.115


Chapter 12Packet Headers <strong>and</strong> Form<strong>at</strong>s<strong>The</strong> procedures <strong>and</strong> functio<strong>ns</strong> described in this chapter can be found in ~<strong>ns</strong>/tcl/lib/<strong>ns</strong>-lib.tcl, ~<strong>ns</strong>/tcl/lib/<strong>ns</strong>-packet.tcl, <strong>and</strong>~<strong>ns</strong>/packet.{cc, h}.Objects in the class Packet are the fundamental unit of exchange between objects in the simul<strong>at</strong>ion. <strong>The</strong> class Packetprovides enough inform<strong>at</strong>ion to link a packet on to a list (i.e., in a PacketQueue or on a free list of packets), refer to a buffercontaining packet headers th<strong>at</strong> are defined on a per-protocol basis, <strong>and</strong> to refer to a buffer of packet d<strong>at</strong>a. New protocols maydefine their own packet headers or may extend existing headers with additional fields.New packet headers are introduced into the simul<strong>at</strong>or by defining a C++ structure with the needed fields, defining a st<strong>at</strong>icclass to provide OTcl linkage, <strong>and</strong> then modifying some of the simul<strong>at</strong>or initializ<strong>at</strong>ion code to assign a byte offset in eachpacket where the new header is to be loc<strong>at</strong>ed rel<strong>at</strong>ive to others.When the simul<strong>at</strong>or is initialized through OTcl, a user may choose to enable only a subset of the compiled-in packet form<strong>at</strong>s,resulting in a modest savings of memory during the execution of the simul<strong>at</strong>ion. Presently, most configured-in packet form<strong>at</strong>sare enabled. <strong>The</strong> management of which packet form<strong>at</strong>s are currently enabled in a simul<strong>at</strong>ion is h<strong>and</strong>led by a special packetheader manager object described below. This object supports an OTcl method used to specify which packet headers will beused in a simul<strong>at</strong>ion. If an object in the simul<strong>at</strong>or makes use of a field in a header which has not been enabled, a run-timef<strong>at</strong>al program abort occurs.12.1 A Protocol-Specific Packet HeaderProtocol developers will often wish to provide a specific header type to be used in packets. Doing so allows a new protocolimplement<strong>at</strong>ion to avoid overloading already-existing header fields. We co<strong>ns</strong>ider a simplified version of RTP as an example.<strong>The</strong> RTP header will require a sequence number fields <strong>and</strong> a source identifier field. <strong>The</strong> following classes cre<strong>at</strong>e the neededheader (see ~<strong>ns</strong>/rtp.h <strong>and</strong> ~<strong>ns</strong>/rtp.cc):From rtp.h:/* rtp packet. For now, just have srcid + seqno. */struct hdr_rtp {u_int32_t srcid_;int seqno_;/* per-field member functio<strong>ns</strong> */u_int32_t& srcid() { return (srcid_); }116


int& seqno() { return (seqno_); }};/* Packet header access functio<strong>ns</strong> */st<strong>at</strong>ic int offset_;inline st<strong>at</strong>ic int& offset() { return offset_; }inline st<strong>at</strong>ic hdr_rtp* access(co<strong>ns</strong>t Packet* p) {return (hdr_rtp*) p->access(offset_);}From rtp.cc:class RTPHeaderClass : public PacketHeaderClass {public:RTPHeaderClass() : PacketHeaderClass("PacketHeader/RTP",sizeof(hdr_rtp)) {bind_offset(&hdr_rtp::offset_);}} class_rtphdr;void RTPAgent::sendpkt(){Packet* p = allocpkt();hdr_rtp *rh = hdr_rtp::access(p);lastpkttime_ = Scheduler::i<strong>ns</strong>tance().clock();}/* Fill in srcid_ <strong>and</strong> seqno */rh->seqno() = seqno_++;rh->srcid() = session_->srcid();target_->recv(p, 0);RTPAgent::RTPAgent(): session_(0), lastpkttime_(-1e6){type_ = PT_RTP;bind("seqno_", &seqno_);}<strong>The</strong> first structure, hdr_rtp, defines the layout of the RTP packet header (in terms of words <strong>and</strong> their placement): whichfields are needed <strong>and</strong> how big they are. This structure definition is only used by the compiler to compute byte offsets offields; no objects of this structure type are ever directly alloc<strong>at</strong>ed. <strong>The</strong> structure also provides member functio<strong>ns</strong> which inturn provide a layer of d<strong>at</strong>a hiding for objects wishing to read or modify header fields of packets. Note th<strong>at</strong> the st<strong>at</strong>ic classvariable offset_ is used to find the byte offset <strong>at</strong> which the rtp header is loc<strong>at</strong>ed in an arbitrary <strong>ns</strong>packet. Two methodsare provided to utilize this variable to access this header in any packet: offset() <strong>and</strong> access(). <strong>The</strong> l<strong>at</strong>ter is wh<strong>at</strong>most users should choose to access this particular header in a packet; the former is used by the packet header managementclass <strong>and</strong> should seldom be used. For example, to access the RTP packet header in a packet pointed by p, one simply sayshdr_rtp::access(p). <strong>The</strong> actual binding of offset_ to the position of this header in a packet is done by routinesi<strong>ns</strong>ide ~<strong>ns</strong>/tcl/lib/<strong>ns</strong>-packet.tcl <strong>and</strong> ~<strong>ns</strong>/packet.cc. <strong>The</strong> co<strong>ns</strong>t in access()’s argument provides (presumably) read-onlyaccess to a co<strong>ns</strong>t Packet, lthough read-only is enforced since the return pointer is not co<strong>ns</strong>t. One correct way to do this isto provide two methods, one for write access, the other for read-only access. However, this is not currently implemented.IMPORTANT: Notice th<strong>at</strong> this is completely different from the original (<strong>and</strong> obsolete) method to access a packet header,which requires th<strong>at</strong> an integer variable, off_〈hdrname〉_, be defined for any packet header th<strong>at</strong> one needs to access. This117


method is now obsolete; its usage is tricky <strong>and</strong> its misuse can be very difficult to detect.<strong>The</strong> st<strong>at</strong>ic object class_rtphdr of class RTPHeaderClass is used to provide linkage to OTcl when the RTP headeris enabled <strong>at</strong> configur<strong>at</strong>ion time. When the simul<strong>at</strong>or executes, this st<strong>at</strong>ic object calls the PacketHeaderClass co<strong>ns</strong>tructorwith arguments "PacketHeader/RTP" <strong>and</strong> sizeof(hdr_rtp). This causes the size of the RTP header to be stored <strong>and</strong>made available to the packet header manager <strong>at</strong> configur<strong>at</strong>ion time (see below, Section 12.2.4). Notice th<strong>at</strong> bind_offset()MUST be called in the co<strong>ns</strong>tructor of this class, so th<strong>at</strong> the packet header manager knows where to store the offset for thisparticular packet header.<strong>The</strong> sample member function sendpkt() method of RTPAgent cre<strong>at</strong>es a new packet to send by calling allocpkt(),which h<strong>and</strong>les assignment of all the network-layer packet header fields (in this case, IP). Headers other than IP are h<strong>and</strong>ledsepar<strong>at</strong>ely. In this case, the agent uses the RTPHeader defined above. <strong>The</strong> Packet::access(void) member functionretur<strong>ns</strong> the address of the first byte in a buffer used to hold header inform<strong>at</strong>ion (see below). Its return value is cast as a pointerto the header of interest, after which member functio<strong>ns</strong> of the RTPHeader object are used to access individual fields.12.1.1 Adding a New Packet Header TypeAssuming we wish to cre<strong>at</strong>e a new header called newhdr the following steps are performed:1. cre<strong>at</strong>e a new structure defining the raw fields (called hdr_newhdr), define offset_ <strong>and</strong> access methods.2. define member functio<strong>ns</strong> for needed fields.3. cre<strong>at</strong>e a st<strong>at</strong>ic class to perform OTcl linkage (defines PacketHeader/Newhdr), do bind_offset() in its co<strong>ns</strong>tructor.4. edit ~<strong>ns</strong>/tcl/lib/<strong>ns</strong>-packet.tcl to enable new packet form<strong>at</strong> (see 12.2.2, 12.2.4).This is the recommended way to add your packet headers. If you do not follow this method, your simul<strong>at</strong>ion may still work,but it may behave in a unpredictable way when more protocols are added into your simul<strong>at</strong>ion. <strong>The</strong> reason is th<strong>at</strong> the BOB(Bag of Bits, Section 12.2.1) in <strong>ns</strong>packet is a large sparse space, assigning one wrong packet header offset may not triggerfailure immedi<strong>at</strong>ely.12.1.2 Selectively Including Packet Headers in Your Simul<strong>at</strong>ionBy default, <strong>ns</strong> includes ALL packet headers of ALL protocols in <strong>ns</strong> in EVERY packet in your simul<strong>at</strong>ion. This is a LOT ofoverhead, <strong>and</strong> will increase as more protocols are added into <strong>ns</strong>. For “packet-inte<strong>ns</strong>ive” simul<strong>at</strong>io<strong>ns</strong>, this could be a hugeoverhead. For i<strong>ns</strong>tance, as of now (Aug 30, 2000), the size of packet headers of all protocols in <strong>ns</strong> is about 1.9KB; however,if you turn on only the common header, the IP header <strong>and</strong> the TCP header, they add up to about 100 bytes. If you are doinglarge-scale web traffic simul<strong>at</strong>ion with many big f<strong>at</strong> pipes, reducing unused packet headers can lead to major memory saving.To include only the packet headers th<strong>at</strong> are of interest to you in your specific simul<strong>at</strong>ion, follow this p<strong>at</strong>tern (e.g., you want toremove AODV <strong>and</strong> ARP headers from your simul<strong>at</strong>ion):remove-packet-header AODV ARP......set <strong>ns</strong> [new Simul<strong>at</strong>or]Notice th<strong>at</strong> remove-packet-header MUST go before the simul<strong>at</strong>or is cre<strong>at</strong>ed. All packet header names are in the formsof PacketHeader/[hdr]. You only need to supply the [hdr] part, not the prefix. To find the names of packet headers,you may either look them up in ~<strong>ns</strong>/tcl/lib/<strong>ns</strong>-packet.tcl, or run the following simple comm<strong>and</strong>s in <strong>ns</strong>:118


foreach cl [PacketHeader info subclass] {puts $cl}To include only a specific set of headers in your simul<strong>at</strong>ion, e.g., IP <strong>and</strong> TCP, follow this p<strong>at</strong>tern:remove-all-packet-headersadd-packet-header IP TCP......set <strong>ns</strong> [new Simul<strong>at</strong>or]IMPORTANT: You MUST never remove common header from your simul<strong>at</strong>ion. As you can see in ~<strong>ns</strong>/tcl/lib/<strong>ns</strong>-packet.tcl,this is enforced by these header manipul<strong>at</strong>ion procs.Notice th<strong>at</strong> by default, all packet headers are included.12.2 Packet Classes<strong>The</strong>re are four C++ classes relevant to the h<strong>and</strong>ling of packets <strong>and</strong> packet headers in general: Packet, p_info PacketHeader,<strong>and</strong> PacketHeaderManager. <strong>The</strong> class Packet defines the type for all packets in the simul<strong>at</strong>ion; it is a subclass ofEvent so th<strong>at</strong> packets may be scheduled (e.g. for l<strong>at</strong>er arrival <strong>at</strong> some queue). <strong>The</strong> class packet_info holds all textrepresent<strong>at</strong>io<strong>ns</strong> for packet names. <strong>The</strong> class PacketHeader provides a base class for any packet header configured intothe simul<strong>at</strong>ion. It essentially provides enough internal st<strong>at</strong>e to loc<strong>at</strong>e any particular packet header in the collection of packetheaders present in any given packet. <strong>The</strong> class PacketHeaderManager defines a class used to collect <strong>and</strong> managecurrently-configured headers. It is invoked by a method available to OTcl <strong>at</strong> simul<strong>at</strong>ion configur<strong>at</strong>ion time to enable somesubset of the compiled-in packet headers.12.2.1 <strong>The</strong> Packet Class<strong>The</strong> class Packet defines the structure of a packet <strong>and</strong> provides member functio<strong>ns</strong> to h<strong>and</strong>le a free list for objects of this type.It is illustr<strong>at</strong>ed in Figure 12.1 <strong>and</strong> defined as follows in packet.h:class Packet : public Event {priv<strong>at</strong>e:friend class PacketQueue;u_char* bits_;u_char* d<strong>at</strong>a_; /* variable size buffer for ’d<strong>at</strong>a’ */u_int d<strong>at</strong>alen_; /* length of variable size buffer */protected:st<strong>at</strong>ic Packet* free_;public:Packet* next_; /* for queues <strong>and</strong> the free list */st<strong>at</strong>ic int hdrlen_;Packet() : bits_(0), d<strong>at</strong>alen_(0), next_(0) {}u_char* co<strong>ns</strong>t bits() { return (bits_); }Packet* copy() co<strong>ns</strong>t;st<strong>at</strong>ic Packet* alloc();119


Packethdrsize_next_bits()points to next packet in eitherfree list or in a PacketQueueaccessd<strong>at</strong>a()packet d<strong>at</strong>asize determined<strong>at</strong> compile timeip header bodySize Determined<strong>at</strong> Simul<strong>at</strong>or ConfigTime, stored in hdrsize_size determined<strong>at</strong> compile timesize determined<strong>at</strong> compile timesize determined<strong>at</strong> compile timetcp header bodyrtp header bodytrace header bodyFigure 12.1: A Packet Object};st<strong>at</strong>ic Packet* alloc(int);inline void allocd<strong>at</strong>a(int);st<strong>at</strong>ic void free(Packet*);inline u_char* access(int off) {if (off < 0)abort();return (&bits_[off]);}inline u_char* accessd<strong>at</strong>a() { return d<strong>at</strong>a_; }This class holds a pointer to a generic array of u<strong>ns</strong>igned characters (commonly called the “bag of bits” or BOB for short) wherepacket header fields are stored. It also holds a pointer to packet “d<strong>at</strong>a” (which is often not used in simul<strong>at</strong>io<strong>ns</strong>). <strong>The</strong> bits_variable contai<strong>ns</strong> the address of the first byte of the BOB. Effectively BOB is (currently implemented as) a conc<strong>at</strong>en<strong>at</strong>ion ofall the structures defined for each packet header (by convention, the structures with names beginning hdr_〈something〉)th<strong>at</strong> have been configured in. BOB generally remai<strong>ns</strong> a fixed size throughout a simul<strong>at</strong>ion, <strong>and</strong> the size is recorded in thePacket::hdrlen_ member variable. This size is upd<strong>at</strong>ed during simul<strong>at</strong>or configur<strong>at</strong>ion by OTcl 1 .<strong>The</strong> other methods of the class Packet are for cre<strong>at</strong>ing new packets <strong>and</strong> storing old (unused) ones on a priv<strong>at</strong>e free list. Suchalloc<strong>at</strong>ion <strong>and</strong> dealloc<strong>at</strong>ion is performed by the following code (in ~<strong>ns</strong>/packet.h):inline Packet* Packet::alloc(){Packet* p = free_;if (p != 0)free_ = p->next_;1 It is not intended to be upd<strong>at</strong>ed after configur<strong>at</strong>ion time. Doing so should be possible, but is currently untested.120


}else {p = new Packet;p->bits_ = new u_char[hdrsize_];if (p == 0 || p->bits_ == 0)abort();}return (p);/* alloc<strong>at</strong>e a packet with an n byte d<strong>at</strong>a buffer */inline Packet* Packet::alloc(int n){Packet* p = alloc();if (n > 0)p->allocd<strong>at</strong>a(n);return (p);}/* alloc<strong>at</strong>e an n byte d<strong>at</strong>a buffer to an existing packet */inline void Packet::allocd<strong>at</strong>a(int n){d<strong>at</strong>alen_ = n;d<strong>at</strong>a_ = new u_char[n];if (d<strong>at</strong>a_ == 0)abort();}inline void Packet::free(Packet* p){p->next_ = free_;free_ = p;if (p->d<strong>at</strong>alen_) {delete p->d<strong>at</strong>a_;p->d<strong>at</strong>alen_ = 0;}}inline Packet* Packet::copy() co<strong>ns</strong>t{Packet* p = alloc();memcpy(p->bits(), bits_, hdrlen_);if (d<strong>at</strong>alen_) {p->d<strong>at</strong>alen_ = d<strong>at</strong>alen_;p->d<strong>at</strong>a_ = new u_char[d<strong>at</strong>alen_];memcpy(p->d<strong>at</strong>a_, d<strong>at</strong>a_, d<strong>at</strong>alen_);}return (p);}<strong>The</strong> alloc() method is a support function commonly used to cre<strong>at</strong>e new packets. It is called by Agent::allocpkt()method on behalf of agents <strong>and</strong> is thus not normally invoked directly by most objects. It first <strong>at</strong>tempts to loc<strong>at</strong>e an old packeton the free list <strong>and</strong> if this fails alloc<strong>at</strong>es a new one using the C++ new oper<strong>at</strong>or. Note th<strong>at</strong> Packet class objects <strong>and</strong> BOBs arealloc<strong>at</strong>ed separ<strong>at</strong>ely. <strong>The</strong> free() method frees a packet by returning it to the free list. Note th<strong>at</strong> packets are never returned to121


the system’s memory alloc<strong>at</strong>or. I<strong>ns</strong>tead, they are stored on a free list when Packet::free() is called. <strong>The</strong> copy() membercre<strong>at</strong>es a new, identical copy of a packet with the exception of the uid_ field, which is unique. This function is used byReplic<strong>at</strong>or objects to support multicast distribution <strong>and</strong> LANs.12.2.2 p_info ClassThis class is used as a “glue” to bind numeric packet type values with their symbolic names. When a new packet type isdefined, its numeric code should be added to the enumer<strong>at</strong>ion packet_t (see ~<strong>ns</strong>/packet.h) 2 <strong>and</strong> its symbolic name shouldbe added to the co<strong>ns</strong>tructor of p_info:enum packet_t {PT_TCP,...PT_NTYPE // This MUST be the LAST one};class p_info {public:p_info() {name_[PT_TCP]= "tcp";...}}12.2.3 <strong>The</strong> hdr_cmn ClassEvery packet in the simul<strong>at</strong>or has a “common” header which is defined in ~<strong>ns</strong>/packet.h as follows:struct hdr_cmn {double ts_; /* timestamp: for q-delay measurement */packet_t ptype_; /* packet type (see above) */int uid_; /* unique id */int size_; /* simul<strong>at</strong>ed packet size */int iface_; /* receiving interface (label) *//* Packet header access functio<strong>ns</strong> */st<strong>at</strong>ic int offset_;inline st<strong>at</strong>ic int& offset() { return offset_; }inline st<strong>at</strong>ic hdr_cmn* access(Packet* p) {return (hdr_cmn*) p->access(offset_);}/* per-field member functio<strong>ns</strong> */int& ptype() { return (ptype_); }int& uid() { return (uid_); }int& size() { return (size_); }int& iface() { return (iface_); }2 Note: PT_NTYPE should remain the last element of this enumer<strong>at</strong>ion.122


};double& timestamp() { return (ts_); }This structure primarily defines fields used for tracing the flow of packets or measuring other quantities. <strong>The</strong> time stamp fieldis used to measure queuing delay <strong>at</strong> switch nodes. <strong>The</strong> ptype_ field is used to identify the type of packets, which makesreading traces simpler. <strong>The</strong> uid_ field is used by the scheduler in scheduling packet arrivals. <strong>The</strong> size_ field is of generaluse <strong>and</strong> gives the simul<strong>at</strong>ed packet’s size in bytes. Note th<strong>at</strong> the actual number of bytes co<strong>ns</strong>umed in the simul<strong>at</strong>ion may notrel<strong>at</strong>e to the value of this field (i.e., size_ has no rel<strong>at</strong>io<strong>ns</strong>hip to sizeof(struct hdr_cmn) or other <strong>ns</strong> structures).R<strong>at</strong>her, it is used most often in computing the time required for a packet to be delivered along a network link. As such itshould be set to the sum of the applic<strong>at</strong>ion d<strong>at</strong>a size <strong>and</strong> IP-, tra<strong>ns</strong>port-, <strong>and</strong> applic<strong>at</strong>ion-level headers for the simul<strong>at</strong>ed packet.<strong>The</strong> iface_ field is used by the simul<strong>at</strong>or when performing multicast distribution tree comput<strong>at</strong>io<strong>ns</strong>. It is a label indic<strong>at</strong>ing(typically) on which link a packet was received.12.2.4 <strong>The</strong> PacketHeaderManager ClassAn object of the class PacketHeaderManager is used to manage the set of currently-active packet header types <strong>and</strong>assign each of them unique offsets in the BOB. It is defined in both the C++ <strong>and</strong> OTcl code:From tcl/lib/<strong>ns</strong>-packet.tcl:PacketHeaderManager set hdrlen_ 0......foreach prot {AODVARPaSRMCommonCtrMcastDiffusion......TORAUMP} {add-packet-header $prot}Simul<strong>at</strong>or i<strong>ns</strong>tproc cre<strong>at</strong>e_packetform<strong>at</strong> {} {PacketHeaderManager i<strong>ns</strong>tvar tab_set pm [new PacketHeaderManager]foreach cl [PacketHeader info subclass] {if [info exists tab_($cl)] {set off [$pm allochdr $cl]$cl offset $off}}$self set packetManager_ $pm}PacketHeaderManager i<strong>ns</strong>tproc allochdr cl {set size [$cl set hdrlen_]$self i<strong>ns</strong>tvar hdrlen_set NS_ALIGN 8 ;# round up to nearest NS_ALIGN bytes, (needed on sparc/solaris)set incr [expr ($size + ($NS_ALIGN-1)) & ~($NS_ALIGN-1)]set base $hdrlen_123


}incr hdrlen_ $incrreturn $baseFrom packet.cc:/* manages active packet header types */class PacketHeaderManager : public TclObject {public:PacketHeaderManager() {bind("hdrlen_", &Packet::hdrlen_);}};<strong>The</strong> code in ~<strong>ns</strong>/tcl/lib/<strong>ns</strong>-packet.tcl is executed when the simul<strong>at</strong>or initializes. Thus, the foreach st<strong>at</strong>ement is executedbefore the simul<strong>at</strong>ion begi<strong>ns</strong>, <strong>and</strong> initializes the OTcl class array tab_ to contain the mapping between class the name <strong>and</strong>the names of the currently active packet header classes. As discussed above (12.1), packet headers should be accessed usinghdr_〈hdrname〉::access().<strong>The</strong> cre<strong>at</strong>e_packetform<strong>at</strong>{} i<strong>ns</strong>tance procedure is part of the basic Simul<strong>at</strong>or class <strong>and</strong> is called one time during simul<strong>at</strong>orconfigur<strong>at</strong>ion. It first cre<strong>at</strong>es a single PacketHeaderManager object. <strong>The</strong> C++ co<strong>ns</strong>tructor links the OTcl i<strong>ns</strong>tancevariable hdrlen_ (of class PacketHeaderManager) to the C++ variable Packet::hdrlen_ (a st<strong>at</strong>ic member of thePacket class). This has the effect of setting Packet::hdrlen_ to zero. Note th<strong>at</strong> binding across class types in thisfashion is unusual.After cre<strong>at</strong>ing the packet manager, the foreach loop enables each of the packet headers of interest. This loop iter<strong>at</strong>esthrough the list of defined packet headers of the form (h i , o i ) where h i is the name of the ith header <strong>and</strong> o i is the name of thevariable containing the loc<strong>at</strong>ion of the h i header in BOB. <strong>The</strong> placement of headers is performed by the allochdr i<strong>ns</strong>tprocof the PacketHeaderManager OTcl class. <strong>The</strong> procedure keeps a running variable hdrlen_ with the current length ofBOB as new packet headers are enabled. It also arranges for 8-byte alignment for any newly-enabled packet header. Thisis needed to e<strong>ns</strong>ure th<strong>at</strong> when double-world length quantities are used in packet headers on machines where double-wordalignment is required, access faults are not produced. 3 .12.3 Comm<strong>and</strong>s <strong>at</strong> a glanceFollowing is a list of packet-header rel<strong>at</strong>ed procedures:Simul<strong>at</strong>or::cre<strong>at</strong>e_packetform<strong>at</strong>This is an internal simul<strong>at</strong>or procedure <strong>and</strong> is called once during the simul<strong>at</strong>or configur<strong>at</strong>ion to setup apacketHeaderManager object.PacketHeaderManager::allochdrThis is another internal procedure of Class PacketHeaderManager th<strong>at</strong> keeps track of a variable called hdrlen_ as newpacket-headers are enabled. It also allows 8-byte allignment for any newly-enabled pkt header.add-packet-header takes a list of arguments, each of which is a packet header name (without PacketHeader/prefix). This global proc will tell simul<strong>at</strong>or to include the specified packet header(s) in your simul<strong>at</strong>ion.3 In some processer architectures, including the Sparc <strong>and</strong> HP-PA, double-word access must be performed on a double-word boundary (i.e. addressesending in 0 mod 8). Attempting to perform unaligned accesses result in an abnormal program termin<strong>at</strong>ion.124


emove-packet-header oper<strong>at</strong>es in the same syntax, but it removes the specified headers from your simul<strong>at</strong>ion; noticeth<strong>at</strong> it does not remove the common header even it is i<strong>ns</strong>tructed to do so.remove-all-packet-headers is a global Tcl proc. It takes no argument <strong>and</strong> removes all packet headers, except thecommon header, from your simul<strong>at</strong>ion. add-all-packet-headers is its counterpart.125


Chapter 13Error ModelThis chapter describes the implement<strong>at</strong>ion <strong>and</strong> configur<strong>at</strong>ion of error models, which introduces packet losses into a simul<strong>at</strong>ion.In addition to the basic class ErrorModel described in details below, there are several other types of error modules not beingcompletely documented yet, which include:• SRMErrorModel, PGMErrorModel: error model for SRM <strong>and</strong> PGM.• ErrorModel/Trace: error model th<strong>at</strong> reads a loss trace (i<strong>ns</strong>tead of a m<strong>at</strong>h/computed model)• MrouteErrorModel: error model for multicast routing, now inherits from trace.• ErrorModel/Periodic: models periodic packet drops (drop every nth packet we see). This model can be convenientlycombined with a flow-based classifier to achieve drops in particular flows• SelectErrorModel: for Selective packet drop.• ErrorModel/TwoSt<strong>at</strong>e: Two-St<strong>at</strong>e: error-free <strong>and</strong> error• ErrorModel/TwoSt<strong>at</strong>eMarkov, ErrorModel/Expo, ErrorModel/Empirical: inerit from ErrorModel/TwoSt<strong>at</strong>e.• ErrorModel/List: specify a list of packets/bytes to drop, which could be in any order.<strong>The</strong>ir definitio<strong>ns</strong> can be found in ~<strong>ns</strong>/queue/errmodel.{cc, h} <strong>and</strong> ~<strong>ns</strong>/tcl/lib/<strong>ns</strong>-errmodel.tcl, <strong>ns</strong>-default.tcl.13.1 Implement<strong>at</strong>ion<strong>The</strong> procedures <strong>and</strong> functio<strong>ns</strong> described in this section can be found in ~<strong>ns</strong>/errmodel.{cc, h}.Error model simul<strong>at</strong>es link-level errors or loss by either marking the packet’s error flag or dumping the packet to a droptarget. In simul<strong>at</strong>io<strong>ns</strong>, errors can be gener<strong>at</strong>ed from a simple model such as the packet error r<strong>at</strong>e, or from more complic<strong>at</strong>edst<strong>at</strong>istical <strong>and</strong> empirical models. To support a wide variety of models, the unit of error can be specified in term of packet, bits,or time-based.<strong>The</strong> ErrorModel class is derived from the Connector base class. As the result, it inherits some methods for hooking upobjects such as target <strong>and</strong> drop-target. If the drop target exists, it will received corrupted packets from ErrorModel.126


Otherwise, ErrorModel just marks the error_ flag of the packet’s common header, thereby, allowing agents to h<strong>and</strong>lethe loss. <strong>The</strong> ErrorModel also defines additional Tcl method unit to specify the unit of error <strong>and</strong> ranvar to specify ther<strong>and</strong>om variable for gener<strong>at</strong>ing errors. If not specified, the unit of error will be in packets, <strong>and</strong> the r<strong>and</strong>om variable will beuniform distributed from 0 to 1. Below is a simple example of cre<strong>at</strong>ing an error model with the packet error r<strong>at</strong>e of 1 percent(0.01):# cre<strong>at</strong>e a loss_module <strong>and</strong> set its packet error r<strong>at</strong>e to 1 percentset loss_module [new ErrorModel]$loss_module set r<strong>at</strong>e_ 0.01# optional: set the unit <strong>and</strong> r<strong>and</strong>om variable$loss_module unit pkt$loss_module ranvar [new R<strong>and</strong>omVariable/Uniform];# error unit: packets (the default)# set target for dropped packets$loss_module drop-target [new Agent/Null]In C++, the ErrorModel contai<strong>ns</strong> both the mechanism <strong>and</strong> policy for dropping packets. <strong>The</strong> packet dropping mechanismis h<strong>and</strong>led by the recv method, <strong>and</strong> packet corrupting policy is h<strong>and</strong>led by the corrupt method.enum ErrorUnit { EU_PKT=0, EU_BIT, EU_TIME };class ErrorModel : public Connector {public:ErrorModel();void recv(Packet*, H<strong>and</strong>ler*);virtual int corrupt(Packet*);inline double r<strong>at</strong>e() { return r<strong>at</strong>e_; }protected:int comm<strong>and</strong>(int argc, co<strong>ns</strong>t char*co<strong>ns</strong>t* argv);ErrorUnit eu_; /* error unit in pkt, bit, or time */R<strong>and</strong>omVariable* ranvar_;double r<strong>at</strong>e_;};<strong>The</strong> ErrorModel only implements a simple policy based on a single error r<strong>at</strong>e, either in packets of bits. More sophistic<strong>at</strong>eddropping policy can be implemented in C++ by deriving from ErrorModel <strong>and</strong> redefining its corrupt method.13.2 Configur<strong>at</strong>ion<strong>The</strong> previous section talked about error model, in this section we discuss how to use error models in <strong>ns</strong> over either wirednetworks or wireless ones.To use an error model for wired networks, <strong>at</strong> first it has to be i<strong>ns</strong>erted into a SimpleLink object. Because a SimpleLink is acomposite object (Chapter 6), an error model can be i<strong>ns</strong>erted to many places. Currently we provide the following methods toi<strong>ns</strong>ert an error module into three different places.• I<strong>ns</strong>ert an error module in a SimpleLink BEFORE the queue module. This is provided by the following two OTclmethods:127


SimpleLink::errormodule argsSimul<strong>at</strong>or::lossmodel 〈em〉 〈src〉 〈dst〉When an error model is given as a parameter, it i<strong>ns</strong>erts the error module intothe simple link, right after the queue module, <strong>and</strong> set the drop-target of the errormodel to be the drop trace object of the simple link. Note th<strong>at</strong> this requiresthe following configur<strong>at</strong>ion order: <strong>ns</strong> namtrace-all followed by link configur<strong>at</strong>io<strong>ns</strong>,followed by error model i<strong>ns</strong>ertion. When no argument is given, itretur<strong>ns</strong> the current error model in the link, if there’s any. This method is definedin <strong>ns</strong>/tcl/lib/<strong>ns</strong>-link.tclCall SimpleLink::errormodule to i<strong>ns</strong>ert the given error module into the simplelink (src, dst). It’s simply a wrapper for the above method. This method is definedin <strong>ns</strong>/tcl/lib/<strong>ns</strong>-lib.tcl.• I<strong>ns</strong>ert an error module in a SimpleLink AFTER the queue but BEFORE the delay link. This is provided by the followingtwo methods:SimpleLink::i<strong>ns</strong>ert-linkloss args This method’s behavior is identical to th<strong>at</strong> ofSimpleLink::errormodule, except th<strong>at</strong> it i<strong>ns</strong>erts an error moduleimmedi<strong>at</strong>ely after the queue object. It’s defined in <strong>ns</strong>/tcl/lib/<strong>ns</strong>-link.tclSimul<strong>at</strong>or::link-lossmodel 〈em〉 〈src〉 〈dst〉 This is a wrapper for SimpleLink::i<strong>ns</strong>ert-linkloss. It’s definedin <strong>ns</strong>/tcl/lib/<strong>ns</strong>-lib.tcl<strong>The</strong> nam traces gener<strong>at</strong>ed by error models i<strong>ns</strong>erted using these two methods do not require special tre<strong>at</strong>ment <strong>and</strong> canbe visualized using an older version of nam.• I<strong>ns</strong>ert an error module in a Link AFTER the delay link module. This can be done by Link::i<strong>ns</strong>tall-error.Currently this API doesn’t produce any trace. It only serves as a placeholder for possible future exte<strong>ns</strong>io<strong>ns</strong>.To add an error model over wireless networks, each node can i<strong>ns</strong>ert a given st<strong>at</strong>istical error model either over outgoing orincoming wireless channels. Precisely, the i<strong>ns</strong>tanci<strong>at</strong>ed error model would be stuck between mac <strong>and</strong> netif modules depictedin Figure 16.2. For the outgoing link, the error module would be pointed by downtarget_ of the above mac module while forthe incoming link it would be linked by uptaget_ pointer of the below netif module. And in each case the target_ of the errormodule points to either the netif or the mac respectively. <strong>The</strong> difference of placing over the two different loc<strong>at</strong>io<strong>ns</strong> is th<strong>at</strong> theoutgoing causes all the receivers to receive the packet suffering the same degree of errors since the error is determined beforewireless channel module copies the packet. On the other h<strong>and</strong>, the incoming error module lets each receiver get the packetcorrupted with different degree of error since the error is independently computed in each error module.<strong>The</strong> i<strong>ns</strong>ertion into the wireless protocol stack can be done by calling node-config comm<strong>and</strong> explained in Section ?? with thetwo optio<strong>ns</strong> IncomingErrrProc <strong>and</strong> OutgoingErrProc. We can use these two optio<strong>ns</strong> <strong>at</strong> the same time or each one separ<strong>at</strong>ely.<strong>The</strong> argument of the two option is the name of the global procedure which cre<strong>at</strong>es an error model object, feeds it withnecessary initial values appropri<strong>at</strong>e for the new error module, <strong>and</strong> finally retur<strong>ns</strong> the object pointer. <strong>The</strong> following shows asimple TCL example script to add an error module into the wireless protocol stack.$<strong>ns</strong> node-config -IncomingErrProc UniformErr -OutgoingErrProc UniformErrproc UniformErrset err [new ErrorModel]$err unit packetreturn $err13.3 Multi-st<strong>at</strong>e error modelContributed by Jianping Pan (jpan@bbcr.uw<strong>at</strong>erloo.ca).128


<strong>The</strong> multi-st<strong>at</strong>e error model implements time-based error st<strong>at</strong>e tra<strong>ns</strong>itio<strong>ns</strong>. Tra<strong>ns</strong>itio<strong>ns</strong> to the next error st<strong>at</strong>e occur <strong>at</strong> the endof the dur<strong>at</strong>ion of the current st<strong>at</strong>e. <strong>The</strong> next error st<strong>at</strong>e is then selected using the tra<strong>ns</strong>ition st<strong>at</strong>e m<strong>at</strong>rix.To cre<strong>at</strong>e a multi-st<strong>at</strong>e error model, the following parameters should be supplied (as defined in <strong>ns</strong>/tcl/lib/<strong>ns</strong>-errmodel.tcl):• st<strong>at</strong>es: an array of st<strong>at</strong>es (error models).• periods: an array of st<strong>at</strong>e dur<strong>at</strong>io<strong>ns</strong>.• tra<strong>ns</strong>: the tra<strong>ns</strong>ition st<strong>at</strong>e model m<strong>at</strong>rix.• tra<strong>ns</strong>unit: one of [pkt|byte|time].• sttype: type of st<strong>at</strong>e tra<strong>ns</strong>itio<strong>ns</strong> to use: either time or pkt.• <strong>ns</strong>t<strong>at</strong>es: number of st<strong>at</strong>es.• start: the start st<strong>at</strong>e.Here is a simple example script to cre<strong>at</strong>e a multi-st<strong>at</strong>e error model:set tmp [new ErrorModel/Uniform 0 pkt]set tmp1 [new ErrorModel/Uniform .9 pkt]set tmp2 [new ErrorModel/Uniform .5 pkt]# Array of st<strong>at</strong>es (error models)set m_st<strong>at</strong>es [list $tmp $tmp1 $tmp2]# Dur<strong>at</strong>io<strong>ns</strong> for each of the st<strong>at</strong>es, tmp, tmp1 <strong>and</strong> tmp2, respectivelyset m_periods [list 0 .0075 .00375]# Tra<strong>ns</strong>ition st<strong>at</strong>e model m<strong>at</strong>rixset m_tra<strong>ns</strong>mx { {0.95 0.05 0}{0 0 1}{1 0 0} }set m_trunit pkt# Use time-based tra<strong>ns</strong>itio<strong>ns</strong>et m_sttype timeset m_<strong>ns</strong>t<strong>at</strong>es 3set m_<strong>ns</strong>tart [lindex $m_st<strong>at</strong>es 0]set em [new ErrorModel/MultiSt<strong>at</strong>e $m_st<strong>at</strong>es $m_periods $m_tra<strong>ns</strong>mx$m_trunit $m_sttype $m_<strong>ns</strong>t<strong>at</strong>es $m_<strong>ns</strong>tart]13.4 Comm<strong>and</strong>s <strong>at</strong> a glance<strong>The</strong> following is a list of error-model rel<strong>at</strong>ed comm<strong>and</strong>s commonly used in simul<strong>at</strong>ion scripts:set em [new ErrorModel]$em unit pkt$em set r<strong>at</strong>e_ 0.02$em ranvar [new R<strong>and</strong>omVariable/Uniform]$em drop-target [new Agent/Null]129


This is a simple example of how to cre<strong>at</strong>e <strong>and</strong> configure an error model. <strong>The</strong> comm<strong>and</strong>s to place the error-model in a simplelink will be shown next.$simplelink errormodule This comm<strong>and</strong>s i<strong>ns</strong>erts the error-model before the queue object in simple link. However in this case the error-model’sdrop-target points to the link’s drophead_ element.$<strong>ns</strong>_ lossmodel This comm<strong>and</strong> places the error-model before the queue in a simplelink defined by the <strong>and</strong> nodes. This isbasically a wrapper for the above method.$simplelink i<strong>ns</strong>ert-linkloss This i<strong>ns</strong>erts a loss-module after the queue, but right before the delay link_ element in the simple link. This is because namcan visualize a packet drop only if the packet is on the link or in the queue. <strong>The</strong> error-module’s drop-target points to thelink’s drophead_ element.$<strong>ns</strong>_ link-lossmodel This too is a wrapper method for i<strong>ns</strong>ert-linkloss method described above. Th<strong>at</strong> is this i<strong>ns</strong>erts the error-module right after thequeue element in a simple link (src-dst).130


Chapter 14Local Area Networks<strong>The</strong> characteristics of the wireless <strong>and</strong> local area networks (LAN) are inherently different from those of point-to-point links.A network co<strong>ns</strong>isting of multiple point-to-point links cannot capture the sharing <strong>and</strong> contention properties of a LAN. Tosimul<strong>at</strong>e these properties, we cre<strong>at</strong>ed a new type of a Node, called LanNode. <strong>The</strong> OTcl configur<strong>at</strong>io<strong>ns</strong> <strong>and</strong> interfaces forLanNode reside in the following two files in the main <strong>ns</strong> directory:tcl/lan/vlan.tcltcl/lan/<strong>ns</strong>-ll.tcltcl/lan/<strong>ns</strong>-mac.tcl14.1 Tcl configur<strong>at</strong>ion<strong>The</strong> interface for cre<strong>at</strong>ing <strong>and</strong> configuring a LAN slightly differs from those of point-to-point link. At the top level, theOTcl class Simul<strong>at</strong>or exports a new method called make-lan. <strong>The</strong> parameters to this method are similar to the methodduplex-link, except th<strong>at</strong> make-lan only accepts a list of nodes as a single parameter i<strong>ns</strong>tead of 2 parameters as induplex-link:Simul<strong>at</strong>or i<strong>ns</strong>tproc make-lan {nodes bw delay lltype ifqtype mactype chantype}<strong>The</strong> optional parameters to make-lan specify the type of objects to be cre<strong>at</strong>ed for the link layer (LL), the interface queue,the MAC layer (Mac), <strong>and</strong> the physical layer (Channel). Below is an example of how a new CSMA/CD (Ethernet) LAN iscre<strong>at</strong>ed.Example:$<strong>ns</strong> make-lan "$n1 $n2" $bw $delay LL Queue/DropTail Mac/Csma/Cdcre<strong>at</strong>es a LAN with basic link-layer, drop-tail queue, <strong>and</strong> CSMA/CD MAC.131


Higher LayersNode 1Node 2. . .Node NLink LayerQueueQueue. . .QueueLLLLLLMac LayerMacMac. . .MacPhysical LayerChannelClassifier/Mac14.2 Components of a LANFigure 14.1: Connectivity within a LANLanLink captures the functionality of the three lowest layers in the network stack:1. Link Layer (LL)2. Medium Access Control (MAC) Layer3. Physical (PHY) LayerFigure 14.1 illustr<strong>at</strong>es the extended network stack th<strong>at</strong> makes simul<strong>at</strong>io<strong>ns</strong> of local area network possible in <strong>ns</strong>. A packet sentdown the stack flows through the link layer (Queue <strong>and</strong> LL), the MAC layer (Mac), <strong>and</strong> the physical layer (Channel toClassifier/Mac). <strong>The</strong> packet then makes its way up the stack through the Mac, <strong>and</strong> the LL.At the bottom of the stack, the physical layer is composed of two simul<strong>at</strong>ion objects: the Channel <strong>and</strong> Classifier/Mac.<strong>The</strong> Channel object simul<strong>at</strong>es the shared medium <strong>and</strong> supports the medium access mechanisms of the MAC objects on thesending side of the tra<strong>ns</strong>mission. On the receiving side, the Classifier/Mac is respo<strong>ns</strong>ible for delivering <strong>and</strong> optionallyreplic<strong>at</strong>ing packets to the receiving MAC objects.Depending on the type of physical layer, the MAC layer must contain a certain set of functionalities such as: carrier se<strong>ns</strong>e,collision detection, collision avoidance, etc. Since these functionalities affect both the sending <strong>and</strong> receiving sides, they are132


implemented in a single Mac object. For sending, the Mac object must follow a certain medium access protocol beforetra<strong>ns</strong>mitting the packet on the channel. For receiving, the MAC layer is respo<strong>ns</strong>ible for delivering the packet to the link layer.Above the MAC layer, the link layer can potentially have many functionalities such as queuing <strong>and</strong> link-level retra<strong>ns</strong>mission.<strong>The</strong> need of having a wide variety of link-level schemes leads to the division of functionality into two components: Queue<strong>and</strong> LL (link-layer). <strong>The</strong> Queue object, simul<strong>at</strong>ing the interface queue, belongs to the same Queue class th<strong>at</strong> is describedin Chapter 7. <strong>The</strong> LL object implements a particular d<strong>at</strong>a link protocol, such as ARQ. By combining both the sending <strong>and</strong>receiving functionalities into one module, the LL object can also support other mechanisms such as piggybacking.14.3 Channel Class<strong>The</strong> Channel class simul<strong>at</strong>es the actual tra<strong>ns</strong>mission of the packet <strong>at</strong> the physical layer. <strong>The</strong> basic Channel implementsa shared medium with support for contention mechanisms. It allows the MAC to carry out carrier se<strong>ns</strong>e, contention, <strong>and</strong>collision detection. If more than one tra<strong>ns</strong>missio<strong>ns</strong> overlaps in time, a channel raises the collision flag. By checking this flag,the MAC object can implement collision detection <strong>and</strong> h<strong>and</strong>ling.Since the tra<strong>ns</strong>mission time is a function of the number of bits in the packet <strong>and</strong> the modul<strong>at</strong>ion speed of each individualinterface (MAC), the Channel object only sets its busy signal for the dur<strong>at</strong>ion requested by the MAC object. It alsoschedules the packets to be delivered to the destin<strong>at</strong>ion MAC objects after the tra<strong>ns</strong>mission time plus the propag<strong>at</strong>ion delay.14.3.1 Channel St<strong>at</strong>e<strong>The</strong> C++ class Channel includes enough internal st<strong>at</strong>e to schedule packet delivery <strong>and</strong> detect collisio<strong>ns</strong>. It exports thefollowing OTcl configur<strong>at</strong>ion parameter:delay_propag<strong>at</strong>ion delay on the channel14.3.2 Example: Channel <strong>and</strong> classifier of the physical layerset channel_ [new Channel]$channel_ set delay_ 4us# propag<strong>at</strong>ion delayset mcl_ [new Classifier/Mac]$channel_ target $mcl_$mcl_ i<strong>ns</strong>tall $mac_DA $recv_iface. . .14.3.3 Channel Class in C++In C++, the class Channel extends the Connector object with several new methods to support a variety of MAC protocols.<strong>The</strong> class is defined as follow in ~<strong>ns</strong>/channel.h:class Channel : public Connector {public:Channel();133


};void recv(Packet* p, H<strong>and</strong>ler*);virtual int send(Packet* p, double txtime);virtual void contention(Packet*, H<strong>and</strong>ler*);int hold(double txtime);virtual int collision() { return numtx_ > 1; }virtual double txstop() { return txstop_; }. . .<strong>The</strong> important methods of the class Channel are:• txstop() method retur<strong>ns</strong> the time when the channel will become idle, which can be used by the MAC to implementcarrier se<strong>ns</strong>e.• contention() method allows the MAC to contend for the channel before sending a packet. <strong>The</strong> channel then usethis packet to signal the corresponding Mac object <strong>at</strong> the end of each contention period.• collision() method indic<strong>at</strong>es whether a collision occurs during the contention period. When the Channel signalthe end of the contention period, the MAC can use the collision() method to detect collision.• send() method allows the MAC object to tra<strong>ns</strong>mit a packet on the channel for a specified dur<strong>at</strong>ion of time.• hold() method allows the MAC object to hold the channel for a specified dur<strong>at</strong>ion of time without actually tra<strong>ns</strong>mittingany packets. This is useful in simul<strong>at</strong>ing the jamming mechanism of some MAC protocols.14.4 MacClassifier Class<strong>The</strong> MacClassifier class extends the Classifier class to implement a simple broadcasting mechanism. It modifiesthe recv() method in the following way: since the replic<strong>at</strong>ion of a packet is expe<strong>ns</strong>ive, normally a unicast packet willbe classified by the MAC destin<strong>at</strong>ion address macDA_ <strong>and</strong> delivered directly to the MAC object with such an address.However, if the destin<strong>at</strong>ion object cannot be found or if the MAC destin<strong>at</strong>ion address is explicitly set to the broadcast addressBCAST_ADDR, the packet will be replic<strong>at</strong>ed <strong>and</strong> sent to all MACs on the lan excluding the one th<strong>at</strong> is the source of the packet.Finally, by setting the bound variable MacClassifier::bcast_ to a non–zero value, will cause MacClassifieralways to replic<strong>at</strong>e packets.class MacClassifier : public Classifier {public:void recv(Packet*, H<strong>and</strong>ler*);};void MacClassifier::recv(Packet* p, H<strong>and</strong>ler*){Mac* mac;hdr_mac* mh = hdr_mac::access(p);}if (bcast_ || mh->macDA() == BCAST_ADDR || (mac = (Mac *)find(p)) == 0) {// Replic<strong>at</strong>e packets to all slots (broadcast). . .return;}mac->recv(p);134


14.5 MAC Class<strong>The</strong> Mac object simul<strong>at</strong>es the medium access protocols th<strong>at</strong> are necessary in the shared medium environment such as thewireless <strong>and</strong> local area networks. Since the sending <strong>and</strong> receiving mechanisms are tightly coupled in most types of MAClayers, it is essential for the Mac object to be duplex.On the sending side, the Mac object is respo<strong>ns</strong>ible for adding the MAC header <strong>and</strong> tra<strong>ns</strong>mitting the packet onto the channel.On the receiving side, the Mac object asynchronously receives packets from the classifier of the physical layer. After MACprotocol processing, it passes the d<strong>at</strong>a packet to the link layer.14.5.1 Mac St<strong>at</strong>e<strong>The</strong> C++ class Mac class contai<strong>ns</strong> enough internal st<strong>at</strong>e to simul<strong>at</strong>e the particular MAC protocol. It also exports thefollowing OTcl configur<strong>at</strong>ion parameter:b<strong>and</strong>width_hlen_label_modul<strong>at</strong>ion r<strong>at</strong>e of the MACadditional bytes added to packet for MAC headerMAC address14.5.2 Mac Methods<strong>The</strong> class Mac class added several Tcl methods for configur<strong>at</strong>ion, in particular, linking with other simul<strong>at</strong>ion objects:channelclassifiermaclistspecify the channel for tra<strong>ns</strong>missionthe classifier th<strong>at</strong> deliver packets to receiving MACa link list of MAC interfaces on the same node14.5.3 Mac Class in C++In C++, the Mac class derives from Connector. When the recv() method gets a packet, it identifies the direction ofthe packet based on the presence of a callback h<strong>and</strong>ler. If there is a callback h<strong>and</strong>ler, the packet is outgoing, otherwise, it isincoming.class Mac : public Connector {public:Mac();virtual void recv(Packet* p, H<strong>and</strong>ler* h);virtual void send(Packet* p);virtual void resume(Packet* p = 0);. . .};When a Mac object receives a packet via its recv() method, it checks whether the packet is outgoing or incoming. Foran outgoing packet, it assumes th<strong>at</strong> the link-layer of the sender has obtained the destin<strong>at</strong>ion MAC address <strong>and</strong> filled in themacDA_ field of the MAC header, hdr_mac. <strong>The</strong> Mac object fills in the rest of the MAC header with the source MAC address135


<strong>and</strong> the frame type. It then passes the packet to its send() method, which carries out the medium access protocol. For thebasic Mac object, the send method calls txtime() to compute the tra<strong>ns</strong>mission time, then invokes Channel::send totra<strong>ns</strong>mit the packet. Finally, it schedules itself to resume after the tra<strong>ns</strong>mission time has elapsed.For an incoming packet, the MAC object does its protocol processing <strong>and</strong> passes the packet to the link-layer.14.5.4 CSMA-based MAC<strong>The</strong> class CsmaMac extends the Mac class with new methods th<strong>at</strong> implements carrier se<strong>ns</strong>e <strong>and</strong> backoff mechanisms.<strong>The</strong> CsmaMac::send() method detects when the channel becomes idle using Channel::txtime(). If the channelis busy, the MAC schedules the next carrier se<strong>ns</strong>e <strong>at</strong> the moment the channel tur<strong>ns</strong> idle. Once the channel is idle,the CsmaMac object initi<strong>at</strong>es the contention period with Channel::contention(). At the end of the contention period,the endofContention() method is invoked. At this time, the basic CsmaMac just tra<strong>ns</strong>mits the packet usingChannel::send.class CsmaMac : public Mac {public:CsmaMac();void send(Packet* p);void resume(Packet* p = 0);virtual void endofContention(Packet* p);virtual void backoff(H<strong>and</strong>ler* h, Packet* p, double delay=0);. . .};class CsmaCdMac : public CsmaMac {public:CsmaCdMac();void endofContention(Packet*);};class CsmaCaMac : public CsmaMac {public:CsmaCaMac();virtual void send(Packet*);};<strong>The</strong> CsmaCdMac extends CsmaMac to carry out collision detection procedure of the CSMA/CD (Ethernet) protocol. Whenthe channel signals the end of contention period, the endofContention method checks for collision using the Channel::collision(method. If there is a collision, the MAC invokes its backoff method to schedule the next carrier se<strong>ns</strong>e to retra<strong>ns</strong>mit thepacket.<strong>The</strong> CsmaCaMac extends the send method of CsmaMac to carry out the collision avoidance (CSMA/CA) procedure. I<strong>ns</strong>teadof tra<strong>ns</strong>mitting immedi<strong>at</strong>ely when the channel is idle, the CsmaCaMac object backs off a r<strong>and</strong>om number of slots, thentra<strong>ns</strong>mits if the channel remai<strong>ns</strong> idle until the end of the backoff period.136


14.6 LL (link-layer) Class<strong>The</strong> link-layer object is respo<strong>ns</strong>ible for simul<strong>at</strong>ing the d<strong>at</strong>a link protocols. Many protocols can be implemented within thislayer such as packet fragment<strong>at</strong>ion <strong>and</strong> reassembly, <strong>and</strong> reliable link protocol.Another important function of the link layer is setting the MAC destin<strong>at</strong>ion address in the MAC header of the packet. In thecurrent implement<strong>at</strong>ion this task involves two separ<strong>at</strong>e issues: finding the next–hop–node’s IP address (routing) <strong>and</strong> resolvingthis IP address into the correct MAC address (ARP). For simplicity, the default mapping between MAC <strong>and</strong> IP addresses isone–to–one, which mea<strong>ns</strong> th<strong>at</strong> IP addresses are re–used <strong>at</strong> the MAC layer.14.6.1 LL Class in C++<strong>The</strong> C++ class LL derives from the LinkDelay class. Since it is a duplex object, it keeps a separ<strong>at</strong>e pointer for the sendtarget, sendtarget, <strong>and</strong> the receive target, recvtarget. It also defines the methods recvfrom() <strong>and</strong> sendto() toh<strong>and</strong>le the incoming <strong>and</strong> outgoing packets respectively.class LL : public LinkDelay {public:LL();virtual void recv(Packet* p, H<strong>and</strong>ler* h);virtual Packet* sendto(Packet* p, H<strong>and</strong>ler* h = 0);virtual Packet* recvfrom(Packet* p);inline int seqno() return seqno_;inline int ackno() return ackno_;inline int macDA() return macDA_;inline Queue *ifq() return ifq_;inline NsObject* sendtarget() return sendtarget_;inline NsObject* recvtarget() return recvtarget_;protected:int comm<strong>and</strong>(int argc, co<strong>ns</strong>t char*co<strong>ns</strong>t* argv);void h<strong>and</strong>le(Event* e) recv((Packet*)e, 0);inline virtual int arp (int ip_addr) return ip_addr;int seqno_; // link-layer sequence numberint ackno_; // ACK received so farint macDA_; // destin<strong>at</strong>ion MAC addressQueue* ifq_; // interface queueNsObject* sendtarget_; // for outgoing packetNsObject* recvtarget_; // for incoming packet};LanRouter* lanrouter_; // for lookups of the next hop14.6.2 Example: Link Layer configur<strong>at</strong>io<strong>ns</strong>et ll_ [new LL]set ifq_ [new Queue/DropTail]$ll_ lanrouter [new LanRouter $<strong>ns</strong> $lan] # LanRouter is one object137


$ll_ set delay_ $delay$ll_ set b<strong>and</strong>width_ $bw$ll_ sendtarget $mac$ll_ recvtarget $iif. . .# per LAN# link-level overhead# b<strong>and</strong>width# interface queue <strong>at</strong> the sender side# input interface of the receiver14.7 LanRouterclassBy default, there is just one LanRouter object per LAN, which is cre<strong>at</strong>ed when a new LanNode is initialized. For everynode on the LAN, the link layer object (LL) has a pointer to the LanRouter, so it is able to find the next hop for the packetth<strong>at</strong> is sent on the LAN:Packet* LL::sendto(Packet* p, H<strong>and</strong>ler* h){int nh = (lanrouter_) ? lanrouter_->next_hop(p) : -1;. . .}LanRouter is able to find the next hop by querying the current RouteLogic:int LanRouter::next_hop(Packet *p) {int next_hopIP;if (enableHrouting_) {routelogic_->lookup_hier(lanaddr_, adst, next_hopIP);} else {routelogic_->lookup_fl<strong>at</strong>(lanaddr_, adst, next_hopIP);}One limit<strong>at</strong>ion of this is th<strong>at</strong> RouteLogic may not be aware of dynamic changes to the routing. But it is always possible toderive a new class from LanRouter so th<strong>at</strong> to re–define its next_hop method to h<strong>and</strong>le dynamic changes appopri<strong>at</strong>ely.14.8 Other ComponentsIn addition to the C++ components described above, simul<strong>at</strong>ing local area networks also requires a number of existing componentsin <strong>ns</strong> such as Classifier, Queue, <strong>and</strong> Trace, networkinterface, etc. Configuring these objects requiresknowledge of wh<strong>at</strong> the user wants to simul<strong>at</strong>e. <strong>The</strong> default configur<strong>at</strong>ion is implemented in the two Tcl files mentioned <strong>at</strong> thebeginning of this chapter. To obtain more realistic simul<strong>at</strong>io<strong>ns</strong> of wireless networks, one can use the ErrorModel describedin Chapter 13.14.9 LANs <strong>and</strong> <strong>ns</strong> routingWhen a LAN is cre<strong>at</strong>ed using either make-lan or newLan, a “virtual LAN node” LanNode is cre<strong>at</strong>ed. LanNode keepstogether all shared objects on the LAN: Channel, Classifier/Mac, <strong>and</strong> LanRouter. <strong>The</strong>n for each node on the LAN,138


a LanIface object is cre<strong>at</strong>ed. LanIface contai<strong>ns</strong> all other objects th<strong>at</strong> are needed on the per–node basis: a Queue, a linklayer (LL), Mac, etc. It should be emphasized th<strong>at</strong> LanNode is a node only for routing algorithms: Node <strong>and</strong> LanNodehave very little in common. One of few things th<strong>at</strong> they share is an identifier taken from the Node ID–space. If hierarchicalrouting is used, LanNode has to be assigned a hierarchical address just like any other node. From the point of view of <strong>ns</strong>(st<strong>at</strong>ic) routing, LanNode is just another node connected to every node on the LAN. Links connecting the LanNode withn1n2n1n2LANLANn3n4n3n4Figure 14.2: Actual LAN configur<strong>at</strong>ion (left) <strong>and</strong> as seen by <strong>ns</strong> routing (right)the nodes on the LAN are also “virtual” (Vlink). <strong>The</strong> default routing cost of such a link is 1/2, so the cost of traversing twoVlinks (e.g. n1 → LAN → n2) is counted as just one hop.Most important method of Vlink is the one th<strong>at</strong> gives the head of the link:Vlink i<strong>ns</strong>tproc head {} {$self i<strong>ns</strong>tvar lan_ dst_ src_if {$src_ == [$lan_ set id_]} {# if this is a link FROM the lan vnode,# it doesn’t m<strong>at</strong>ter wh<strong>at</strong> we return, because# it’s only used by $lan add-route (empty)return ""} else {# if this is a link TO the lan vnode,# return the entry to the lanIface objectset src_lif [$lan_ set lanIface_($src_)]return [$src_lif entry]}}This method is used by st<strong>at</strong>ic (default) routing to i<strong>ns</strong>tall correct routes <strong>at</strong> a node (see Simul<strong>at</strong>or methodscompute-fl<strong>at</strong>-routes <strong>and</strong> compute-hier-routes in tcl/lib/<strong>ns</strong>-route.tcl, as well as Node methodsadd-route <strong>and</strong> add-hroute in tcl/lib/<strong>ns</strong>-node.tcl).From the code fragment above it can be seen th<strong>at</strong> it retur<strong>ns</strong> LAN interface of the node as a head of the link to be i<strong>ns</strong>talled inthe appropri<strong>at</strong>e classifier.Thus, Vlink does not impose any delay on the packet <strong>and</strong> serves the only purpose to i<strong>ns</strong>tall LAN interfaces i<strong>ns</strong>tead of normallinks <strong>at</strong> nodes’ classifiers.Note, th<strong>at</strong> this design allows to have nodes connected by parallel LANs, while in the current implement<strong>at</strong>ion it is impossibleto have nodes connected by parallel simple links <strong>and</strong> use them both (the array Simul<strong>at</strong>or i<strong>ns</strong>tvar link_ holds thelink object for each connected pair of source <strong>and</strong> destin<strong>at</strong>ion, <strong>and</strong> it can be only one object per source/destin<strong>at</strong>ion pair).139


14.10 Comm<strong>and</strong>s <strong>at</strong> a glance<strong>The</strong> following is a list of lan rel<strong>at</strong>ed comm<strong>and</strong>s commonly used in simul<strong>at</strong>ion scripts:$<strong>ns</strong>_ make-lan Cre<strong>at</strong>es a lan from a set of nodes given by . B<strong>and</strong>width, delay characteristics along with the link-layer, Interfacequeue, Mac layer <strong>and</strong> channel type for the lan also needs to be defined. Default values used are as follows: .. LL.. Queue/DropTail.. Mac.. Channel <strong>and</strong>.. Phy/WiredPhy$<strong>ns</strong>_ newLan This comm<strong>and</strong> cre<strong>at</strong>es a lan similar to make-lan described above. But this comm<strong>and</strong> can be used for finer control whereasmake-lan is a more convinient <strong>and</strong> easier comm<strong>and</strong>. For example newLan maybe used to cre<strong>at</strong>e a lan with hierarchicaladdresses. See <strong>ns</strong>/tcl/ex/vlantest-hier.tcl, vlantest-mcst.tcl, lantest.tcl, mac-test.tcl for usage of newLan. <strong>The</strong> possibleargument types th<strong>at</strong> can be passed are LL, ifq, MAC, channel, phy <strong>and</strong> address.$lannode cost This assig<strong>ns</strong> a cost of c/2 to each of the (uni-directional) links in the lan.$lannode cost?Retur<strong>ns</strong> the cost of (bi-directional) links in the lan, i.e c.Internal procedures :$lannode addNode Lan is implemented as a virtual node. <strong>The</strong> LanNode mimics a real node <strong>and</strong> uses an address (id) from node’s address space.This comm<strong>and</strong> adds a list of to the lan represented by lannode. <strong>The</strong> b<strong>and</strong>width, delay <strong>and</strong> network characteristics ofnodes are given by the above arguments. This is an internal comm<strong>and</strong> used by make-lan <strong>and</strong> newLan.$lannode idRetur<strong>ns</strong> the virtual node’s id.$lannode node-addrRetur<strong>ns</strong> virtual nodes’s address.$lannode dump-namconfigThis comm<strong>and</strong> cre<strong>at</strong>es a given lan layout in nam. This function may be changed to redefine the lan layout in a different way.$lannode is-lan?This comm<strong>and</strong> always retur<strong>ns</strong> 1, since the node here is a virtual node representing a lan. <strong>The</strong> corresponding comm<strong>and</strong> forbase class Node $node is-lan? always retur<strong>ns</strong> a 0.140


Chapter 15<strong>The</strong> (Revised) Addressing Structure in NSThis chapter describes the internals of the revised addressing form<strong>at</strong> implemented in <strong>ns</strong>. <strong>The</strong> chapter co<strong>ns</strong>ists of five sectio<strong>ns</strong>.We describe the APIs th<strong>at</strong> can be used for alloc<strong>at</strong>ing bits to the <strong>ns</strong> addressing structure. <strong>The</strong> address space as describedin chapter 3, can be thought of a contiguous field of n bits, where n may vary as per the address requirement of the simul<strong>at</strong>ion.<strong>The</strong> default value of n is 16 (as defined by MAXADDRSIZE_). <strong>The</strong> maximum value of n is set to 32 (defined asMAXADDRSIZE_). <strong>The</strong>se default <strong>and</strong> maximum address sizes are defined in ~<strong>ns</strong>//tcl/lib/<strong>ns</strong>-default.tcl.<strong>The</strong> address space co<strong>ns</strong>ists of 2 parts, the node-id <strong>and</strong> the port-id. <strong>The</strong> higher bits are assigned as the node’s address or id_<strong>and</strong> remaining lower bits are assigned to form port-id or the identific<strong>at</strong>ion of the agent <strong>at</strong>tached to the node. Of the higherbits, 1 bit is assigned for multicast. <strong>The</strong> address space co<strong>ns</strong>ists of 32 bits <strong>and</strong> port id space co<strong>ns</strong>ists of 32 bits as well. <strong>The</strong>higher 32 bits for node-id, the MSB for multicast <strong>and</strong> the lower 32 bits for port-id. Additionally, the address space mayalso be set in hierarchical form<strong>at</strong>, co<strong>ns</strong>isting of multiple levels of addressing hierarchy. We shall be describing the APIs forsetting address structure in different form<strong>at</strong>s as described above as well as exp<strong>and</strong>ing the address space. <strong>The</strong> procedures <strong>and</strong>functio<strong>ns</strong> described in this chapter can be found in ~<strong>ns</strong>/tcl/lib/<strong>ns</strong>-address.tcl, address.cc <strong>and</strong> address.h.15.1 <strong>The</strong> Default Address Form<strong>at</strong><strong>The</strong> default settings alloc<strong>at</strong>es 32 lower bits for port-id, 1 higher bit for mcast <strong>and</strong> the rest 32 higher bits for node-id. <strong>The</strong>procedure to set the address form<strong>at</strong> in default mode is called during initialis<strong>at</strong>ion of the simul<strong>at</strong>or as:# <strong>The</strong> preambleset <strong>ns</strong> [new Simul<strong>at</strong>or];# initialise the simul<strong>at</strong>ionIt can also be called explicitly set as:$<strong>ns</strong> set-address-form<strong>at</strong> def15.2 <strong>The</strong> Hierarchical Address Form<strong>at</strong><strong>The</strong>re are two optio<strong>ns</strong> for setting an address to hierarchical form<strong>at</strong>, the default <strong>and</strong> the specified.141


15.2.1 Default Hierarchical Setting<strong>The</strong> default hierarchical node-id co<strong>ns</strong>ists of 3 levels with (10 11 11) bits in the three levels. <strong>The</strong> hierarchical configur<strong>at</strong>ionmay be invoked as follows:$<strong>ns</strong> set-address-form<strong>at</strong> hierarchicalThis sets :* 32 bits for port-id, * 32 bits for node-id assigned in - 3 levels of hierarchy - (10 11 11) bits for the three levels.- or (9 11 11) if multicast is enabled.15.2.2 Specific Hierarchical Setting<strong>The</strong> second option allows a hierarchical address to be set with specified number of levels with number of bits assigned foreach level. <strong>The</strong> API would be as the following:$<strong>ns</strong> set-address-form<strong>at</strong> hierarchical ....An example configur<strong>at</strong>ion would be:$<strong>ns</strong> set-address-form<strong>at</strong> hierarchical 2 8 15where 2 levels of hierarchy is specified, assigning 8 bits for the 1st level <strong>and</strong> 15 bits for the second.15.3 <strong>The</strong> Exp<strong>and</strong>ed Node-Address Form<strong>at</strong>NOTE: Please note th<strong>at</strong> this comm<strong>and</strong> is now obsolete given th<strong>at</strong> node address <strong>and</strong> port address spaces are 32 bits wide.On the event of requirement of more bits to the address space, the exp<strong>and</strong>ed address API may be used as:$<strong>ns</strong> set-address-form<strong>at</strong> exp<strong>and</strong>edThis exp<strong>and</strong>s the address space to 30 bits, alloc<strong>at</strong>ing 22 higher bits to node-id <strong>and</strong> lower 8 bits to port-id.15.4 Exp<strong>and</strong>ing port-id fieldNOTE: Please note th<strong>at</strong> this comm<strong>and</strong> is now obsolete given th<strong>at</strong> node address <strong>and</strong> port address spaces are 32 bits wide.This primitive may be used in case of need to exp<strong>and</strong> portid in the event of requirement to <strong>at</strong>tach a large number of agentsto the nodes. This may be used in conjunction with set-addres-form<strong>at</strong> comm<strong>and</strong> (with different optio<strong>ns</strong>) explained above.Synopsis for this comm<strong>and</strong> shall be:exp<strong>and</strong>-port-field-bits exp<strong>and</strong>-port-field-bits checks <strong>and</strong> raises error in the following if the requested portsize cannot be accomod<strong>at</strong>ed (i.e if sufficientnum.of free bits are not available) or if requested portsize is less than or equal to the existing portsize.142


15.5 Errors in setting address form<strong>at</strong>Errors are returned for both set-address-form<strong>at</strong> <strong>and</strong> exp<strong>and</strong>-port-field-bits primitives in the following cases:* if number of bits specified is less than 0. * if bit positio<strong>ns</strong> clash (contiguous number of requested free bits not *found). * if total number of bits exceed MAXADDRSIZE_. * if exp<strong>and</strong>-port-field-bits is <strong>at</strong>tempted with portbitsless than or * equal to the existing portsize. * if number of hierarchy levels donot m<strong>at</strong>ch with number of bits *specified (for each level).15.6 Comm<strong>and</strong>s <strong>at</strong> a glance<strong>The</strong> following is a list of address-form<strong>at</strong> rel<strong>at</strong>ed comm<strong>and</strong>s used in simul<strong>at</strong>ion scripts:$<strong>ns</strong>_ set-address-form<strong>at</strong> defThis comm<strong>and</strong> is used internally to set the address form<strong>at</strong> to its default value of 32 lower bits for port-id, 1 higher bit formcast <strong>and</strong> the rest 31 higher bits for node-id. However this API has been replaced by the new node API$<strong>ns</strong>_ node-config -addressType fl<strong>at</strong>.$<strong>ns</strong>_ set-address-form<strong>at</strong> hierarchicalThis comm<strong>and</strong> is used to set the address form<strong>at</strong> to the hierarchical configur<strong>at</strong>ion th<strong>at</strong> co<strong>ns</strong>ists of 3 levels with 8bits assignedto each level <strong>and</strong> 32 lower bits for port-id. However this API has been replaced by the new node API$<strong>ns</strong>_ node-config -addressType hierarchical.$<strong>ns</strong>_ set-address-form<strong>at</strong> hierarchical This comm<strong>and</strong> is used to set the address form<strong>at</strong> to a specific hierarchical setting. <strong>The</strong> indic<strong>at</strong>e the number of levelsof hierarchy in the addressing structure, while the args define number of bits for each level. An example would be $<strong>ns</strong>_set-address-form<strong>at</strong> hierachical 3 4 4 16 , where 4, 4 <strong>and</strong> 16 defines the number of bits to be used for theaddress space in level 1 , 2 <strong>and</strong> 3 respectively.$<strong>ns</strong>_ set-address-form<strong>at</strong> exp<strong>and</strong>edTHIS COMMAND IS NOW OBSOLETE This comm<strong>and</strong> was used to exp<strong>and</strong> the address space to 30 bits, alloc<strong>at</strong>ing 22higher bits for node-id <strong>and</strong> lower 8 bits for port-id. However this comm<strong>and</strong> is obsoleted now by 32 bit addressing, i.enode-id field is 32 bit wide.exp<strong>and</strong>-port-field-bits THIS COMMAND IS NOW OBSOLETE Similar to the comm<strong>and</strong> above, this was used to exp<strong>and</strong> the address space for theport-id field to number of bits. However this comm<strong>and</strong> is obsolete now th<strong>at</strong> the ports are 32 bit wide.143


Chapter 16Mobile Networking in <strong>ns</strong>This chapter describes the wireless model th<strong>at</strong> was originally ported as CMU’s Monarch group’s mobility exte<strong>ns</strong>ion to <strong>ns</strong>.This chapter co<strong>ns</strong>ists of two sectio<strong>ns</strong> <strong>and</strong> several subsectio<strong>ns</strong>. <strong>The</strong> first section covers the original mobility model ported fromCMU/Monarch group. In this section, we cover the internals of a mobilenode, routing mechanisms <strong>and</strong> network componentsth<strong>at</strong> are used to co<strong>ns</strong>truct the network stack for a mobilenode. <strong>The</strong> components th<strong>at</strong> are covered briefly are Channel, Networkinterface,Radio propag<strong>at</strong>ion model, MAC protocols, Interface Queue, Link layer <strong>and</strong> Address resolution protocol model(ARP). CMU trace support <strong>and</strong> Gener<strong>at</strong>ion of node movement <strong>and</strong> traffic scenario files are also covered in this section. <strong>The</strong>original CMU model allows simul<strong>at</strong>ion of pure wireless LANs or multihop ad-hoc networks. Further exte<strong>ns</strong>io<strong>ns</strong> were made tothis model to allow combined simul<strong>at</strong>ion of wired <strong>and</strong> wireless networks. MobileIP was also extended to the wireless model.<strong>The</strong>se are discussed in the second section of this chapter.16.1 <strong>The</strong> basic wireless model in <strong>ns</strong><strong>The</strong> wireless model essentially co<strong>ns</strong>ists of the MobileNode <strong>at</strong> the core,with additional supporting fe<strong>at</strong>ures th<strong>at</strong> allows simul<strong>at</strong>io<strong>ns</strong>of multi-hop ad-hoc networks, wireless LANs etc. <strong>The</strong> MobileNode object is a split object. <strong>The</strong> C++ classMobileNode is derived from parent class Node. Refer to Chapter 5 for details on Node. A MobileNode thus is thebasic Node object with added functionalities of a wireless <strong>and</strong> mobile node like ability to move within a given topology,ability to receive <strong>and</strong> tra<strong>ns</strong>mit signals to <strong>and</strong> from a wireless channel etc. A major difference between them, though, is th<strong>at</strong>a MobileNode is not connected by mea<strong>ns</strong> of Links to other nodes or mobilenodes. In this section we shall describe theinternals of MobileNode, its routing mechanisms, the routing protocols dsdv, aodv, tora <strong>and</strong> dsr, cre<strong>at</strong>ion of network stackallowing channel access in MobileNode, brief description of each stack component, trace support <strong>and</strong> movement/trafficscenario gener<strong>at</strong>ion for wireless simul<strong>at</strong>io<strong>ns</strong>.16.1.1 Mobilenode: cre<strong>at</strong>ing wireless topologyMobileNode is the basic <strong>ns</strong>Node object with added functionalities like movement, ability to tra<strong>ns</strong>mit <strong>and</strong> receive on a channelth<strong>at</strong> allows it to be used to cre<strong>at</strong>e mobile, wireless simul<strong>at</strong>ion environments. <strong>The</strong> class MobileNode is derived from thebase class Node. MobileNode is a split object. <strong>The</strong> mobility fe<strong>at</strong>ures including node movement, periodic position upd<strong>at</strong>es,maintaining topology boundary etc are implemented in C++ while plumbing of network components within MobileNodeitself (like classifiers, dmux , LL, Mac, Channel etc) have been implemented in Otcl. <strong>The</strong> functio<strong>ns</strong> <strong>and</strong> procedures describedin this subsection can be found in ~<strong>ns</strong>/mobilenode.{cc,h}, ~<strong>ns</strong>/tcl/lib/<strong>ns</strong>-mobilenode.tcl, ~<strong>ns</strong>/tcl/mobility/dsdv.tcl,~<strong>ns</strong>/tcl/mobility/dsr.tcl, ~<strong>ns</strong>/tcl/mobility/tora.tcl. Example scripts can be found in ~<strong>ns</strong>/tcl/ex/wireless-test.tcl <strong>and</strong> ~<strong>ns</strong>/tcl/ex/wireless.tcl.144


While the first example uses a small topology of 3 nodes, the second example ru<strong>ns</strong> over a topology of 50 nodes. <strong>The</strong>se scriptscan be run simply by typing$<strong>ns</strong> tcl/ex/wireless.tcl (or /wireless-test.tcl)<strong>The</strong> four ad-hoc routing protocols th<strong>at</strong> are currently supported are Destin<strong>at</strong>ion Sequence Distance Vector (DSDV), DynamicSource Routing (DSR), Temporally ordered Routing Algorithm (TORA) <strong>and</strong> Adhoc On-dem<strong>and</strong> Distance Vector (AODV).<strong>The</strong> primitive to cre<strong>at</strong>e a mobilenode is described below. Please note th<strong>at</strong> the old APIs for cre<strong>at</strong>ing a mobilenode dependedon which routing protocol was used, likeset mnode [$opt(rp)-cre<strong>at</strong>e-mobile-node $id]where$opt(rp)defines "dsdv", "aodv", "tora" or "dsr" <strong>and</strong> id is the index for the mobilenode. But the old API’s use is being deprec<strong>at</strong>ed <strong>and</strong>the new API is described as follows:.$<strong>ns</strong>_ node-config -adhocRouting $opt(adhocRouting)-llType $opt(ll)-macType $opt(mac)-ifqType $opt(ifq)-ifqLen $opt(ifqlen)-antType $opt(ant)-propI<strong>ns</strong>tance [new $opt(prop)]-phyType $opt(netif)-channel [new $opt(chan)]-topoI<strong>ns</strong>tance $topo-wiredRouting OFF-agentTrace ON-routerTrace OFF-macTrace OFF<strong>The</strong> above API configures for a mobilenode with all the given values of adhoc-routing protocol, network stack, channel,topography,propag<strong>at</strong>ion model, with wired routing turned on or off (required for wired-cum-wireless scenarios) <strong>and</strong>tracing turned on or off <strong>at</strong> different levels (router, mac, agent). Incase hierarchical addressing is being used, the hier addressof the node needs to be passed as well. For more info about this comm<strong>and</strong> (part of new node APIs) see chapter titled"Restructuring <strong>ns</strong> node <strong>and</strong> new Node APIs" in <strong>ns</strong> <strong>Notes</strong> <strong>and</strong> <strong>Document<strong>at</strong>ion</strong>.Next actually cre<strong>at</strong>e the mobilenodes as follows:for { set j 0 } { $j < $opt(nn)} {incr j} {set node_($j) [ $<strong>ns</strong>_ node ]$node_($i) r<strong>and</strong>om-motion 0 ;# disable r<strong>and</strong>om motion}<strong>The</strong> above procedure cre<strong>at</strong>es a mobilenode (split)object, cre<strong>at</strong>es an adhoc-routing routing agent as specified, cre<strong>at</strong>es thenetwork stack co<strong>ns</strong>isting of a link layer, interface queue, mac layer, <strong>and</strong> a network interface with an antenna, uses the defined145


entry_addrdemuxIP addressdefaulttarget_portdemux255Src/SinkRTagent(DSDV)uptarget_LLtarget_arptable_ARPdowntarget_IFqdowntarget_mac_MACuptarget_downtarget_uptarget_RadioPropag<strong>at</strong>ionModelpropag<strong>at</strong>ion_NetIFchannel_uptarget_ChannelFigure 16.1: Schem<strong>at</strong>ic of a mobilenode under the CMU monarch’s wireless exte<strong>ns</strong>io<strong>ns</strong> to <strong>ns</strong>propag<strong>at</strong>ion model, interconnects these components <strong>and</strong> connects the stack to the channel. <strong>The</strong> mobilenode now looks likethe schem<strong>at</strong>ic in Figure 16.1.<strong>The</strong> mobilenode structure used for DSR routing is slightly different from the mobilenode described above. <strong>The</strong> class SRNodeis derived from class MobileNode. SRNode doesnot use address demux or classifiers <strong>and</strong> all packets received by the node146


portdemuxSrc/Sinkentry_DSRtarget_ll_uptarget_LLll_(0)arptable_ARPdowntarget_IFqdowntarget_MACuptarget_downtarget_uptarget_RadioPropag<strong>at</strong>ionModelpropag<strong>at</strong>ion_NetIFchannel_uptarget_ChannelFigure 16.2: Schem<strong>at</strong>ic of a SRNode under the CMU monarch’s wireless exte<strong>ns</strong>io<strong>ns</strong> to <strong>ns</strong>are h<strong>and</strong>ed dow n to the DSR routing agent by default. <strong>The</strong> DSR routing agent either receives pkts for itself by h<strong>and</strong>ing itover to the port dmux or forwards pkts as per source routes in the pkt hdr or sends out route requests <strong>and</strong> route replies forfresh packets. Details on DSR routing agent may be found in section 16.1.5. <strong>The</strong> schem<strong>at</strong>ic model for a SRNode is shown inFigure 16.2.147


16.1.2 Cre<strong>at</strong>ing Node movements<strong>The</strong> mobilenode is designed to move in a three dime<strong>ns</strong>ional topology. However the third dime<strong>ns</strong>ion (Z) is not used. Th<strong>at</strong> isthe mobilenode is assumed to move always on a fl<strong>at</strong> terrain with Z always equal to 0. Thus the mobilenode has X, Y, Z(=0)co-ordin<strong>at</strong>es th<strong>at</strong> is continually adjusted as the node moves. <strong>The</strong>re are two mechanisms to induce movement in mobilenodes.In the first method, starting position of the node <strong>and</strong> its future destin<strong>at</strong>io<strong>ns</strong> may be set explicitly. <strong>The</strong>se directives are normallyincluded in a separ<strong>at</strong>e movement scenario file.<strong>The</strong> start-position <strong>and</strong> future destin<strong>at</strong>io<strong>ns</strong> for a mobilenode may be set by using the following APIs:$node set X_ $node set Y_ $node set Z_ $<strong>ns</strong> <strong>at</strong> $time $node setdest At $time sec, the node would start moving from its initial position of (x1,y1) towards a destin<strong>at</strong>ion (x2,y2) <strong>at</strong> the definedspeed.In this method the node-movement-upd<strong>at</strong>es are triggered whenever the position of the node <strong>at</strong> a given time is required to beknown. This may be triggered by a query from a neighbouring node seeking to know the distance between them, or the setdestdirective described above th<strong>at</strong> changes the direction <strong>and</strong> speed of the node.An example of a movement scenario file using the above APIs, can be found in ~<strong>ns</strong>/tcl/mobility/scene/scen-670x670-50-600-20-0. Here 670x670 defines the length <strong>and</strong> width of the topology with 50 nodes moving <strong>at</strong> a maximum speed of 20m/s withaverage pause time of 600s. <strong>The</strong>se node movement files may be gener<strong>at</strong>ed using CMU’s scenario gener<strong>at</strong>or to be found under~<strong>ns</strong>/indep-utils/cmu-scen-gen/setdest. See subsection 16.1.8 for details on gener<strong>at</strong>ion of node movement scenarios.<strong>The</strong> second method employs r<strong>and</strong>om movement of the node. <strong>The</strong> primitive to be used is:$mobilenode startwhich starts the mobilenode with a r<strong>and</strong>om position <strong>and</strong> have routined upd<strong>at</strong>es to change the direction <strong>and</strong> speed of the node.<strong>The</strong> destin<strong>at</strong>ion <strong>and</strong> speed values are gener<strong>at</strong>ed in a r<strong>and</strong>om fashion. We have not used the second method <strong>and</strong> leave it to theuser to explore the details. <strong>The</strong> mobilenode movement is implemented in C++. See methods in ~<strong>ns</strong>/mobilenode.{cc.h} forthe implement<strong>at</strong>ional details.Irrespective of the methods used to gener<strong>at</strong>e node movement, the topography for mobilenodes needs to be defined. It should bedefined before cre<strong>at</strong>ing mobilenodes. Normally fl<strong>at</strong> topology is cre<strong>at</strong>ed by specifying the length <strong>and</strong> width of the topographyusing the following primitive:set topo [new Topography]$topo load_fl<strong>at</strong>grid $opt(x) $opt(y)where opt(x) <strong>and</strong> opt(y) are the boundaries used in simul<strong>at</strong>ion.<strong>The</strong> movement of mobilenodes may be logged by using a procedure like the following:proc log-movement {} {148


global logtimer <strong>ns</strong>_ <strong>ns</strong>set <strong>ns</strong> $<strong>ns</strong>_source ../mobility/timer.tclClass LogTimer -superclass TimerLogTimer i<strong>ns</strong>tproc timeout {} {global opt node_;for {set i 0} {$i < $opt(nn)} {incr i} {$node_($i) log-movement}$self sched 0.1}}set logtimer [new LogTimer]$logtimer sched 0.1In this case, mobilenode positio<strong>ns</strong> would be logged every 0.1 sec.16.1.3 Network Components in a mobilenode<strong>The</strong> network stack for a mobilenode co<strong>ns</strong>ists of a link layer(LL), an ARP module connected to LL, an interface priorityqueue(IFq), a mac layer(MAC), a network interface(netIF), all connected to the channel. <strong>The</strong>se network components arecre<strong>at</strong>ed <strong>and</strong> plumbed together in OTcl. <strong>The</strong> relevant MobileNode method add-interface() in ~<strong>ns</strong>/tcl/lib/<strong>ns</strong>-mobilenode.tcl isshown below:## <strong>The</strong> following setups up link layer, mac layer, network interface# <strong>and</strong> physical layer structures for the mobile node.#Node/MobileNode i<strong>ns</strong>tproc add-interface { channel pmodellltype mactype qtype qlen iftype anttype } {$self i<strong>ns</strong>tvar arptable_ nifs_$self i<strong>ns</strong>tvar netif_ mac_ ifq_ ll_global <strong>ns</strong>_ MacTrace optset t $nifs_incr nifs_set netif_($t) [new $iftype] ;# net-interfaceset mac_($t) [new $mactype] ;# mac layerset ifq_($t) [new $qtype] ;# interface queueset ll_($t) [new $lltype] ;# link layerset ant_($t) [new $anttype]## Local Variables#set nullAgent_ [$<strong>ns</strong>_ set nullAgent_]149


set netif $netif_($t)set mac $mac_($t)set ifq $ifq_($t)set ll $ll_($t)## Initialize ARP table only once.#if { $arptable_ == "" } {set arptable_ [new ARPTable $self $mac]set drpT [cmu-trace Drop "IFQ" $self]$arptable_ drop-target $drpT}## Link Layer#$ll arptable $arptable_$ll mac $mac$ll up-target [$self entry]$ll down-target $ifq## Interface Queue#$ifq target $mac$ifq set qlim_ $qle<strong>ns</strong>et drpT [cmu-trace Drop "IFQ" $self]$ifq drop-target $drpT## Mac Layer#$mac netif $netif$mac up-target $ll$mac down-target $netif$mac nodes $opt(nn)## Network Interface#$netif channel $channel$netif up-target $mac$netif propag<strong>at</strong>ion $pmodel$netif node $self$netif antenna $ant_($t)## Physical Channel#$channel addif $netif;# Propag<strong>at</strong>ion Model;# Bind node interface;# <strong>at</strong>tach antenna;# add to list of interfaces# ============================================================# Setting up trace objects150


if { $MacTrace == "ON" } {## Trace RTS/CTS/ACK Packets#set rcvT [cmu-trace Recv "MAC" $self]$mac log-target $rcvT## Trace Sent Packets#set sndT [cmu-trace Send "MAC" $self]$sndT target [$mac sendtarget]$mac sendtarget $sndT## Trace Received Packets#set rcvT [cmu-trace Recv "MAC" $self]$rcvT target [$mac recvtarget]$mac recvtarget $rcvT## Trace Dropped Packets#set drpT [cmu-trace Drop "MAC" $self]$mac drop-target $drpT} else {$mac log-target [$<strong>ns</strong>_ set nullAgent_]$mac drop-target [$<strong>ns</strong>_ set nullAgent_]}# ============================================================}$self addif $netif<strong>The</strong> plumbing in the above method cre<strong>at</strong>es the network stack we see in Figure 16.1.Each component is briefly described here. Hopefully more detailed docuent<strong>at</strong>ion from CMU shall be available in the future.Link Layer <strong>The</strong> LL used by mobilenode is same as described in Chapter 14. <strong>The</strong> only difference being the link layer formobilenode, has an ARP module connected to it which resolves all IP to hardware (Mac) address conversio<strong>ns</strong>. Normallyfor all outgoing (into the channel) packets, the packets are h<strong>and</strong>ed down to the LL by the Routing Agent. <strong>The</strong> LL h<strong>and</strong>sdown packets to the interface queue. For all incoming packets (out of the channel), the mac layer h<strong>and</strong>s up packets tothe LL which is then h<strong>and</strong>ed off <strong>at</strong> the node_entry_ point. <strong>The</strong> class LL is implemented in ~<strong>ns</strong>/ll.{cc,h} <strong>and</strong>~<strong>ns</strong>/tcl/lan/<strong>ns</strong>-ll.tcl.ARP <strong>The</strong> Address Resolution Protocol (implemented in BSD style) module receives queries from Link layer. If ARP hasthe hardware address for destin<strong>at</strong>ion, it writes it into the mac header of the packet. Otherwise it broadcasts an ARPquery, <strong>and</strong> caches the packet temporarily. For each unknown destin<strong>at</strong>ion hardware address, there is a buffer for a singlepacket. Incase additional packets to the same destin<strong>at</strong>ion is sent to ARP, the earlier buffered packet is dropped. Once151


the hardware address of a packet’s next hop is known, the packet is i<strong>ns</strong>erted into the interface queue. <strong>The</strong> classARPTable is implemented in ~<strong>ns</strong>/arp.{cc,h} <strong>and</strong> ~<strong>ns</strong>/tcl/lib/<strong>ns</strong>-mobilenode.tcl.Interface Queue <strong>The</strong> class PriQueue is implemented as a priority queue which gives priority to routing rotocol packets,i<strong>ns</strong>erting them <strong>at</strong> the head of the queue. It supports running a filter over all packets in the queue <strong>and</strong> removes those witha specified destin<strong>at</strong>ion address. See ~<strong>ns</strong>/priqueue.{cc,h} for interface queue implement<strong>at</strong>ion.Mac Layer <strong>The</strong> IEEE 802.11 distributed coordin<strong>at</strong>ion function (DCF) Mac protocol has been implemented by CMU. It usesa RTS/CTS/DATA/ACK p<strong>at</strong>tern for all unicast packets <strong>and</strong> simply sends out DATA for all broadcast packets. <strong>The</strong>implement<strong>at</strong>ion uses both physical <strong>and</strong> virtual carrier se<strong>ns</strong>e. <strong>The</strong> class Mac802_11 is implemented in ~<strong>ns</strong>/mac-802_11.{cc,h}.Tap Agents Agents th<strong>at</strong> subclass themselves as class Tap defined in mac.h can register themselves with the mac objectusing method i<strong>ns</strong>tallTap(). If the particular Mac protocol permits it, the tap will promiscuously be given all packetsreceived by the mac layer, before address filtering is done. See ~<strong>ns</strong>/mac.{cc,h} for class Tapmplement<strong>at</strong>ion.Network Interfaces <strong>The</strong> Network Interphase layer serves as a hardware interface which is used by mobilenode to access thechannel. <strong>The</strong> wireless shared media interface is implemented as class Phy/WirelessPhy. This interface subjectto collisio<strong>ns</strong> <strong>and</strong> the radio propag<strong>at</strong>ion model receives packets tra<strong>ns</strong>mitted by other node interfaces to the channel. <strong>The</strong>interface stamps each tra<strong>ns</strong>mitted packet with the meta-d<strong>at</strong>a rel<strong>at</strong>ed to the tra<strong>ns</strong>mitting interface like the tra<strong>ns</strong>missionpower, wavelength etc. This meta-d<strong>at</strong>a in pkt header is used by the propag<strong>at</strong>ion model in receiving network interfaceto determine if the packet has minimum power to be received <strong>and</strong>/or captured <strong>and</strong>/or detected (carrier se<strong>ns</strong>e) by thereceiving node. <strong>The</strong> model approxim<strong>at</strong>es the DSSS radio interface (Lucent WaveLan direct-sequence spread-spectrum).See ~<strong>ns</strong>/phy.{cc.h} <strong>and</strong> ~<strong>ns</strong>/wireless-phy.{cc,h} for network interface implement<strong>at</strong>io<strong>ns</strong>.Radio Propag<strong>at</strong>ion Model It uses Friss-space <strong>at</strong>tenu<strong>at</strong>ion (1/r 2 ) <strong>at</strong> near distances <strong>and</strong> an approxim<strong>at</strong>ion to Two ray Ground(1/r 4 ) <strong>at</strong> far distances. <strong>The</strong> approxim<strong>at</strong>ion assumes specular reflection off a fl<strong>at</strong> ground plane. See ~<strong>ns</strong>/tworayground.{cc,h}for implement<strong>at</strong>ion.Antenna An omni-directional antenna having unity gain is used by mobilenodes. See ~<strong>ns</strong>/antenna.{cc,h} for implement<strong>at</strong>iondetails.16.1.4 Different MAC layer protocols for mobile networkingIn <strong>ns</strong>, two MAC layer protocols are implemented for mobile networks, which are 802.11 <strong>and</strong> TDMA. In this section we brieflydiscuss each of them.802.11 MAC protocolSee ~<strong>ns</strong>/mac-802_11.{cc,h} for implement<strong>at</strong>ion details.Preamble based TDMA protocolNote: this works is still <strong>at</strong> a preliminary stage, some practical issues, such as: contention in the preamble phase <strong>and</strong> time slotreuse in a multi-hop environment are not co<strong>ns</strong>idered.Unlike contention based MAC protocol (802.11, for example), a TDMA MAC protocol alloc<strong>at</strong>es different time slots for nodesto send <strong>and</strong> receive packets. <strong>The</strong> superset of these time slots is called a TDMA frame.Currently, <strong>ns</strong> supports a single hop, preamble-based TDMA MAC protocol. With this protocl, a TDMA frame contai<strong>ns</strong>preamble besides the d<strong>at</strong>a tra<strong>ns</strong>mission slots. Within the preamble, every node has a dedic<strong>at</strong>ed subslot <strong>and</strong> uses it to broadcast152


the destin<strong>at</strong>ion node id of outgoing packet. Other nodes listen in the preamble <strong>and</strong> record the time slots to receive packets.Like other common TDMA protocols (GSM, for example), each node has a d<strong>at</strong>a tra<strong>ns</strong>mission slot to send packets.To avoid unnecessary power co<strong>ns</strong>umption, each node tur<strong>ns</strong> its radio on <strong>and</strong> off explicitly by invoking node API set_node_sleep().<strong>The</strong> radio only needs to be on when: in the pramble phase (takes one slot time) <strong>and</strong> there is a packet to send <strong>and</strong> receive.<strong>The</strong> preamble is implemented as a central d<strong>at</strong>a structure tdma_preamble_, which is accessible to all the nodes. At thebeginning of a frame, each node writes the destin<strong>at</strong>ion node id into its subslot in preamble if it has a packet to send. Followingpreamble phase, each node sends packet in its d<strong>at</strong>a tra<strong>ns</strong>mission slot <strong>and</strong> checks the preamble to determine if there is a packetto receive in other slots.<strong>The</strong> following parameters are user configurable: the wireless link b<strong>and</strong>width b<strong>and</strong>with_, the slot length packet_slot_len_,<strong>and</strong> the number of nodes max_node_num_. See ~<strong>ns</strong>/mac-tdma.{cc,h} for implement<strong>at</strong>ion details.16.1.5 Different types of Routing Agents in mobile networking<strong>The</strong> four different ad-hoc routing protocols currently implemented for mobile networking in <strong>ns</strong>are dsdv, dsr, aodv <strong>and</strong> tora.In this section we shall briefly discuss each of them.DSDVIn this routing protocol routing messages are exchanged between neighbouring mobilenodes (i.e mobilenodes th<strong>at</strong> are withinrange of one another). Routing upd<strong>at</strong>es may be triggered or routine. Upd<strong>at</strong>es are triggered in case a routing inform<strong>at</strong>ion fromone of t he neighbours forces a change in the routing table. A packet for which the route to its destin<strong>at</strong>ion is not known iscached while routing queries are sent out. <strong>The</strong> pkts are cached until route-replies are received from the destin<strong>at</strong>ion. <strong>The</strong>re isa maximum buffer size for caching the pkts waiting for routing inform<strong>at</strong>ion beyond which pkts are dropped.All packets destined for the mobilenode are routed directly by the address dmux to its port dmux. <strong>The</strong> port dmux h<strong>and</strong>sthe packets to the respective destin<strong>at</strong>ion agents. A port number of 255 is used to <strong>at</strong>tach routing agent in mobilenodes. <strong>The</strong>mobilenodes al so use a default-target in their classifier (or address demux). In the event a target is not found for the destin<strong>at</strong>ionin the classifier (which happe<strong>ns</strong> when the destin<strong>at</strong>ion of the packet is not the mobilenode itself), the pkts are h<strong>and</strong>ed to thedefault-ta rget which is the routing agent. <strong>The</strong> routing agent assig<strong>ns</strong> the next hop for the packet <strong>and</strong> sends it down to the linklayer.<strong>The</strong> routing protocol is mainly implemented in C++. See ~<strong>ns</strong>/dsdv directory <strong>and</strong> ~<strong>ns</strong>/tcl/mobility/dsdv.tcl for all proceduresrel<strong>at</strong>ed to DSDV protocol implement<strong>at</strong>ion.DSRThis section briefly describes the functionality of the dynamic source routing protocol. As mentioned earlier the SRNode isdifferent from the MobileNode. <strong>The</strong> SRNode’s entry_ points to the DSR routing agent, thus forcing all packets receivedby the node to be h<strong>and</strong>ed down to the routing agent. This model is required for future implement<strong>at</strong>ion of piggy-backed routinginform<strong>at</strong>ion on d<strong>at</strong>a packets which otherwise would not flow through the routing agent.<strong>The</strong> DSR agent checks every d<strong>at</strong>a packet for source-route inform<strong>at</strong>ion. It forwards the packet as per the routing inform<strong>at</strong>ion.Incase it doesnot find routing inform<strong>at</strong>ion in the packet, it provides the source route, if route is known, or caches the packet<strong>and</strong> sends out route queries if route to destin<strong>at</strong>ion is not known. Routing queries, always triggered by a d<strong>at</strong>a packet with noroute to its destin<strong>at</strong>ion, are initially broadcast to all neighbours. Route-replies are send back either by intermedi<strong>at</strong>e nodes orthe destin<strong>at</strong>ion node, to the source, if it can find routing info for the destin<strong>at</strong>ion in the route-query. It h<strong>and</strong>s over all packets153


destined to itself to the port dmux. In SRNode the port number 255 points to a null agent since the packet has already beenprocessed by the routing agent.See ~<strong>ns</strong>/dsr directory <strong>and</strong> ~<strong>ns</strong>/tcl/mobility/dsr.tcl for implement<strong>at</strong>ion of DSR protocol.TORATora is a distributed routing protocol based on "link reversal" algorithm. At every node a separ<strong>at</strong>e copy of TORA is run forevery destin<strong>at</strong>ion. When a node needs a route to a given destin<strong>at</strong>ion it broadcasts a QUERY message containing the addressof the destin<strong>at</strong>ion for which it requires a route. This packet travels through the network until it reaches the destin<strong>at</strong>ion oran intermedi<strong>at</strong>e node th<strong>at</strong> has a route to the destin<strong>at</strong>ion node. This recepient node node then broadcasts an UPDATE packetlisting its height wrt the destin<strong>at</strong>ion. As this node propag<strong>at</strong>es through the network each node upd<strong>at</strong>es its height to a valuegre<strong>at</strong>er than the height of the neighbour from which it receives the UPDATE. This results in a series of directed links from thenode th<strong>at</strong> origin<strong>at</strong>ed the QUERY to the destin<strong>at</strong>ion node. If a node discovers a particular destin<strong>at</strong>ion to be unreachable it setsa local maximum value of height for th<strong>at</strong> destin<strong>at</strong>ion. Incase the node cannot find any neighbour having finite height wrt thisdestin<strong>at</strong>ion it <strong>at</strong>tempts to find a new route. In case of network partition, the node broadcasts a CLEAR message th<strong>at</strong> resets allrouting st<strong>at</strong>es <strong>and</strong> removes invalid routes from the network.TORA oper<strong>at</strong>es on top of IMEP (Internet MANET Encapsul<strong>at</strong>ion Protocol) th<strong>at</strong> provides reliable delivery of route-messages<strong>and</strong> informs the routing protocol of any changes of the links to its neighbours. IMEP tries to aggreg<strong>at</strong>e IMEP <strong>and</strong> TORAmessages into a single packet (called block) in order to reduce overhead. For link-st<strong>at</strong>us se<strong>ns</strong>ing <strong>and</strong> maintaining a list ofneighbour nodes, IMEP sends out periodic BEACON messages which is a<strong>ns</strong>wered by each node th<strong>at</strong> hears it by a HELLOreply message. See <strong>ns</strong>/tora directory <strong>and</strong> <strong>ns</strong>/tcl/mobility/tora.tcl for implement<strong>at</strong>ion of tora in <strong>ns</strong>.AODVAODV is a combin<strong>at</strong>ion of both DSR <strong>and</strong> DSDV protocols. It has the basic route-discovery <strong>and</strong> route-maintenance of DSR<strong>and</strong> uses the hop-by-hop routing, sequence numbers <strong>and</strong> beaco<strong>ns</strong> of DSDV. <strong>The</strong> node th<strong>at</strong> wants to know a route to a givendestin<strong>at</strong>ion gener<strong>at</strong>es a ROUTE REQUEST. <strong>The</strong> route request is forwarded by intermedi<strong>at</strong>e nodes th<strong>at</strong> also cre<strong>at</strong>es a reverseroute for itself from the destin<strong>at</strong>ion. When the request reaches a node with route to destin<strong>at</strong>ion it gener<strong>at</strong>es a ROUTE REPLYcontaining the number of hops requires to reach destin<strong>at</strong>ion. All nodes th<strong>at</strong> particip<strong>at</strong>es in forwarding this reply to the sourcenode cre<strong>at</strong>es a forward route to destin<strong>at</strong>ion. This st<strong>at</strong>e cre<strong>at</strong>ed from each node from source to destin<strong>at</strong>ion is a hop-by-hop st<strong>at</strong>e<strong>and</strong> not the entire route as is done in source routing. See <strong>ns</strong>/aodv <strong>and</strong> <strong>ns</strong>/tcl/lib/<strong>ns</strong>-lib.tcl for implement<strong>at</strong>ional details of aodv.16.1.6 Trace Support<strong>The</strong> trace support for wireless simul<strong>at</strong>io<strong>ns</strong> currently use cmu-trace objects. In the future this shall be extended to merge withtrace <strong>and</strong> monitoring support available in <strong>ns</strong>, which would also include nam support for wireless modules. For now we willexplain briefly with cmu-trace objects <strong>and</strong> how they may be used to trace packets for wireless scenarios.<strong>The</strong> cmu-trace objects are of three types - CMUTrace/Drop, CMUTrace/Recv <strong>and</strong> CMUTrace/Send. <strong>The</strong>se are used fortracing packets th<strong>at</strong> are dropped, received <strong>and</strong> sent by agents, routers, mac layers or interface queues in <strong>ns</strong>. <strong>The</strong> methods <strong>and</strong>procedures used for implementing wireless trace support can be found under ~<strong>ns</strong>/trace.{cc,h} <strong>and</strong> ~<strong>ns</strong>/tcl/lib/<strong>ns</strong>-cmutrace.tcl.A cmu-trace object may be cre<strong>at</strong>ed by the following API:set sndT [cmu-trace Send "RTR" $self]154


which cre<strong>at</strong>es a trace object, sndT, of the type CMUTrace/Send for tracing all packets th<strong>at</strong> are sent out in a router. <strong>The</strong> traceobjects may be used to trace packets in MAC, agents (routing or others), routers or any other NsObject.<strong>The</strong> cmu-trace object CMUTrace is derived from the base class Trace. See Chapter 26 for details on class Trace. <strong>The</strong>class CMUTrace is defined as the following:class CMUTrace : public Trace {public:CMUTrace(co<strong>ns</strong>t char *s, char t);void recv(Packet *p, H<strong>and</strong>ler *h);void recv(Packet *p, co<strong>ns</strong>t char* why);priv<strong>at</strong>e:int off_arp_;int off_mac_;int off_sr_;char tracename[MAX_ID_LEN + 1];int tracetype;MobileNode *node_;int initialized() { return node_ && 1; }};intvoidvoidvoidvoidvoidvoidvoidvoidcomm<strong>and</strong>(int argc, co<strong>ns</strong>t char*co<strong>ns</strong>t* argv);form<strong>at</strong>(Packet *p, co<strong>ns</strong>t char *why);form<strong>at</strong>_mac(Packet *p, co<strong>ns</strong>t char *why, int offset);form<strong>at</strong>_ip(Packet *p, int offset);form<strong>at</strong>_arp(Packet *p, int offset);form<strong>at</strong>_dsr(Packet *p, int offset);form<strong>at</strong>_msg(Packet *p, int offset);form<strong>at</strong>_tcp(Packet *p, int offset);form<strong>at</strong>_rtp(Packet *p, int offset);<strong>The</strong> type field (described in Trace class definition) is used to differenti<strong>at</strong>e among different types of traces. For cmu-tracethis can be s for sending, r for receiving or D for dropping a packet. A fourth type f is used to denote forwarding of a packet(When the node is not the origin<strong>at</strong>or of the packet). Similar to the method Trace::form<strong>at</strong>(), the CMUTrace::form<strong>at</strong>() defines<strong>and</strong> dict<strong>at</strong>es the trace file form<strong>at</strong>. <strong>The</strong> method is shown below:void CMUTrace::form<strong>at</strong>(Packet* p, co<strong>ns</strong>t char *why){hdr_cmn *ch = HDR_CMN(p);int offset = 0;/** Log the MAC Header*/form<strong>at</strong>_mac(p, why, offset);offset = strlen(wrk_);155


switch(ch->ptype()) {case PT_MAC:break;case PT_ARP:form<strong>at</strong>_arp(p, offset);break;default:form<strong>at</strong>_ip(p, offset);offset = strlen(wrk_);switch(ch->ptype()) {case PT_DSR:form<strong>at</strong>_dsr(p, offset);break;case PT_MESSAGE:case PT_UDP:form<strong>at</strong>_msg(p, offset);break;case PT_TCP:case PT_ACK:form<strong>at</strong>_tcp(p, offset);break;case PT_CBR:form<strong>at</strong>_rtp(p, offset);break;..........}}}<strong>The</strong> above function calls different form<strong>at</strong> functio<strong>ns</strong> depending on the type of the packet being traced. All traces are written tothe buffer wrk_. A count of the offset for the buffer is kept <strong>and</strong> is passed along the different trace functio<strong>ns</strong>. <strong>The</strong> most basicform<strong>at</strong> is defined by form<strong>at</strong>_mac() <strong>and</strong> is used to trace all pkt types. <strong>The</strong> other form<strong>at</strong> functio<strong>ns</strong> print additional inform<strong>at</strong>ionas defined by the packet types. <strong>The</strong> mac form<strong>at</strong> prints the following:#ifdef LOG_POSITIONdouble x = 0.0, y = 0.0, z = 0.0;node_->getLoc(&x, &y, &z);#endifsprintf(wrk_ + offset,#ifdef LOG_POSITION"%c %.9f %d (%6.2f %6.2f) %3s %4s %d %s %d [%x %x %x %x] ",#else"%c %.9f _%d_ %3s %4s %d %s %d [%x %x %x %x] ",156


#endifop,// s, r, D or fScheduler::i<strong>ns</strong>tance().clock(), // time stampsrc_,// the nodeid for this node#ifdef LOG_POSITIONx, // x co-ordy, // y co-ord#endiftracename,// name of object type tracingwhy,// reason, if anych->uid(),// identifier for this eventpacket_info.name(ch->ptype()), // packet typech->size(),// size of cmn headermh->dh_dur<strong>at</strong>ion, // expected time to send d<strong>at</strong>aETHER_ADDR(mh->dh_da), // mac_destin<strong>at</strong>ion addressETHER_ADDR(mh->dh_sa),// mac_sender addressGET_ETHER_TYPE(mh->dh_body)); // type - arp or IPIf the LOG_POSITION is defined the x <strong>and</strong> y co-ordin<strong>at</strong>es for the mobilenode is also printed. <strong>The</strong> descriptio<strong>ns</strong> for differentfields in the mac trace are given in the comments above. For all IP packets additional IP header fields are also added to theabove trace. <strong>The</strong> IP trace is described below:sprintf(wrk_ + offset, "------- [%d:%d %d:%d %d %d] ",src,// IP src addressih->sport_, // src port numberdst,// IP dest addressih->dport_, // dest port numberih->ttl_, // TTL value(ch->next_hop_ < 0) ? 0 : ch->next_hop_); // next hopaddress, if any.An example of a trace for a tcp packet is as follows:r 160.093884945 _6_ RTR --- 5 tcp 1492 [a2 4 6 800] ------- [65536:0 16777984:0 31 16777984] [1 0] 2 0Here we see a TCP d<strong>at</strong>a packet being received by a node with id of 6. UID of this pkt is 5 with a cmn hdr size of 1492. <strong>The</strong> macdetails shows an IP pkt (ETHERTYPE_IP is defined as 0x0800, ETHERTYPE_ARP is 0x0806 ), mac-id of this receivingnode is 4. Th<strong>at</strong> of the sending node is 6 <strong>and</strong> expected time to send this d<strong>at</strong>a pkt over the wireless channel is a2 (hex2decconversion: 160+2 sec). Additionally, IP traces inform<strong>at</strong>ion about IP src <strong>and</strong> destin<strong>at</strong>ion addresses. <strong>The</strong> src tra<strong>ns</strong>l<strong>at</strong>es (usinga 3 level hier-address of 8/8/8) to a address string of 0.1.0 with port of 0. <strong>The</strong> dest address is 1.0.3 with port address of 0.<strong>The</strong> TTL value is 31 <strong>and</strong> the destin<strong>at</strong>ion was a hop away from the src. Additionally TCP form<strong>at</strong> prints inform<strong>at</strong>ion about tcpseqno of 1, ackno of 0. See other form<strong>at</strong>s described in ~<strong>ns</strong>//cmu-trace.cc for DSR, UDP/MESSAGE, TCP/ACK <strong>and</strong> CBRpacket types.Other trace form<strong>at</strong>s are also used by the routing agents (TORA <strong>and</strong> DSR) to log certain special routing events like "origin<strong>at</strong>ing"(adding a SR header to a packet) or "ran off the end of a source route" indic<strong>at</strong>ing some sort of routing problem with the sourceroute etc. <strong>The</strong>se special event traces begin with "S" for DSR <strong>and</strong> "T" for Tora <strong>and</strong> may be found in ~<strong>ns</strong>/tora/tora.cc for TORA<strong>and</strong> ~<strong>ns</strong>/dsr/dsrgent.cc for DSR routing agent.157


16.1.7 Revised form<strong>at</strong> for wireless tracesIn an effort to merge wireless trace, using cmu-trace objects, with <strong>ns</strong> tracing, a new, inproved trace form<strong>at</strong> has been introduced.This revised trace support is backwards comp<strong>at</strong>ible with the old trace form<strong>at</strong>ting <strong>and</strong> can be enabled by the followingcomm<strong>and</strong>:$<strong>ns</strong> use-newtraceThis comm<strong>and</strong> should be called before the universal trace comm<strong>and</strong> $<strong>ns</strong> trace-all . Primitive use-newtracesets up new form<strong>at</strong> for wireless tracing by setting a simul<strong>at</strong>or variable called newTraceForm<strong>at</strong>. Currently this new tracesupport is available for wireless simul<strong>at</strong>io<strong>ns</strong> only <strong>and</strong> shall be extended to rest of <strong>ns</strong> in the near future.An example of the new trace form<strong>at</strong> is shown below:s -t 0.267662078 -Hs 0 -Hd -1 -Ni 0 -Nx 5.00 -Ny 2.00 -Nz 0.00 -Ne-1.000000 -Nl RTR -Nw --- -Ma 0 -Md 0 -Ms 0 -Mt 0 -Is 0.255 -Id -1.255 -Itmessage -Il 32 -If 0 -Ii 0 -Iv 32s -t 1.511681090 -Hs 1 -Hd -1 -Ni 1 -Nx 390.00 -Ny 385.00 -Nz 0.00 -Ne-1.000000 -Nl RTR -Nw --- -Ma 0 -Md 0 -Ms 0 -Mt 0 -Is 1.255 -Id -1.255 -Itmessage -Il 32 -If 0 -Ii 1 -Iv 32s -t 10.000000000 -Hs 0 -Hd -2 -Ni 0 -Nx 5.00 -Ny 2.00 -Nz 0.00 -Ne-1.000000 -Nl AGT -Nw --- -Ma 0 -Md 0 -Ms 0 -Mt 0 -Is 0.0 -Id 1.0 -It tcp -Il 1000 -If2 -Ii 2 -Iv 32 -Pn tcp -Ps 0 -Pa 0 -Pf 0 -Po 0r -t 10.000000000 -Hs 0 -Hd -2 -Ni 0 -Nx 5.00 -Ny 2.00 -Nz 0.00 -Ne-1.000000 -Nl RTR -Nw --- -Ma 0 -Md 0 -Ms 0 -Mt 0 -Is 0.0 -Id 1.0 -It tcp -Il 1000 -If2 -Ii 2 -Iv 32 -Pn tcp -Ps 0 -Pa 0 -Pf 0 -Po 0r -t 100.004776054 -Hs 1 -Hd 1 -Ni 1 -Nx 25.05 -Ny 20.05 -Nz 0.00 -Ne-1.000000 -Nl AGT -Nw --- -Ma a2 -Md 1 -Ms 0 -Mt 800 -Is 0.0 -Id 1.0 -Ittcp -Il 1020 -If 2 -Ii 21 -Iv 32 -Pn tcp -Ps 0 -Pa 0 -Pf 1 -Po 0s -t 100.004776054 -Hs 1 -Hd -2 -Ni 1 -Nx 25.05 -Ny 20.05 -Nz 0.00 -Ne-1.000000 -Nl AGT -Nw --- -Ma 0 -Md 0 -Ms 0 -Mt 0 -Is 1.0 -Id 0.0 -It ack -Il 40-If 2 -Ii 22 -Iv 32 -Pn tcp -Ps 0 -Pa 0 -Pf 0 -Po 0Explan<strong>at</strong>ion of new trace form<strong>at</strong><strong>The</strong> new trace form<strong>at</strong> as seen above can be can be divided into the following fields :Event type In the traces above, the first field (as in the older trace form<strong>at</strong>) describes the type of event taking place <strong>at</strong> the node<strong>and</strong> can be one of the four types:s sendr received dropf forwardGeneral tag <strong>The</strong> second field starting with "-t" may st<strong>and</strong> for time or global setting-t time-t * (global setting)158


Node property tags This field denotes the node properties like node-id, the level <strong>at</strong> which tracing is being done like agent,router or MAC. <strong>The</strong> tags start with a leading "-N" <strong>and</strong> are listed as below:-Ni: node id-Nx: node’s x-coordin<strong>at</strong>e-Ny: node’s y-coordin<strong>at</strong>e-Nz: node’s z-coordin<strong>at</strong>e-Ne: node energy level-Nl: trace level, such as AGT, RTR, MAC-Nw: reason for the event. <strong>The</strong> different reaso<strong>ns</strong> for dropping a packet are given below:"END" DROP_END_OF_SIMULATION"COL" DROP_MAC_COLLISION"DUP" DROP_MAC_DUPLICATE"ERR" DROP_MAC_PACKET_ERROR"RET" DROP_MAC_RETRY_COUNT_EXCEEDED"STA" DROP_MAC_INVALID_STATE"BSY" DROP_MAC_BUSY"NRTE" DROP_RTR_NO_ROUTE i.e no route is available."LOOP" DROP_RTR_ROUTE_LOOP i.e there is a routing loop"TTL" DROP_RTR_TTL i.e TTL has reached zero."TOUT" DROP_RTR_QTIMEOUT i.e packet has expired."CBK" DROP_RTR_MAC_CALLBACK"IFQ" DROP_IFQ_QFULL i.e no buffer space in IFQ."ARP" DROP_IFQ_ARP_FULL i.e dropped by ARP"OUT" DROP_OUTSIDE_SUBNET i.e dropped by base st<strong>at</strong>io<strong>ns</strong> on receiving routing upd<strong>at</strong>es from nodes outsideits domain.Packet inform<strong>at</strong>ion <strong>at</strong> IP level <strong>The</strong> tags for this field start with a leading "-I" <strong>and</strong> are listed along with their explan<strong>at</strong>io<strong>ns</strong> asfollowing:-Is: source address.source port number-Id: dest address.dest port number-It: packet type-Il: packet size-If: flow id-Ii: unique id-Iv: ttl valueNext hop info This field provides next hop info <strong>and</strong> the tag starts with a leading "-H".-Hs: id for this node-Hd: id for next hop towards the destin<strong>at</strong>ion.Packet info <strong>at</strong> MAC level This field gives MAC layer inform<strong>at</strong>ion <strong>and</strong> starts with a leading "-M" as shown below:-Ma: dur<strong>at</strong>ion-Md: dst’s ethernet address-Ms: src’s ethernet address-Mt: ethernet type159


Packet info <strong>at</strong> "Applic<strong>at</strong>ion level" <strong>The</strong> packet inform<strong>at</strong>ion <strong>at</strong> applic<strong>at</strong>ion level co<strong>ns</strong>ists of the type of applic<strong>at</strong>ion like ARP,TCP, the type of adhoc routing protocol like DSDV, DSR, AODV etc being traced. This field co<strong>ns</strong>ists of a leading "-P"<strong>and</strong> list of tags for different applic<strong>at</strong>ion is listed as below:-P arp Address Resolution Protocol. Details for ARP is given by the following tags:-Po: ARP Request/Reply-Pm: src mac address-Ps: src address-Pa: dst mac address-Pd: dst address-P dsr This denotes the adhoc routing protocol called Dynamic source routing. Inform<strong>at</strong>ion on DSR is represented bythe following tags:-Pn: how many nodes traversed-Pq: routing request flag-Pi: route request sequence number-Pp: routing reply flag-Pl: reply length-Pe: src of srcrouting->dst of the source routing-Pw: error report flag ?-Pm: number of errors-Pc: report to whom-Pb: link error from linka->linkb-P cbr Co<strong>ns</strong>tant bit r<strong>at</strong>e. Inform<strong>at</strong>ion about the CBR applic<strong>at</strong>ion is represented by the following tags:-Pi: sequence number-Pf: how many times this pkt was forwarded-Po: optimal number of forwards-P tcp Inform<strong>at</strong>ion about TCP flow is given by the following subtags:-Ps: seq number-Pa: ack number-Pf: how many times this pkt was forwarded-Po: optimal number of forwardsThis field is still under development <strong>and</strong> new tags shall be added for other applic<strong>at</strong>io<strong>ns</strong> as they get included along theway.16.1.8 Gener<strong>at</strong>ion of node-movement <strong>and</strong> traffic-connection for wireless scenariosNormally for large topologies, the node movement <strong>and</strong> traffic connection p<strong>at</strong>ter<strong>ns</strong> are defined in separ<strong>at</strong>e files for convinience.<strong>The</strong>se movement <strong>and</strong> traffic files may be gener<strong>at</strong>ed using CMU’s movement- <strong>and</strong> connection-gener<strong>at</strong>ors. In this section weshall describe both separ<strong>at</strong>ely.MobileNode MovementSome examples of node movement files may be found in ~<strong>ns</strong>/tcl/mobility/scene/scen-670x670-50-600-20-*. <strong>The</strong>se filesdefine a topology of 670 by 670m where 50 nodes move with a speed of 20m/s with pause time of 600s. each node is assigned160


a starting position. <strong>The</strong> inform<strong>at</strong>ion regarding number of hops between the nodes is fed to the central object "GOD" (XXXbut why/where is this inform<strong>at</strong>ion used??-a<strong>ns</strong>wer awaited from CMU.) Next each node is a speed <strong>and</strong> a direction to move to.<strong>The</strong> gener<strong>at</strong>or for cre<strong>at</strong>ing node movement files are to be found under ~<strong>ns</strong>/indep-utils/cmu-scen-gen/setdest/ directory. Compilethe files under setdest to cre<strong>at</strong>e an executable. run setdest with arguments in the following way:./setdest -n -p -s -t -x -y > /Note th<strong>at</strong> the index used for nodes now start from 0 i<strong>ns</strong>tead of 1 as was in the original CMU version, to m<strong>at</strong>ch with <strong>ns</strong>’stradition of assigning node indices from 0.Gener<strong>at</strong>ing traffic p<strong>at</strong>tern files<strong>The</strong> examples for traffic p<strong>at</strong>ter<strong>ns</strong> may be found in ~<strong>ns</strong>/tcl/mobility/scene/cbr-50-{10-4-512, 20-4-512}.<strong>The</strong> traffic gener<strong>at</strong>or is loc<strong>at</strong>ed under ~<strong>ns</strong>/indep-utils/cmu-scen-gen/ <strong>and</strong> are called cbrgen.tcl <strong>and</strong> tcpgen.tcl. <strong>The</strong>y may beused for gener<strong>at</strong>ing CBR <strong>and</strong> TCP connectio<strong>ns</strong> respectively.To cre<strong>at</strong>e CBR connecio<strong>ns</strong>, run<strong>ns</strong> cbrgen.tcl [-type cbr|tcp] [-nn nodes] [-seed seed][-mc connectio<strong>ns</strong>] [-r<strong>at</strong>e r<strong>at</strong>e]To cre<strong>at</strong>e TCP connectio<strong>ns</strong>, run<strong>ns</strong> tcpgen.tcl [-nn nodes] [-seed seed]You will need to pipe the outputs from above to a cbr-* or a tcp-* file.16.2 Exte<strong>ns</strong>io<strong>ns</strong> made to CMU’s wireless modelAs mentioned earlier, the original CMU wireless model allows simul<strong>at</strong>ion of wireless LANs <strong>and</strong> ad-hoc networks. Howeverin order to use the wireless model for simul<strong>at</strong>io<strong>ns</strong> using both wired <strong>and</strong> wireless nodes we had to add certain exte<strong>ns</strong>io<strong>ns</strong> tocmu model. We call this wired-cum-wireless fe<strong>at</strong>ure. Also SUN’s MobileIP (implemented for wired nodes) was integr<strong>at</strong>edinto the wireless model allowing mobileIP to run over wireless mobilenodes. <strong>The</strong> following two subsectio<strong>ns</strong> describe thesetwo exte<strong>ns</strong>io<strong>ns</strong> to the wireless model in <strong>ns</strong>.16.2.1 wired-cum-wireless scenarios<strong>The</strong> mobilenodes described so far mainly supports simul<strong>at</strong>ion of multi-hop ad-hoc networks or wireless LANs. But wh<strong>at</strong> ifwe need to simul<strong>at</strong>e a topology of multiple wireless LANs connected through wired nodes, or may need to run mobileIP ontop of these wireless nodes? <strong>The</strong> exte<strong>ns</strong>io<strong>ns</strong> made to the CMU wireless model allows us to do th<strong>at</strong>.161


<strong>The</strong> main problem facing the wired-cum-wireless scenario was the issue of routing. In <strong>ns</strong>, routing inform<strong>at</strong>ion is gener<strong>at</strong>edbased on the connectivity of the topology, i.e how nodes are connected to one another through Links. Mobilenodes on theother h<strong>and</strong> have no concept of links. <strong>The</strong>y route packets among themselves, within the wireless topology, using their routingprotocol. so how would packets be exchanged between these two types of nodes?So a node called BaseSt<strong>at</strong>ionNode is cre<strong>at</strong>ed which plays the role of a g<strong>at</strong>eway for the wired <strong>and</strong> wireless domai<strong>ns</strong>.<strong>The</strong> BaseSt<strong>at</strong>ionNode is essentially a hybrid between a Hierarchical node 1 (HierNode) <strong>and</strong> a MobileNode. <strong>The</strong>basest<strong>at</strong>ion node is respo<strong>ns</strong>ible for delivering packets into <strong>and</strong> out of the wireless domain. In order to achieve this we needHierarchical routing.Each wireless domain along with its base-st<strong>at</strong>ion would have an unique domain address assigned to them. All packets destinedto a wireless node would reach the base-st<strong>at</strong>ion <strong>at</strong>tached to the domain of th<strong>at</strong> wireless node, who would eventually h<strong>and</strong> thepacket over to the destin<strong>at</strong>ion (mobilenode). And mobilenodes route packets, destined to outside their (wireless) domain, totheir base-st<strong>at</strong>ion node. <strong>The</strong> base-st<strong>at</strong>ion knows how to forward these packets towards the (wired) destin<strong>at</strong>ion. <strong>The</strong> schem<strong>at</strong>icof a BaseSt<strong>at</strong>ionNode is shown in Figure 16.3.<strong>The</strong> mobilenodes in wired-cum-wireless scenario are required to support hierarchical addressing/routing. Thus the MobileNodelooks exactly like the BaseSt<strong>at</strong>ionNode. <strong>The</strong> SRNode, however, simply needs to have its own hier-address since it doesnot require any address demuxes <strong>and</strong> thus is not required to support hier routing 2 .<strong>The</strong> DSDV agent on having to forward a packet checks to see if the destin<strong>at</strong>ion is outside its (wireless) subnet. If so, it triesto forward the packet to its base-st<strong>at</strong>ion node. In case no route to base-st<strong>at</strong>ion is found the packet is dropped. Otherwisethe packet is forwarded to the next_hop towards the base-st<strong>at</strong>ion. Which is then routed towards the wired network by basest<strong>at</strong>ion’sclassifiers.<strong>The</strong> DSR agent, on receiving a pkt destined outside its subnet, sends out a route-query for its base-st<strong>at</strong>ion in case the route tobase-st<strong>at</strong>ion is not known. <strong>The</strong> d<strong>at</strong>a pkt is temporarily cached while it waits to hear route replies from base-st<strong>at</strong>ion. On gettinga reply the packet is provided with routing inform<strong>at</strong>ion in its header <strong>and</strong> send away towards the base-st<strong>at</strong>ion. <strong>The</strong> base-st<strong>at</strong>ionaddress demuxes routes it correctly toward the wired network.<strong>The</strong> example script for a wired-cum-wireless simul<strong>at</strong>ion can be found <strong>at</strong> ~<strong>ns</strong>/tcl/ex/wired-cum-wireless-sim.tcl. <strong>The</strong> methodsfor wired-cum-wireless implement<strong>at</strong>io<strong>ns</strong> are defined in ~<strong>ns</strong>/tcl/lib/<strong>ns</strong>-bsnode.tcl, ~<strong>ns</strong>/tcl/mobility/{com.tcl,dsr.tcl, dsdv.tcl},~<strong>ns</strong>/dsdv/dsdv.{cc,h} <strong>and</strong> ~<strong>ns</strong>/dsr/dsragent.{cc,h}.16.2.2 MobileIP<strong>The</strong> wired-cum-wireless exte<strong>ns</strong>io<strong>ns</strong> for the wireless model paved the p<strong>at</strong>h for supporting wireless MobileIP in <strong>ns</strong>. SunMicrosystem’s (Charlie Perki<strong>ns</strong> et al) MobileIP model was based on <strong>ns</strong>’s wired model (co<strong>ns</strong>isting of Node’s <strong>and</strong> Link’s)<strong>and</strong> thus didnot use CMU’s mobility model.Here we briefly describe the wireless MobileIP implement<strong>at</strong>ion. We hope th<strong>at</strong> Sun would provide the detailed version of thedocument<strong>at</strong>ion in the future.<strong>The</strong> mobileIP scenario co<strong>ns</strong>ists of Home-Agents(HA) <strong>and</strong> Foreign-Agents(FA) <strong>and</strong> have Mobile-Hosts(MH) moving betweentheir HA <strong>and</strong> FAs. <strong>The</strong> HA <strong>and</strong> FA are essentially base-st<strong>at</strong>ion nodes we have described earlier. While MHs arebasically the mobileNodes described in section 16.1.1. <strong>The</strong> methods <strong>and</strong> procedures for MobileIP exte<strong>ns</strong>io<strong>ns</strong> are described in~<strong>ns</strong>/mip.{cc,h}, ~<strong>ns</strong>/mip-reg.cc, ~<strong>ns</strong>/tcl/lib/<strong>ns</strong>-mip.tcl <strong>and</strong> ~<strong>ns</strong>/tcl/lib/<strong>ns</strong>-wireless-mip.tcl.<strong>The</strong> HA <strong>and</strong> FA nodes are defined as MobileNode/MIPBS having a registering agent (regagent_) th<strong>at</strong> sends beacon out to1 Refer to Chapter 32 for details on hierarchical routing <strong>and</strong> internals of HierNode.2 In order to do away with all these different vari<strong>at</strong>io<strong>ns</strong> of the definition of a node, we are planning to revise the node architecture th<strong>at</strong> would allow a moreflexible <strong>and</strong> modularised co<strong>ns</strong>truction of a node without the necessity of having to define <strong>and</strong> be limited to certain Class definitio<strong>ns</strong> only.162


HierarchicalclassifiersportdemuxSrc/Sinknodeentrylevel 1level 2level nIP address255RTagent(DSDV)defaulttarget_target_arptable_uptarget_LLARPdowntarget_IFqdowntarget_mac_MACuptarget_downtarget_uptarget_RadioPropag<strong>at</strong>ionModelpropag<strong>at</strong>ion_NetIFchannel_uptarget_ChannelFigure 16.3: Schem<strong>at</strong>ic of a baseSt<strong>at</strong>ionNodethe mobilenodes, sets up encapsul<strong>at</strong>or <strong>and</strong> decapsul<strong>at</strong>or, as required <strong>and</strong> replies to solicit<strong>at</strong>io<strong>ns</strong> from MHs. <strong>The</strong> MH nodesare defined as MobileNode/MIPMH which too have a regagent_ th<strong>at</strong> receives <strong>and</strong> responds to beaco<strong>ns</strong> <strong>and</strong> sends out solicit<strong>at</strong>io<strong>ns</strong>to HA or FAs. Figure 16.4 illustr<strong>at</strong>es the schem<strong>at</strong>ic of a MobileNode/MIPBS node. <strong>The</strong> MobileNode/MIPMHnode is very similar to this except for the fact th<strong>at</strong> it doesnot have any encapsul<strong>at</strong>or or decapsul<strong>at</strong>or. As for the SRNode versionof a MH, it doesnot have the hierarchical classifiers <strong>and</strong> the RA agent forms the entry point of the node. See Figure 16.2 for163


target_target_encapsul<strong>at</strong>orreg_agent_MH IP address01decapsul<strong>at</strong>or_Hierarchicalclassifierslevel nown IP address255defaulttarget_entry_level 2level 1defaulttarget_Rtg Agenttarget_uptarget_LLdowntarget_ChannelFigure 16.4: Schem<strong>at</strong>ic of a Wireless MobileIP BaseSt<strong>at</strong>ion Nodemodel of a SRNode.<strong>The</strong> MobileNode/MIPBS node routinely broadcasts beacon or advertisement messages out to MHs. A solicit<strong>at</strong>ion from amobilenode gener<strong>at</strong>es an ad th<strong>at</strong> is send directly to the requesting MH. <strong>The</strong> address of the base-st<strong>at</strong>ion sending out beacon isheard by MH <strong>and</strong> is used as the COA (care-of-address) of the MH. Thus as the MH moves from its n<strong>at</strong>ive to foreign domai<strong>ns</strong>,its COA changes. Upon receiving reg_request (as reply to ads) from a mobilehost the base-st<strong>at</strong>ion checks to see if it is theHA for the MH. If not, it sets up its decapsul<strong>at</strong>or <strong>and</strong> forwards the reg_request towards the HA of the MH.In case the base-st<strong>at</strong>ion is the HA for the requesting MH but the COA doesnot m<strong>at</strong>ch its own, it sets up an encapsul<strong>at</strong>or <strong>and</strong>sends reg-request-reply back to the COA (address of the FA) who has forwarded the reg_request to it. so now all packetsdestined to the MH reaching the HA would be tunneled through the encapsul<strong>at</strong>or which encapsul<strong>at</strong>es the IP pkthdr with aIPinIP hdr, now destined to the COA i<strong>ns</strong>tead of MH. <strong>The</strong> FA’s decapsul<strong>at</strong>or recives this packet, removes the encapsul<strong>at</strong>ion164


<strong>and</strong> sends it to the MH.If the COA m<strong>at</strong>ches th<strong>at</strong> of the HA, it just removes the encapsul<strong>at</strong>or it might have set up (when its mobilehost was roaminginto foreign networks) <strong>and</strong> sends the reply directly back to the MH, as the MH have now returned to its n<strong>at</strong>ive domain.<strong>The</strong> mobilehost sends out solicit<strong>at</strong>io<strong>ns</strong> if it doesnot hear any ads from the base-st<strong>at</strong>io<strong>ns</strong>. Upon receiving ads, it changes itsCOA to the address of the HA/FA it has heard the ad from, <strong>and</strong> replies back to the COA with a request for registr<strong>at</strong>ion(reg-request). Initially the MH maybe in the range of the HA <strong>and</strong> receives all pkts directly from its COA which is HA inthis case. Eventually as the MH moves out of range of its HA <strong>and</strong> into the a foreign domain of a FA, the MH’s COA changesfrom its HA to th<strong>at</strong> of the FA. <strong>The</strong> HA now sets up an encapsul<strong>at</strong>or <strong>and</strong> tunnels all pkts destined for MH towards the FA.<strong>The</strong> FA decapsul<strong>at</strong>es the pkts <strong>and</strong> h<strong>and</strong>s them over to the MH. <strong>The</strong> d<strong>at</strong>a from MH destined for the wired world is alwaysrouted towards its current COA. An example script for wireless mobileIP can be found <strong>at</strong> ~<strong>ns</strong>/tcl/ex/wireless-mip-test.tcl. <strong>The</strong>simul<strong>at</strong>ion co<strong>ns</strong>ists of a MH moving between its HA <strong>and</strong> a FA. <strong>The</strong> HA <strong>and</strong> FA are each connected to a wired domain on oneside <strong>and</strong> to their wireless domai<strong>ns</strong> on the other. TCP flows are set up between the MH <strong>and</strong> a wired node.16.3 Lists of changes for merging code developed in older version of <strong>ns</strong> (2.1b5 orl<strong>at</strong>er) into the current version (2.1b8)<strong>The</strong> CMU-wireless model developed by David Johnhson’s Monarch project was merged into <strong>ns</strong> around 1998-99 in wh<strong>at</strong> wasthen the <strong>ns</strong>-2.1b5 version. Since then the <strong>ns</strong> versio<strong>ns</strong> used by Monarch <strong>and</strong> by us here <strong>at</strong> ISI have forked quite a bit. Recentlywe ported a newer version of DSR developed by the Monarch group back into <strong>ns</strong> <strong>and</strong> in the process have cre<strong>at</strong>ed a list ofchanges th<strong>at</strong> were required to be made for the merge. Hopefully this list will be helpful for those who have been working onolder versio<strong>ns</strong> of <strong>ns</strong> from around th<strong>at</strong> time or or l<strong>at</strong>er, to have their stuff merged in to the current version of <strong>ns</strong>-2.1b8.<strong>The</strong> following lists of changes are required for merging the cmu version of <strong>ns</strong> (2.1b5) in to current version of 2.1b8. Eachchange is followed by a brief explan<strong>at</strong>ion for why the change was made.Methods for accessing pkt hdrs have changed from(hdr_sr *)p->access(off_sr)to a st<strong>at</strong>ic access method defined for each hdr, ashdr_sr::access(p)where for class hdr_sr a st<strong>at</strong>ic method access() is defined asinline st<strong>at</strong>ic hdr_sr* access(co<strong>ns</strong>t Packet* p)return (hdr_sr*)p->access(offset_);why: This change avoids using casts everywhere.As the method for accessing hdrs have changed, there is no need to explicitly bind the hdr offset values. This is now donewhile establishing tcl linkage for the individual hdr classes. so lines likebind("off_SR_", &off_sr_);bind("off_ll_", &off_ll_);bind("off_mac_", &off_mac_);bind("off_ip_", &off_ip_);should be removed.AF_ enumer<strong>at</strong>io<strong>ns</strong> replaced by NS_AF_ as inenum <strong>ns</strong>_af_enum NS_AF_NONE, NS_AF_ILINK, NS_AF_INET ;165


why: This avoids header clashes between <strong>ns</strong> <strong>and</strong> the OS.<strong>The</strong> ip hdr (dst/src) address fields th<strong>at</strong> used be integers are now defined as structures called <strong>ns</strong>_addr_t. <strong>ns</strong>_addr_t has 2members address_ <strong>and</strong> port_ th<strong>at</strong> are both defined as int. Hence lines likeiph->src() should change toiph->saddr() & iph->sport();Also lines likedst_ = (IP_BROADCAST « 8) | RT_PORTshould be replaced bydst_.addr_ = IP_BROADCAST;dst_.port_ = RT_PORT;Why: This exte<strong>ns</strong>ion supports 32bit addressing.<strong>The</strong> addrs_ member for hdr_sr class has a separ<strong>at</strong>e function for returning its value . Thus need to call hsr.addrs()i<strong>ns</strong>tead of hsr.addrs.why: addrs_ is now a priv<strong>at</strong>e variable which is accessed by public function addrs().All includes th<strong>at</strong> had absolute p<strong>at</strong>hs by using were replaced by "". Thuswas changed to"cmu/dsr/dsragent.h"<strong>The</strong> tcl comm<strong>and</strong> "ip-addr" was changed to "addr".Other new tcl comm<strong>and</strong>s like "node", "port-dmux" <strong>and</strong> "trace-target" were added.why: Part of support for mobileIP <strong>and</strong> wired-cum-wireless simul<strong>at</strong>io<strong>ns</strong>.Need to convert address in string form<strong>at</strong> into int form<strong>at</strong>; so useAddress::i<strong>ns</strong>tance().str2addr(argv[2])i<strong>ns</strong>tead of<strong>at</strong>oi(argv[2])why: This is required for supporting hier-addressing/routing.<strong>The</strong> array packet_names[] has changed to packet_info.name()why: In order to remove a bunch of #defines for pkt types, an enumer<strong>at</strong>ion called packet_t now describes all packet types in<strong>ns</strong>. class p_info was cre<strong>at</strong>ed th<strong>at</strong> now describes an array name_ th<strong>at</strong> has replaced packet_names array used previously.Have to explicitly set direction of new pkts to DOWN before sending them down to the LL.why: A variable direction_ in hdr_cmn is now used. This is used in the lower layers like LL, mac, phy etc to determine thedirection of the pkt flow. All incoming pkts are marked as UP by channel, which should be remarked as DOWN by agentsbefore sending them out into the network again.I<strong>ns</strong>tead of logtarget->buffer, should now call logtarget->pt_->buffer.why: This change reflects support for eventtracing. Tracing has evolved into two types, packet tracing <strong>and</strong> event tracing.Class Trace essentially supports packet tracing. However in addition to the basic tracing properties th<strong>at</strong> it derives from aBaseTrace class, pkt-tracing also requires to inherit some of the Connector class properties as well. Hence pt_, a basetraceobject represents the pure tracing functionalities required for a trace object.<strong>The</strong> parameter used to describe the reason a pkt was dropped used to be an integer. This was changed to char*. Henceneeded to define different pkt-drop reaso<strong>ns</strong> in string form<strong>at</strong>s.Why: Allows gre<strong>at</strong>er exp<strong>and</strong>ibility <strong>and</strong> flexibility.linkHead changed to dsrLinkHead.why: name clashed with linkHead used elsewhere in <strong>ns</strong>.166


<strong>The</strong> older cmu model used an incoming_ flag added in all pkts to figure out direction of pkt flow in the lower layers like ll,mac etc. L<strong>at</strong>er this was replaced by a variable called direction_ added in cmn_hdr. direction value can be set to UP, DOWNor NONE. all pkts cre<strong>at</strong>ed with a DOWN dir by default.why: Both these flags were being used which is not really reqd. so incoming_ flag has been replaced with direction_.16.4 Comm<strong>and</strong>s <strong>at</strong> a glanceFollowing is a list of comm<strong>and</strong>s used in wireless simul<strong>at</strong>io<strong>ns</strong>:$<strong>ns</strong>_ node-config -addressingType -adhocRouting -llType-macType -propType -ifqType -ifqLen -phyType -antType -channelType -topoI<strong>ns</strong>tance -wiredRouting -mobileIP -energyModel -initialEnergy -rxPower -txPower -agentTrace -routerTrace -macTrace -movementTrace This comm<strong>and</strong> is used typically to configure for a mobilenode. For more info about this comm<strong>and</strong> (part of new node APIs)see chapter titled "Restructuring <strong>ns</strong> node <strong>and</strong> new Node APIs" in <strong>ns</strong> <strong>Notes</strong> <strong>and</strong> <strong>Document<strong>at</strong>ion</strong>.$<strong>ns</strong>_ node This comm<strong>and</strong> is used to cre<strong>at</strong>e a mobilenode after node configur<strong>at</strong>ion is done as shown in the node-config comm<strong>and</strong>. Incasehierarchical addressing is being used, the hier address of the node needs to be passed as well.$node log-movementThis comm<strong>and</strong> previously used to enable logging of mobilenode’s movement has now been replaced by $<strong>ns</strong>_node-config -movementTrace .cre<strong>at</strong>e-god 167


This comm<strong>and</strong> is used to cre<strong>at</strong>e a God i<strong>ns</strong>tance. <strong>The</strong> number of mobilenodes is passed as argument which is used by God tocre<strong>at</strong>e a m<strong>at</strong>rix to store connectivity inform<strong>at</strong>ion of the topology.$topo load_fl<strong>at</strong>grid This initializes the grid for the topography object. <strong>and</strong> are the x-y co-ordin<strong>at</strong>es for the topology <strong>and</strong> are used forsizing the grid. <strong>The</strong> grid resolution may be passed as . A default value of 1 is normally used.$topo load_demfile For loading DEMFile objects into topography. See <strong>ns</strong>/dem.cc,.h for details on DEMFiles.$<strong>ns</strong>_ namtrace-all-wireless This comm<strong>and</strong> is used to initialize a namtrace file for logging node movements to be viewed in nam. <strong>The</strong> namtrace filedescriptor, the X <strong>and</strong> Y co-ordin<strong>at</strong>es of the wireless topology is passed as parameters with this comm<strong>and</strong>.$<strong>ns</strong>_ nam-end-wireless This comm<strong>and</strong> is used to tell nam the simul<strong>at</strong>ion stop time given by .$<strong>ns</strong>_ initial_node_pos This comm<strong>and</strong> defines the node initial position in nam. denotes the size of node in nam. This function must be calledafter mobility model has been defined.$mobilenode r<strong>and</strong>om-motion R<strong>and</strong>om-motion is used to turn on r<strong>and</strong>om movements for the mobilenode, in which case r<strong>and</strong>om destin<strong>at</strong>io<strong>ns</strong> are assignedto the node. 0 disables <strong>and</strong> 1 enables r<strong>and</strong>om-motion.$mobilenode setdest This comm<strong>and</strong> is used to setup a destin<strong>at</strong>ion for the mobilenode. <strong>The</strong> mobile node starts moving towards destin<strong>at</strong>ion givenby <strong>and</strong> <strong>at</strong> a speed of m/s.$mobilenode resetThis comm<strong>and</strong> is used to reset all the objects in the nodes (network components like LL, MAC, phy etc).Internal proceduresFollowing is a list of internal procedures used in wireless networking:$mobilenode base-st<strong>at</strong>ion This is used for wired-cum-wireless scenarios. Here the mobilenode is provided with the base-st<strong>at</strong>ionnode info for itsdomain. <strong>The</strong> address is hierarchical since wired-cum-wireless scenarios typically use hierarchical addressing.$mobilenode log-target <strong>The</strong> , which is normally a trace object, is used to log mobilenode movements <strong>and</strong> their energy usage, ifenergy model is provided.$mobilenode topography This comm<strong>and</strong> is used to provide the node with a h<strong>and</strong>le to the topography object.$mobilenode addifA mobilenode may have more than one network interface. This comm<strong>and</strong> is used to pass h<strong>and</strong>le for a network interface tothe node.$mobilenode nam<strong>at</strong>tach This comm<strong>and</strong> is used to <strong>at</strong>tach the namtrace file descriptor to the mobilenode. All nam traces for the nodeare then written into this namtrace file.168


$mobilenode radius <strong>The</strong> radius denotes the node’s range. All mobilenodes th<strong>at</strong> fall within the circle of radius with the node <strong>at</strong> its centerare co<strong>ns</strong>idered as neighbours. This info is typically used by the gridkeeper.$mobilenode startThis comm<strong>and</strong> is used to start off the movement of the mobilenode.169


Chapter 17S<strong>at</strong>ellite Networking in <strong>ns</strong>This chapter describes exte<strong>ns</strong>io<strong>ns</strong> th<strong>at</strong> enable the simul<strong>at</strong>ion of s<strong>at</strong>ellite networks in <strong>ns</strong>. In particular, these exte<strong>ns</strong>io<strong>ns</strong> enable<strong>ns</strong> to model the following: i) traditional geost<strong>at</strong>ionary “bent-pipe” s<strong>at</strong>ellites with multiple users per uplink/downlink <strong>and</strong>asymmetric links, ii) geost<strong>at</strong>ionary s<strong>at</strong>ellites with processing payloads (either regener<strong>at</strong>ive payloads or full packet switching),<strong>and</strong> iii) polar orbiting LEO co<strong>ns</strong>tell<strong>at</strong>io<strong>ns</strong> such as Iridium <strong>and</strong> Teledesic. <strong>The</strong>se s<strong>at</strong>ellite models are principally aimed <strong>at</strong> using<strong>ns</strong> to study networking aspects of s<strong>at</strong>ellite systems; in particular, MAC, link layer, routing, <strong>and</strong> tra<strong>ns</strong>port protocols.17.1 Overview of s<strong>at</strong>ellite modelsExact simul<strong>at</strong>ion of s<strong>at</strong>ellite networks requires a detailed modelling of radio frequency characteristics (interference, fading),protocol interactio<strong>ns</strong> (e.g., interactio<strong>ns</strong> of residual burst errors on the link with error checking codes), <strong>and</strong> second-order orbitaleffects (precession, gravit<strong>at</strong>ional anomalies, etc.). However, in order to study fundamental characteristics of s<strong>at</strong>ellite networksfrom a networking perspective, certain fe<strong>at</strong>ures may be abstracted out. For example, the performance of TCP over s<strong>at</strong>ellitelinks is impacted little by using an approxim<strong>at</strong>e r<strong>at</strong>her than detailed channel model– performance can be characterized to firstorder by the overall packet loss probability. This is the approach taken in this simul<strong>at</strong>ion model– to cre<strong>at</strong>e a framework forstudying tra<strong>ns</strong>port, routing, <strong>and</strong> MAC protocols in a s<strong>at</strong>ellite environment co<strong>ns</strong>isting of geost<strong>at</strong>ionary s<strong>at</strong>ellites or co<strong>ns</strong>tell<strong>at</strong>io<strong>ns</strong>of polar-orbiting low-earth-orbit (LEO) s<strong>at</strong>ellites. Of course, users may extend these models to provide more detail <strong>at</strong> agiven layer.17.1.1 Geost<strong>at</strong>ionary s<strong>at</strong>ellitesGeost<strong>at</strong>ionary s<strong>at</strong>ellites orbit the Earth <strong>at</strong> an altitude of 22,300 miles above the equ<strong>at</strong>or. <strong>The</strong> position of the s<strong>at</strong>ellites isspecified in terms of the longitude of the nadir point (subs<strong>at</strong>ellite point on the Earth’s surface). In practice, geost<strong>at</strong>ionarys<strong>at</strong>ellites can drift from their design<strong>at</strong>ed loc<strong>at</strong>ion due to gravit<strong>at</strong>ional perturb<strong>at</strong>io<strong>ns</strong>– these effects are not modelled in <strong>ns</strong>.Two kinds of geost<strong>at</strong>ionary s<strong>at</strong>ellites can be modelled. Traditional “bent-pipe” geost<strong>at</strong>ionary s<strong>at</strong>ellites are merely repe<strong>at</strong>ersin orbit– all packets received by such s<strong>at</strong>ellites on an uplink channel are piped through <strong>at</strong> RF frequencies to a correspondingdownlink, <strong>and</strong> the s<strong>at</strong>ellite node is not visible to routing protocols. Newer s<strong>at</strong>ellites will increasingly use baseb<strong>and</strong> processing,both to regener<strong>at</strong>e the digital signal <strong>and</strong> to perform fast packet switching on-board the spacecraft. In the simul<strong>at</strong>io<strong>ns</strong>, theses<strong>at</strong>ellites can be modelled more like traditional <strong>ns</strong> nodes with classifiers <strong>and</strong> routing agents.Previously, users could simul<strong>at</strong>e geost<strong>at</strong>ionary s<strong>at</strong>ellite links by simply simul<strong>at</strong>ing a long delay link using traditional <strong>ns</strong> links<strong>and</strong> nodes. <strong>The</strong> key enhancement of these s<strong>at</strong>ellite exte<strong>ns</strong>io<strong>ns</strong> with respect to geost<strong>at</strong>ionary s<strong>at</strong>ellites is the capability to170


Counter-rot<strong>at</strong>ing planescause rapid ‘‘crossseam’’ISL h<strong>and</strong>offsOverlap of coverage <strong>at</strong> the polesInterplane inters<strong>at</strong>ellitelinks (ISLs) are turned offAn ‘‘intraplane’’ ISLAn ‘‘interplane’’ ISLFigure 17.1: Example of a polar-orbiting LEO co<strong>ns</strong>tell<strong>at</strong>ion. This figure was gener<strong>at</strong>ed using the SaVi software package fromthe geometry center <strong>at</strong> the University of Minnesota.simul<strong>at</strong>e MAC protocols. Users can now define many terminals <strong>at</strong> different loc<strong>at</strong>io<strong>ns</strong> on the Earth’s surface <strong>and</strong> connect themto the same s<strong>at</strong>ellite uplink <strong>and</strong> downlink channels, <strong>and</strong> the propag<strong>at</strong>ion delays in the system (which are slightly different foreach user) are accur<strong>at</strong>ely modelled. In addition, the uplink <strong>and</strong> downlink channels can be defined differently (perhaps withdifferent b<strong>and</strong>widths or error models).17.1.2 Low-earth-orbiting s<strong>at</strong>ellitesPolar orbiting s<strong>at</strong>ellite systems, such as Iridium <strong>and</strong> the proposed Teledesic system, can be modelled in <strong>ns</strong>. In particular, thesimul<strong>at</strong>or supports the specific<strong>at</strong>ion of s<strong>at</strong>ellites th<strong>at</strong> orbit in purely circular planes, for which the neighboring planes are corot<strong>at</strong>ing.<strong>The</strong>re are other non-geost<strong>at</strong>ionary co<strong>ns</strong>tell<strong>at</strong>ion configur<strong>at</strong>io<strong>ns</strong> possible (e.g., Walker co<strong>ns</strong>tell<strong>at</strong>io<strong>ns</strong>)– the interesteduser may develop new co<strong>ns</strong>tell<strong>at</strong>ion classes to simul<strong>at</strong>e these other co<strong>ns</strong>tell<strong>at</strong>ion types. In particular, this would mainly requiredefining new inters<strong>at</strong>ellite link h<strong>and</strong>off procedures.<strong>The</strong> following are the parameters of s<strong>at</strong>ellite co<strong>ns</strong>tell<strong>at</strong>io<strong>ns</strong> th<strong>at</strong> can currently be simul<strong>at</strong>ed:• Basic co<strong>ns</strong>tell<strong>at</strong>ion definition Includes s<strong>at</strong>ellite altitude, number of s<strong>at</strong>ellites, number of planes, number of s<strong>at</strong>ellitesper plane.• Orbits Orbit inclin<strong>at</strong>ion can range continuously from 0 to 180 degrees (inclin<strong>at</strong>ion gre<strong>at</strong>er than 90 degrees correspondsto retrograde orbits). Orbit eccentricity is not modeled. Nodal precession is not modeled. Inters<strong>at</strong>ellite spacing within agiven plane is fixed. Rel<strong>at</strong>ive phasing between planes is fixed (although some systems may not control phasing betweenplanes).• Inters<strong>at</strong>ellite (ISL) links For polar orbiting co<strong>ns</strong>tell<strong>at</strong>io<strong>ns</strong>, intraplane, interplane, <strong>and</strong> crossseam ISLs can be defined.Intraplane ISLs exist between s<strong>at</strong>ellites in the same plane <strong>and</strong> are never deactiv<strong>at</strong>ed or h<strong>and</strong>ed off. Interplane ISLs existbetween s<strong>at</strong>ellites of neighboring co-rot<strong>at</strong>ing planes. <strong>The</strong>se links are deactiv<strong>at</strong>ed near the poles (above the “ISL l<strong>at</strong>itudethreshold” in the table) because the antenna pointing mechanism cannot track these links in the polar regio<strong>ns</strong>. Likeintraplane ISLs, interplane ISLs are never h<strong>and</strong>ed off. Crossseam ISLs may exist in a co<strong>ns</strong>tell<strong>at</strong>ion between s<strong>at</strong>ellites171


in counter-rot<strong>at</strong>ing planes (where the planes form a so-called “seam” in the topology). GEO ISLs can also be definedfor co<strong>ns</strong>tell<strong>at</strong>io<strong>ns</strong> of geost<strong>at</strong>ionary s<strong>at</strong>ellites.• Ground to s<strong>at</strong>ellite (GSL) links Multiple terminals can be connected to a single GSL s<strong>at</strong>ellite channel. GSL links forGEO s<strong>at</strong>ellites are st<strong>at</strong>ic, while GSL links for LEO channels are periodically h<strong>and</strong>ed off as described below.• Elev<strong>at</strong>ion mask <strong>The</strong> elev<strong>at</strong>ion angle above which a GSL link can be oper<strong>at</strong>ional. Currently, if the (LEO) s<strong>at</strong>elliteserving a terminal drops below the elev<strong>at</strong>ion mask, the terminal searches for a new s<strong>at</strong>ellite above the elev<strong>at</strong>ion mask.S<strong>at</strong>ellite terminals check for h<strong>and</strong>off opportunities according to a timeout interval specified by the user. Each terminaliniti<strong>at</strong>es h<strong>and</strong>offs asynchronously; it would be possible also to define a system in which each h<strong>and</strong>off occurssynchronously in the system.<strong>The</strong> following table lists parameters used for example simul<strong>at</strong>ion scripts of the Iridium 1 <strong>and</strong> Teledesic 2 systems.Iridium TeledesicAltitude 780 km 1375 kmPlanes 6 12S<strong>at</strong>ellites per plane 11 24Inclin<strong>at</strong>ion (deg) 86.4 84.7Interplane separ<strong>at</strong>ion (deg) 31.6 15Seam separ<strong>at</strong>ion (deg) 22 15Elev<strong>at</strong>ion mask (deg) 8.2 40Intraplane phasing yes yesInterplane phasing yes noISLs per s<strong>at</strong>ellite 4 8ISL b<strong>and</strong>width 25 Mb/s 155 Mb/sUp/downlink b<strong>and</strong>width 1.5 Mb/s 1.5 Mb/sCross-seam ISLs no yesISL l<strong>at</strong>itude threshold (deg) 60 60Table 17.1: Simul<strong>at</strong>ion parameters used for modeling a broadb<strong>and</strong> version of the Iridium system <strong>and</strong> the proposed 288-s<strong>at</strong>elliteTeledesic system. Both systems are examples of polar orbiting co<strong>ns</strong>tell<strong>at</strong>io<strong>ns</strong>.1 Aside from the link b<strong>and</strong>widths (Iridium is a narrowb<strong>and</strong> system only), these parameters are very close to wh<strong>at</strong> a broadb<strong>and</strong> version of the Iridiumsystem might look like.2 <strong>The</strong>se Teledesic co<strong>ns</strong>tell<strong>at</strong>ion parameters are subject to change; thanks to Marie-Jose Montpetit of Teledesic for providing tent<strong>at</strong>ive parameters as ofJanuary 1999. <strong>The</strong> link b<strong>and</strong>widths are not necessarily accur<strong>at</strong>e.172


ZRXo0 longitude <strong>at</strong>equ<strong>at</strong>orY17.2 Using the s<strong>at</strong>ellite exte<strong>ns</strong>io<strong>ns</strong>Figure 17.2: Spherical coordin<strong>at</strong>e system used by s<strong>at</strong>ellite nodes17.2.1 Nodes <strong>and</strong> node positio<strong>ns</strong><strong>The</strong>re are two basic kinds of s<strong>at</strong>ellite nodes: geost<strong>at</strong>ionary <strong>and</strong> non-geost<strong>at</strong>ionary s<strong>at</strong>ellite nodes. In addition, terminal nodescan be placed on the Earth’s surface. As is explained l<strong>at</strong>er in Section 17.3, each of these three different types of nodesis actually implemented with the same class S<strong>at</strong>Node object, but with different position, h<strong>and</strong>off manager, <strong>and</strong> linkobjects <strong>at</strong>tached. <strong>The</strong> position object keeps track of the s<strong>at</strong>ellite node’s loc<strong>at</strong>ion in the coordin<strong>at</strong>e system as a function of theelapsed simul<strong>at</strong>ion time. This position inform<strong>at</strong>ion is used to determine link propag<strong>at</strong>ion delays <strong>and</strong> appropri<strong>at</strong>e times forlink h<strong>and</strong>offs. Section 5.3 introduced the "node-config" utility used to prime the node gener<strong>at</strong>or for different types of s<strong>at</strong>ellitenodes.Figure 17.2 illustr<strong>at</strong>es the spherical coordin<strong>at</strong>e system, <strong>and</strong> the corresponding Cartesian coordin<strong>at</strong>e system. <strong>The</strong> coordin<strong>at</strong>esystem is centered <strong>at</strong> the Earth’s center, <strong>and</strong> the z axis coincides with the Earth’s axis of rot<strong>at</strong>ion. (R, θ, φ) =(6378km, 90 o , 0 o ) corresponds to 0 o longitude (prime meridian) on the equ<strong>at</strong>or.Specifically, there is one class of s<strong>at</strong>ellite node Class Node/S<strong>at</strong>Node, to which one of three types of Position objectsmay be <strong>at</strong>tached. Each S<strong>at</strong>Node <strong>and</strong> Position object is a split OTcl/C++ object, but most of the code resides in C++.<strong>The</strong> following types of position objects exist:• Position/S<strong>at</strong>/Term A terminal is specified by its l<strong>at</strong>itude <strong>and</strong> longitude. L<strong>at</strong>itude ranges from [−90, 90] <strong>and</strong>longitude ranges from [−180, 180], with neg<strong>at</strong>ive values corresponding to south <strong>and</strong> west, respectively. As simul<strong>at</strong>iontime evolves, the terminals move along with the Earth’s surface. <strong>The</strong> node gener<strong>at</strong>or can be used to cre<strong>at</strong>e a terminalwith an <strong>at</strong>tached position object as follows:$<strong>ns</strong> node-config -s<strong>at</strong>NodeType terminal \(other node config comm<strong>and</strong>s go here...)set n1 [$<strong>ns</strong> node]$n1 set-position $l<strong>at</strong> $lon; # in decimal degrees173


• Position/S<strong>at</strong>/Geo A geost<strong>at</strong>ionary s<strong>at</strong>ellite is specified by its longitude above the equ<strong>at</strong>or. As simul<strong>at</strong>ion timeevolves, the geost<strong>at</strong>ionary s<strong>at</strong>ellite moves through the coordin<strong>at</strong>e system with the same orbital period as th<strong>at</strong> of theEarth’s rot<strong>at</strong>ion. <strong>The</strong> longitude ranges from [−180, 180] degrees. As we describe further below, two flavors of geost<strong>at</strong>ionarynodes exist: “geo” (for processing s<strong>at</strong>ellites) <strong>and</strong> “geo-repe<strong>at</strong>er” (for bent-pipe s<strong>at</strong>ellites). <strong>The</strong> node gener<strong>at</strong>orcan be used to cre<strong>at</strong>e a geost<strong>at</strong>ionary s<strong>at</strong>ellite with an <strong>at</strong>tached position object as follows:$<strong>ns</strong> node-config -s<strong>at</strong>NodeType geo (or ‘‘geo-repe<strong>at</strong>er’’) \(other node config comm<strong>and</strong>s go here...)set n1 [$<strong>ns</strong> node]$n1 set-position $lon; # in decimal degrees• Position/S<strong>at</strong>/Polar A polar orbiting s<strong>at</strong>ellite has a purely circular orbit along a fixed plane in the coordin<strong>at</strong>esystem; the Earth rot<strong>at</strong>es underne<strong>at</strong>h this orbital plane, so there is both an east-west <strong>and</strong> a north-south component tothe track of a polar s<strong>at</strong>ellite’s footprint on the Earth’s surface. Strictly speaking, the polar position object can be usedto model the movement of any circular orbit in a fixed plane; we use the term “polar” here because we l<strong>at</strong>er use suchs<strong>at</strong>ellites to model polar-orbiting co<strong>ns</strong>tell<strong>at</strong>io<strong>ns</strong>.S<strong>at</strong>ellite orbits are usually specified by six parameters: altitude, semi-major axis, eccentricity, right asce<strong>ns</strong>ion of ascendingnode, inclin<strong>at</strong>ion, <strong>and</strong> time of perigee passage. <strong>The</strong> polar orbiting s<strong>at</strong>ellites in <strong>ns</strong> have purely circular orbits, sowe simplify the specific<strong>at</strong>ion of the orbits to include only three parameters: altitude, inclin<strong>at</strong>ion, <strong>and</strong> longitude, with afourth parameter alpha specifying initial position of the s<strong>at</strong>ellite in the orbit, as described below. Altitude is specifiedin kilometers above the Earth’s surface, <strong>and</strong> inclin<strong>at</strong>ion can range from [0, 180] degrees, with 90 corresponding to purepolar orbits <strong>and</strong> angles gre<strong>at</strong>er than 90 degrees corresponding to “retrograde” orbits. <strong>The</strong> ascending node refers to thepoint where the footprint of the s<strong>at</strong>ellite orbital track crosses the equ<strong>at</strong>or moving from south to north. In this simul<strong>at</strong>ionmodel, the parameter longitude of ascending node specifies the earth-centric longitude <strong>at</strong> which the s<strong>at</strong>ellite’s nadirpoint crosses the equ<strong>at</strong>or moving south to north. 3 Longitude of ascending node can range from [−180, 180] degrees.<strong>The</strong> fourth parameter, alpha, specifies the initial position of the s<strong>at</strong>ellite along this orbit, starting from the ascendingnode. For example, an alpha of 180 degrees indic<strong>at</strong>es th<strong>at</strong> the s<strong>at</strong>ellite is initially above the equ<strong>at</strong>or moving from northto south. Alpha can range from [0, 360] degrees. Finally, a fifth parameter, plane, is specified when cre<strong>at</strong>ing polars<strong>at</strong>ellite nodes– all s<strong>at</strong>ellites in the same plane are given the same plane index. <strong>The</strong> node gener<strong>at</strong>or used to cre<strong>at</strong>e apolar s<strong>at</strong>ellite with an <strong>at</strong>tached position object as follows:$<strong>ns</strong> node-config -s<strong>at</strong>NodeType polar \(other node config comm<strong>and</strong>s go here...)set n1 [$<strong>ns</strong> node]$n1 set-position $alt $inc $lon $alpha $plane17.2.2 S<strong>at</strong>ellite linksS<strong>at</strong>ellite links resemble wireless links, which are described in Chapter 16. Each s<strong>at</strong>ellite node has one or more s<strong>at</strong>ellitenetwork interface stacks, to which channels are connected to the physical layer object in the stack. Figure 17.3 illustr<strong>at</strong>es themajor components. S<strong>at</strong>ellite links differ from <strong>ns</strong> wireless links in two major respects: i) the tra<strong>ns</strong>mit <strong>and</strong> receive interfacesmust be connected to different channels, <strong>and</strong> ii) there is no ARP implement<strong>at</strong>ion. Currently, the Radio Propag<strong>at</strong>ion Model isa placeholder for users to add more detailed error models if so desired; the current code does not use a propag<strong>at</strong>ion model.Network interfaces can be added with the following i<strong>ns</strong>tproc of Class Node/S<strong>at</strong>Node:$node add-interface $type $ll $qtype $qlim $mac $mac_bw $phy3 Traditionally, the “right asce<strong>ns</strong>ion” of the ascending node is specified for s<strong>at</strong>ellite orbits– the right asce<strong>ns</strong>ion corresponds to the celestial longitude. Inour case, we do not care about the orient<strong>at</strong>ion in a celestial coordin<strong>at</strong>e system, so we specify the earth-centric longitude i<strong>ns</strong>tead.174


LLIFqMACPhy_txPhy_rxRadioPropag<strong>at</strong>ionModelChannelChannelFigure 17.3: Main components of a s<strong>at</strong>ellite network interface<strong>The</strong> add-interface i<strong>ns</strong>tproc retur<strong>ns</strong> an index value th<strong>at</strong> can be used to access the network interface stack l<strong>at</strong>er in thesimul<strong>at</strong>ion. By convention, the first interface cre<strong>at</strong>ed on a node is <strong>at</strong>tached to the uplink <strong>and</strong> downlink channels of a s<strong>at</strong>elliteor terminal. <strong>The</strong> following parameters must be provided:• type: <strong>The</strong> following link types can be indic<strong>at</strong>ed: geo or polar for links from a terminal to a geo or polar s<strong>at</strong>ellite,respectively, gsl <strong>and</strong> gsl-repe<strong>at</strong>er for links from a s<strong>at</strong>ellite to a terminal, <strong>and</strong> intraplane, interplane,<strong>and</strong> crossseam ISLs. <strong>The</strong> type field is used internally in the simul<strong>at</strong>or to identify the different types of links, butstructurally they are all very similar.• ll: <strong>The</strong> link layer type (class LL/S<strong>at</strong> is currently the only one defined).• qtype: <strong>The</strong> queue type (e.g., class Queue/DropTail). Any queue type may be used– however, if additionalparameters beyond the length of the queue are needed, then this i<strong>ns</strong>tproc may need to be modified to include morearguments.• qlim: <strong>The</strong> length of the interface queue, in packets.• mac: <strong>The</strong> MAC type. Currently, two types are defined: class Mac/S<strong>at</strong>– a basic MAC for links with only onereceiver (i.e., it does not do collision detection), <strong>and</strong> Class Mac/S<strong>at</strong>/U<strong>ns</strong>lottedAloha– an implement<strong>at</strong>ion ofu<strong>ns</strong>lotted Aloha.• mac_bw: <strong>The</strong> b<strong>and</strong>width of the link is set by this parameter, which controls the tra<strong>ns</strong>mission time how fast the MACsends. <strong>The</strong> packet size used to calcul<strong>at</strong>e the tra<strong>ns</strong>mission time is the sum of the values size() in the common packetheader <strong>and</strong> LINK_HDRSIZE, which is the size of any link layer headers. <strong>The</strong> default value for LINK_HDRSIZE is 16bytes (settable in s<strong>at</strong>link.h). <strong>The</strong> tra<strong>ns</strong>mission time is encoded in the packet header for use <strong>at</strong> the receive MAC (tosimul<strong>at</strong>e waiting for a whole packet to arrive).• phy: <strong>The</strong> physical layer– currently two Phys (Class Phy/S<strong>at</strong> <strong>and</strong> Class Phy/Repe<strong>at</strong>er) are defined. <strong>The</strong>class Phy/S<strong>at</strong> just pass the inform<strong>at</strong>ion up <strong>and</strong> down the stack– as in the wireless code described in Chapter 16, aradio propag<strong>at</strong>ion model could be <strong>at</strong>tached <strong>at</strong> this point. <strong>The</strong> class Phy/Repe<strong>at</strong>er pipes any packets received on areceive interface straight through to a tra<strong>ns</strong>mit interface.An ISL can be added between two nodes using the following i<strong>ns</strong>tproc:175


$<strong>ns</strong> add-isl $ltype $node1 $node2 $bw $qtype $qlimThis cre<strong>at</strong>es two channels (of type Channel/S<strong>at</strong>), <strong>and</strong> appropri<strong>at</strong>e network interfaces on both nodes, <strong>and</strong> <strong>at</strong>taches thechannels to the network interfaces. <strong>The</strong> b<strong>and</strong>width of the link is set to bw. <strong>The</strong> linktype (ltype) must be specified as eitherintraplane, interplane, or crossseam.A GSL involves adding network interfaces <strong>and</strong> a channel on board the s<strong>at</strong>ellite (this is typically done using the wrappermethods described in the next paragraph), <strong>and</strong> then defining the correct interfaces on the terrestrial node <strong>and</strong> <strong>at</strong>taching themto the s<strong>at</strong>ellite link, as follows:$node add-gsl $type $ll $qtype $qlim $mac $bw_up $phy \[$node_s<strong>at</strong>ellite set downlink_] [$node_s<strong>at</strong>ellite set uplink_]Here, the type must be either geo or polar, <strong>and</strong> we make use of the downlink_ <strong>and</strong> uplink_ i<strong>ns</strong>tvars of the s<strong>at</strong>ellite;therefore, the s<strong>at</strong>ellite’s uplink <strong>and</strong> downlink must be cre<strong>at</strong>ed before this i<strong>ns</strong>tproc is called.By default, the node gener<strong>at</strong>or for s<strong>at</strong>ellite nodes (described in Section 5.3) will cre<strong>at</strong>e nodes of a given type, give them anuplink <strong>and</strong> downlink interface, <strong>and</strong> cre<strong>at</strong>e <strong>and</strong> <strong>at</strong>tach an (initial) uplink <strong>and</strong> downlink channel, based on the interface optio<strong>ns</strong>specified.17.2.3 H<strong>and</strong>offsS<strong>at</strong>ellite h<strong>and</strong>off modelling is a key component of LEO s<strong>at</strong>ellite network simul<strong>at</strong>io<strong>ns</strong>. It is difficult to predict exactly howh<strong>and</strong>offs will occur in future LEO systems because the subject is not well tre<strong>at</strong>ed in the liter<strong>at</strong>ure. In these s<strong>at</strong>ellite exte<strong>ns</strong>io<strong>ns</strong>,we establish certain criteria for h<strong>and</strong>offs, <strong>and</strong> allow nodes to independently monitor for situ<strong>at</strong>io<strong>ns</strong> th<strong>at</strong> require a h<strong>and</strong>off. Analtern<strong>at</strong>ive would be to have all h<strong>and</strong>off events synchronized across the entire simul<strong>at</strong>ion– it would not be difficult to changethe simul<strong>at</strong>or to work in such a manner.<strong>The</strong>re are no link h<strong>and</strong>offs involving geost<strong>at</strong>ionary s<strong>at</strong>ellites, but there are two types of links to polar orbiting s<strong>at</strong>ellites th<strong>at</strong>must be h<strong>and</strong>ed off: GSLs to polar s<strong>at</strong>ellites, <strong>and</strong> crossseam ISLs. A third type of link, interplane ISLs, are not h<strong>and</strong>ed off butare deactiv<strong>at</strong>ed <strong>at</strong> high l<strong>at</strong>itudes as we describe below.Each terminal connected to a polar orbiting s<strong>at</strong>ellite ru<strong>ns</strong> a timer th<strong>at</strong>, upon expiry, causes the H<strong>and</strong>offManager to checkwhether the current s<strong>at</strong>ellite has fallen below the elev<strong>at</strong>ion mask of the terminal. If so, the h<strong>and</strong>off manager detaches theterminal from th<strong>at</strong> s<strong>at</strong>ellite’s up <strong>and</strong> down links, <strong>and</strong> searches through the linked list of s<strong>at</strong>ellite nodes for another possibles<strong>at</strong>ellite. First, the “next” s<strong>at</strong>ellite in the current orbital plane is checked– a pointer to this s<strong>at</strong>ellite is stored in the Positionobject of each polar s<strong>at</strong>ellite node <strong>and</strong> is set during simul<strong>at</strong>ion configur<strong>at</strong>ion using the Node/S<strong>at</strong>Node i<strong>ns</strong>tproc “$nodeset_next $next_node.” If the next s<strong>at</strong>ellite is not suitable, the h<strong>and</strong>off manager searches through the remaining s<strong>at</strong>ellites.If it finds a suitable polar s<strong>at</strong>elite, it connects its network interfaces to th<strong>at</strong> s<strong>at</strong>ellite’s uplink <strong>and</strong> downlink channels, <strong>and</strong>restarts the h<strong>and</strong>off timer. If it does not find a suitable s<strong>at</strong>ellite, it restarts the timer <strong>and</strong> tries again l<strong>at</strong>er. If any link changesoccur, the routing agent is notified.<strong>The</strong> elev<strong>at</strong>ion mask <strong>and</strong> h<strong>and</strong>off timer interval are settable via OTcl:H<strong>and</strong>offManager/Term set elev<strong>at</strong>ion_mask_ 10; # degreesH<strong>and</strong>offManager/Term set term_h<strong>and</strong>off_int_ 10; # secondsIn addition, h<strong>and</strong>offs may be r<strong>and</strong>omized to avoid phase effects by setting the following variable:H<strong>and</strong>offManager set h<strong>and</strong>off_r<strong>and</strong>omiz<strong>at</strong>ion_ 0; # 0 is false, 1 is true176


If h<strong>and</strong>off_r<strong>and</strong>omiz<strong>at</strong>ion_ is true, then the next h<strong>and</strong>off interval is a r<strong>and</strong>om vari<strong>at</strong>e picked from a uniform distributionacross (0.5 ∗ term_h<strong>and</strong>off_int_, 1.5 ∗ term_h<strong>and</strong>off_int_).Crossseam ISLs are the only type of ISLs th<strong>at</strong> are h<strong>and</strong>ed off. <strong>The</strong> criteria for h<strong>and</strong>ing off a crossseam ISL is whetheror not there exists a s<strong>at</strong>ellite in the neighboring plane th<strong>at</strong> is closer to the given s<strong>at</strong>ellite than the one to which it is currentlyconnected. Again, a h<strong>and</strong>off timer running within the h<strong>and</strong>off manager on the polar s<strong>at</strong>ellite determines when the co<strong>ns</strong>tell<strong>at</strong>ionis checked for h<strong>and</strong>off opportunities. Crossseam ISL h<strong>and</strong>offs are initi<strong>at</strong>ed by s<strong>at</strong>ellites in the lower-numbered plane of thetwo. It is therefore possible for a tra<strong>ns</strong>ient condition to arise in which a polar s<strong>at</strong>ellite has two crossseam ISLs (to differents<strong>at</strong>ellites). <strong>The</strong> s<strong>at</strong>ellite h<strong>and</strong>off interval is again settable from OTcl <strong>and</strong> may also be r<strong>and</strong>omized:H<strong>and</strong>offManager/S<strong>at</strong> set s<strong>at</strong>_h<strong>and</strong>off_int_ 10; # secondsInterplane <strong>and</strong> crossseam ISLs are deactiv<strong>at</strong>ed near the poles, because the pointing requirements for the links are too severeas the s<strong>at</strong>ellite draw close to one another. Shutdown of these links is governed by a parameter:H<strong>and</strong>offManager/S<strong>at</strong> set l<strong>at</strong>itude_threshold_ 70; # degrees<strong>The</strong> values for this parameter in the example scripts are specul<strong>at</strong>ive; the exact value is dependent upon the s<strong>at</strong>ellite hardware.<strong>The</strong> h<strong>and</strong>off manager checks the l<strong>at</strong>itude of itself <strong>and</strong> its peer s<strong>at</strong>ellite upon a h<strong>and</strong>off timeout; if either or both of the s<strong>at</strong>ellitesis above l<strong>at</strong>itude_threshold_ degrees l<strong>at</strong>itude (north or south), the link is deactiv<strong>at</strong>ed until both s<strong>at</strong>ellites drop belowthis threshold.Finally, if crossseam ISLs exist, there are certain situ<strong>at</strong>io<strong>ns</strong> in which the s<strong>at</strong>ellites draw too close to one another in the midl<strong>at</strong>itudes(if the orbits are not close to being pure polar orbits). We check for the occurence of this orbital overlap with thefollowing parameter:H<strong>and</strong>offManager/S<strong>at</strong> set longitude_threshold_ 10; # degreesAgain, the values for this parameter in the example scripts are specul<strong>at</strong>ive. If the two s<strong>at</strong>ellites are closer together in longitudethan longitude_threshold_ degrees, the link between them is deactiv<strong>at</strong>ed. This parameter is disabled (set to 0) bydefault– all defaults for s<strong>at</strong>ellite-rel<strong>at</strong>ed bound variables can be found in ~<strong>ns</strong>/tcl/lib/<strong>ns</strong>-s<strong>at</strong>.tcl.17.2.4 Routing<strong>The</strong> current st<strong>at</strong>us of routing is th<strong>at</strong> it is incomplete. Ideally, one should be able to run all existing <strong>ns</strong> routing protocols overs<strong>at</strong>ellite links. However, many of the existing routing protocols implemented in OTcl require th<strong>at</strong> the conventional <strong>ns</strong> links beused. Contributio<strong>ns</strong> in this area are welcome, but unfortun<strong>at</strong>ely it is not a trivial change.With th<strong>at</strong> being said, the current routing implement<strong>at</strong>ion is similar to Session routing described in Chapter 29, except th<strong>at</strong>it is implemented entirely in C++. Upon each topology change, a centralized routing genie determines the global networktopology, computes new routes for all nodes, <strong>and</strong> uses the routes to build a forwarding table on each node. Currently, theslot table is kept by a routing agent on each node, <strong>and</strong> packets not destined for agents on the node are sent by default to thisrouting agent. For each destin<strong>at</strong>ion for which the node has a route, the forwarding table contai<strong>ns</strong> a pointer to the head of thecorresponding outgoing link. As noted in Chapter 29, the user is cautioned th<strong>at</strong> this type of centralized routing can lead tominor causality viol<strong>at</strong>io<strong>ns</strong>.<strong>The</strong> routing genie is a class S<strong>at</strong>RouteObject <strong>and</strong> is cre<strong>at</strong>ed <strong>and</strong> invoked with the following OTcl comm<strong>and</strong>s:set s<strong>at</strong>routeobject_ [new S<strong>at</strong>RouteObject]177


$s<strong>at</strong>routeobject_ compute_routeswhere the call to compute_routes is performed after all of the links <strong>and</strong> nodes in the simul<strong>at</strong>or have been i<strong>ns</strong>tanti<strong>at</strong>ed.Like the Scheduler, there is one i<strong>ns</strong>tance of a S<strong>at</strong>RouteObject in the simul<strong>at</strong>ion, <strong>and</strong> it is accessed by mea<strong>ns</strong> of an i<strong>ns</strong>tancevariable in C++. For example, the call to recompute routes after a topology change is:S<strong>at</strong>RouteObject::i<strong>ns</strong>tance().recompute();Despite the current use of centralized routing, the design of having a routing agent on each node was mainly done withdistributed routing in mind. Routing packets can be sent to port 255 of each node. <strong>The</strong> key to distributed routing workingcorrectly is for the routing agent to be able to determine from which link a packet arrived. This is accomplished by the inclusionof a class NetworkInterface object in each link, which uniquely labels the link on which the packet arrived. Ahelper function NsObject* intf_to_target(int label) can be used to return the head of the link correspondingto a given label. <strong>The</strong> use of routing agents parallels th<strong>at</strong> of the mobility exte<strong>ns</strong>io<strong>ns</strong>, <strong>and</strong> the interested reader can turn to thoseexamples to see how to implement distributed routing protocols in this framework.<strong>The</strong> shortest-p<strong>at</strong>h route comput<strong>at</strong>io<strong>ns</strong> use the current propag<strong>at</strong>ion delay of a link as the cost metric. It is possible to computeroutes using only the hop count <strong>and</strong> not the propag<strong>at</strong>ion delays; in order to do so, set the following default variable to "false":S<strong>at</strong>RouteObject set metric_delay_ "true"Finally, for very large topologies (such as the Teledesic example), the centralized routing code will produce a very slowruntime because it executes an all-pairs shortest p<strong>at</strong>h algorithm upon each topology change even if there is no d<strong>at</strong>a currentlybeing sent. To speed up simul<strong>at</strong>io<strong>ns</strong> in which there is not much d<strong>at</strong>a tra<strong>ns</strong>fer but there are lots of s<strong>at</strong>ellites <strong>and</strong> ISLs, one c<strong>and</strong>isable h<strong>and</strong>off-driven <strong>and</strong> enable d<strong>at</strong>a-driven route comput<strong>at</strong>io<strong>ns</strong>. With d<strong>at</strong>a-driven comput<strong>at</strong>io<strong>ns</strong>, routes are computed onlywhen there is a packet to send, <strong>and</strong> furthermore, a single-source shortest-p<strong>at</strong>h algorithm (only for the node with a packet tosend) is executed i<strong>ns</strong>tead of an all-pairs shortest p<strong>at</strong>h algorithm. <strong>The</strong> following OTcl variable can configure this option (whichis set to "false" by default):S<strong>at</strong>RouteObject set d<strong>at</strong>a_driven_comput<strong>at</strong>ion_ "false"17.2.5 Trace supportTracefiles using s<strong>at</strong>ellite nodes <strong>and</strong> links are very similar to conventional <strong>ns</strong> tracing described in Chapter 26. Special S<strong>at</strong>Traceobjects (class S<strong>at</strong>Trace derives from class Trace) are used to log the geographic l<strong>at</strong>itude <strong>and</strong> longitude of the nodelogging the trace (in the case of a s<strong>at</strong>ellite node, the l<strong>at</strong>itude <strong>and</strong> longitude correspond to the nadir point of the s<strong>at</strong>ellite).For example, a packet on a link from node 66 to node 26 might normally be logged as:+ 1.0000 66 26 cbr 210 ------- 0 66.0 67.0 0 0but in the s<strong>at</strong>ellite simul<strong>at</strong>ion, the position inform<strong>at</strong>ion is appended:+ 1.0000 66 26 cbr 210 ------- 0 66.0 67.0 0 0 37.90 -122.30 48.90 -120.94In this case, node 66 is <strong>at</strong> l<strong>at</strong>itude 37.90 degrees, longitude -122.30 degrees, while node 26 is a LEO s<strong>at</strong>ellite whose subs<strong>at</strong>ellitepoint is <strong>at</strong> 48.90 degrees l<strong>at</strong>itude, -120.94 degrees longitude (neg<strong>at</strong>ive l<strong>at</strong>itude corresponds to south, while neg<strong>at</strong>ive longitudecorresponds to west).178


One addition is the Class Trace/S<strong>at</strong>/Error, which traces any packets th<strong>at</strong> are errored by an error model. <strong>The</strong> errortrace logs packets dropped due to errors as follows, for example:e 1.2404 12 13 cbr 210 ------- 0 12.0 13.0 0 0 -0.00 10.20 -0.00 -10.00It may happen th<strong>at</strong> a s<strong>at</strong>ellite node gener<strong>at</strong>es a packet th<strong>at</strong> it cannot forward (such as in s<strong>at</strong>-mixed.tcl). This will show up as adrop in the tracefile with a destin<strong>at</strong>ion field set to -2, <strong>and</strong> the coordin<strong>at</strong>es set to -999.00:d 848.0000 14 -2 cbr 210 ------- 1 14.0 15.0 6 21 0.00 10.00 -999.00 -999.00This indic<strong>at</strong>es th<strong>at</strong> node 14, in trying to send a packet to node 15, could not find an available route.To enable tracing of all s<strong>at</strong>ellite links in the simul<strong>at</strong>or, use the following comm<strong>and</strong>s before i<strong>ns</strong>tanti<strong>at</strong>ing nodes <strong>and</strong> links:set f [open out.tr w]$<strong>ns</strong> trace-all $f<strong>The</strong>n use the following line after all node <strong>and</strong> link cre<strong>at</strong>ion (<strong>and</strong> all error model i<strong>ns</strong>ertion, if any) to enable tracing of alls<strong>at</strong>ellite links:$<strong>ns</strong> trace-all-s<strong>at</strong>links $fSpecifically, this will put tracing around the link layer queues in all s<strong>at</strong>ellite links, <strong>and</strong> will put a receive trace between themac <strong>and</strong> the link layer for received packets. To enable tracing only on a specific link on a specific node, one may use thecomm<strong>and</strong>:$node trace-inlink-queue $f $i$node trace-outlink-queue $f $iwhere i is the index of the interface to be traced.<strong>The</strong> implement<strong>at</strong>io<strong>ns</strong> of the s<strong>at</strong>ellite trace objects can be found in ~<strong>ns</strong>/tcl/lib/<strong>ns</strong>-s<strong>at</strong>.tcl <strong>and</strong> ~<strong>ns</strong>/s<strong>at</strong>trace.{cc,h}.17.2.6 Error models<strong>ns</strong> error models are described in Chapter 13. <strong>The</strong>se error models can be set to cause packets to be errored according to variousprobability distributio<strong>ns</strong>. <strong>The</strong>se error models are simple <strong>and</strong> don’t necessarily correspond to wh<strong>at</strong> would be experienced onan actual s<strong>at</strong>ellite channel (particularly a LEO channel). Users are free to define more sophistic<strong>at</strong>ed error models th<strong>at</strong> moreclosely m<strong>at</strong>ch a particular s<strong>at</strong>ellite environment.<strong>The</strong> following code provides an example of how to add an error model to a link:set em_ [new ErrorModel]$em_ unit pkt$em_ set r<strong>at</strong>e_ 0.02$em_ ranvar [new R<strong>and</strong>omVariable/Uniform]$node interface-errormodel $em_179


This will add an error model to the receive p<strong>at</strong>h of the first interface cre<strong>at</strong>ed on node $node (specifically, between the MAC<strong>and</strong> link layer)– this first interface generally corresponds to the uplink <strong>and</strong> downlink interface for a s<strong>at</strong>ellite or a terminal (ifonly one uplink <strong>and</strong>/or downlink exists). To add the error model to a different stack (indexed by i), use the following code:$node interface-errormodel $em_ $i17.2.7 Other configur<strong>at</strong>ion optio<strong>ns</strong>Given an initial configur<strong>at</strong>ion of s<strong>at</strong>ellites specified for time 0, it is possible to start the s<strong>at</strong>ellite configur<strong>at</strong>ion from any arbitrarypoint in time through the use of the time_advance_ parameter (this is really only useful for LEO simul<strong>at</strong>io<strong>ns</strong>). Duringthe simul<strong>at</strong>ion run, this will set the position of the object to the position <strong>at</strong> time Scheduler::i<strong>ns</strong>tance().clock +time_advance_ seconds.Position/S<strong>at</strong> set time_advance_ 0; # seconds17.2.8 nam supportnam is not currently supported. Addition of nam for s<strong>at</strong>ellite is open to interested contributors.17.2.9 Integr<strong>at</strong>ion with wired <strong>and</strong> wireless codeRecently (November 2001), support has been added to connect traditional OTcl-based wired nodes with the s<strong>at</strong>ellite nodes.This section describes the capabilities <strong>and</strong> limit<strong>at</strong>io<strong>ns</strong> of th<strong>at</strong> code.<strong>The</strong> s<strong>at</strong>ellite code (<strong>and</strong> the wireless code) normally performs all routing in C++, while the traditional <strong>ns</strong> code uses a mix ofOTcl <strong>and</strong> C++ code. For backward comp<strong>at</strong>ibility reaso<strong>ns</strong>, it is difficult to fully integr<strong>at</strong>e both the wired <strong>and</strong> wireless code.<strong>The</strong> str<strong>at</strong>egy for integr<strong>at</strong>ing wireless <strong>and</strong> wired code has been to define a special g<strong>at</strong>eway node (called a "basest<strong>at</strong>ion"), touse hierarchial routing, <strong>and</strong> to loc<strong>at</strong>e a single basest<strong>at</strong>ion node in the wireless network with a network stack loc<strong>at</strong>ed in boththe wireless <strong>and</strong> the wired subnet. Because routing is not fully integr<strong>at</strong>ed, the topology of the simul<strong>at</strong>ion is limited to onlyone g<strong>at</strong>eway node per wireless subnet (i.e., a packet cannot enter the wireless network from one wired g<strong>at</strong>eway <strong>and</strong> leave viaanother).<strong>The</strong> s<strong>at</strong>ellite/wired code integr<strong>at</strong>ion takes a different str<strong>at</strong>egy. By selecting the node configur<strong>at</strong>ion $<strong>ns</strong> node-config-wiredRouting ON option, the C++ routing in the s<strong>at</strong>ellite code is turned off, <strong>and</strong> i<strong>ns</strong>tead, all s<strong>at</strong>ellite topology changeslead to upcalls into the OTcl code. As a result, the link_ array in OTcl is manipul<strong>at</strong>ed according to all topology changes,<strong>and</strong> OTcl-based routing can occur. <strong>The</strong> penalty for doing this is a much longer execution time for larger simul<strong>at</strong>io<strong>ns</strong> (such asTeledesic), but for smaller simul<strong>at</strong>io<strong>ns</strong>, the difference is not as noticeable.An example script detailing the use of this new option is shown in ~<strong>ns</strong>/tcl/ex/s<strong>at</strong>-wired.tcl, <strong>and</strong> a similar test in the s<strong>at</strong>ellitetest suite exercises this code. Additionally, all of the s<strong>at</strong>ellite example scripts in ~<strong>ns</strong>/tcl/ex directory can be converted to OTclrouting by using the $<strong>ns</strong> node-config -wiredRouting ON option. However, there are a few cave<strong>at</strong>s:• <strong>The</strong> wired routing option for s<strong>at</strong>ellite has only been tested with (the default) st<strong>at</strong>ic routing: $<strong>ns</strong> rtProto St<strong>at</strong>ic.<strong>The</strong> code triggers a global routing table upd<strong>at</strong>e upon any s<strong>at</strong>ellite topology change.• <strong>The</strong> option d<strong>at</strong>a_driven_comput<strong>at</strong>ion_ can not be set to “true” when wiredRouting is ON. Note th<strong>at</strong> the enablingor disabling of d<strong>at</strong>a_driven_comput<strong>at</strong>ion_ can give subtle differences in simul<strong>at</strong>ion output since routes180


are computed <strong>at</strong> different times (while propag<strong>at</strong>ion delays are continuously changing). This effect can be seen bytoggling this parameter in the Iridium example script ~<strong>ns</strong>/tcl/ex/s<strong>at</strong>-iridium.tcl.• In the trace file, when a packet is dropped due to “no route to host” (such as when there is a topology change), the tracelooks a bit different depending on whether wiredRouting is turned OFF or ON. In the former case, there is one line perdrop, with the destin<strong>at</strong>ion labelled as “-2”. In the l<strong>at</strong>ter case, there are three events (enque “+”, deque “-”, <strong>and</strong> drop “d”)corresponding to the same packet, <strong>and</strong> the destin<strong>at</strong>ion is shown as “-1”.• In rare cases, there may be warning messages during the execution indic<strong>at</strong>ing “node out of range.” This can occur if anode becomes disconnected in the topology <strong>and</strong> then another node tries to send a packet to it. For example, try enablingwiredRouting in the file ~<strong>ns</strong>/tcl/ex/s<strong>at</strong>-mixed.tcl. This occurs because the routing table is dynamically sized upontopology change, <strong>and</strong> if a node becomes disconnected it may not have any entries i<strong>ns</strong>erted in the routing table (<strong>and</strong>hence the routing table is not grown to accommod<strong>at</strong>e its node number). This warning should not affect actual traceoutput.• <strong>The</strong>re has been no <strong>at</strong>tempt to interoper<strong>at</strong>e with wireless or mobile-IP code.17.2.10 Example scriptsExample scripts can be found in the ~<strong>ns</strong>/tcl/ex directory, including:• s<strong>at</strong>-mixed.tcl A simul<strong>at</strong>ion with a mixture of polar <strong>and</strong> geost<strong>at</strong>ionary s<strong>at</strong>ellites.• s<strong>at</strong>-wired.tcl Similar to the previous script, but shows how to connect wired nodes to a s<strong>at</strong>ellite simul<strong>at</strong>ion.• s<strong>at</strong>-repe<strong>at</strong>er.tcl Demo<strong>ns</strong>tr<strong>at</strong>es the use of a simple bent-pipe geost<strong>at</strong>ionary s<strong>at</strong>ellite, <strong>and</strong> also error models.• s<strong>at</strong>-aloha.tcl Simul<strong>at</strong>es one hundred terminals in a mesh-VSAT configur<strong>at</strong>ion using an u<strong>ns</strong>lotted Aloha MACprotocol with a “bent-pipe” geost<strong>at</strong>ionary s<strong>at</strong>ellite. Terminals listen to their own tra<strong>ns</strong>missio<strong>ns</strong> (after a delay), <strong>and</strong> ifthey do not successfully receive their own packet within a timeout interval, they perform exponential backoff <strong>and</strong> thenretra<strong>ns</strong>mit the packet. Three variants exist: basic, basic_tracing, <strong>and</strong> poisson. <strong>The</strong>se variants are describedfurther in the header comments of the script.• s<strong>at</strong>-iridium.tcl Simul<strong>at</strong>es a broadb<strong>and</strong> LEO co<strong>ns</strong>tell<strong>at</strong>ion with parameters similar to th<strong>at</strong> of the Iridium co<strong>ns</strong>tell<strong>at</strong>ion(with supporting scripts s<strong>at</strong>-iridium-links.tcl, s<strong>at</strong>-iridium-linkswithcross.tcl, <strong>and</strong>s<strong>at</strong>-iridium-nodes.tcl).• s<strong>at</strong>-teledesic.tcl Simul<strong>at</strong>es a broadb<strong>and</strong> LEO co<strong>ns</strong>tell<strong>at</strong>ion with parameters similar to those proposed for the288 s<strong>at</strong>ellite Teledesic co<strong>ns</strong>tell<strong>at</strong>ion (with supporting scripts s<strong>at</strong>-teledesic-links.tcl <strong>and</strong> s<strong>at</strong>-teledesic-nodes.tclIn addition, there is a test suite script th<strong>at</strong> tries to exercise a lot of fe<strong>at</strong>ures simultaneously, it can be found <strong>at</strong> ~<strong>ns</strong>/tcl/test/testsuite-s<strong>at</strong>.tcl.17.3 Implement<strong>at</strong>ion<strong>The</strong> code for the implement<strong>at</strong>ion of s<strong>at</strong>ellite exte<strong>ns</strong>io<strong>ns</strong> can be found in ~<strong>ns</strong>/{s<strong>at</strong>.h, s<strong>at</strong>h<strong>and</strong>off.{cc,h}, s<strong>at</strong>link.{cc,h}, s<strong>at</strong>node.{cc,h},s<strong>at</strong>position.{cc,h}, s<strong>at</strong>route.{cc,h}, s<strong>at</strong>trace.{cc,h}}, <strong>and</strong> ~<strong>ns</strong>/tcl/lib/<strong>ns</strong>-s<strong>at</strong>.tcl. Almost all of the mechanism isimplemented in C++.In this section, we focus on some of the key components of the implement<strong>at</strong>ion; namely, the use of linked lists, the nodestructure, <strong>and</strong> a detailed look <strong>at</strong> the s<strong>at</strong>ellite link structure.181


lh_firstnameobj‘‘name’’ is the name of the structure containing the list head‘‘lh_first’’ is a pointer of type *obj, initialized to NULL‘‘lh_next’’ is a pointer of type *obj‘‘lh_prev’’ (of type **obj) is a pointer to the previous lh_nextobjobjlh_nextlh_prevlh_nextlh_prevlh_nextlh_prevNULLFigure 17.4: Linked list implement<strong>at</strong>ion in <strong>ns</strong>.17.3.1 Use of linked lists<strong>The</strong>re are a number of linked lists used heavily in the implement<strong>at</strong>ion:• class Node maintai<strong>ns</strong> a (st<strong>at</strong>ic) list of all objects of class Node in the simul<strong>at</strong>or. <strong>The</strong> variable Node::nodehead_stores the head of the list. <strong>The</strong> linked list of nodes is used for centralized routing, for finding s<strong>at</strong>ellites to h<strong>and</strong> off to,<strong>and</strong> for tracing.• class Node maintai<strong>ns</strong> a list of all (s<strong>at</strong>ellite) links on the node. Specifically, the list is a list of objects of classLinkHead. <strong>The</strong> variable linklisthead_ stores the head of the list. <strong>The</strong> linked list of LinkHeads is used forchecking whether or not to h<strong>and</strong>off links, <strong>and</strong> to discover topology adjacencies.• class Channel maintai<strong>ns</strong> a list of all objects of class Phy on the channel. <strong>The</strong> head of the list is stored in thevariable if_head_. This list is used to determine the set of interfaces on a channel th<strong>at</strong> should receive a copy of apacket.Figure 17.4 provides a schem<strong>at</strong>ic of how the linked list is organized. Each object in the list is linked through a “LINK_ENTRY”th<strong>at</strong> is a protected member of the class. This entry contai<strong>ns</strong> a pointer to the next item in the list <strong>and</strong> also a pointer to the addressof the previous “next” pointer in the preceding object. Various macros found in ~<strong>ns</strong>/list.h can be used to manipul<strong>at</strong>e the list;the implement<strong>at</strong>ion of linked-lists in <strong>ns</strong> is similar to the queue implement<strong>at</strong>ion found in some variants of BSD UNIX.17.3.2 Node structureFigure 17.5 is a schem<strong>at</strong>ic of the main components of a S<strong>at</strong>Node. <strong>The</strong> structure bears resemblance to the MobileNode inthe wireless exte<strong>ns</strong>io<strong>ns</strong>, but there are several differences. Like all <strong>ns</strong> nodes, the S<strong>at</strong>Node has an “entry” point to a series ofclassifiers. <strong>The</strong> address classifier contai<strong>ns</strong> a slot table for forwarding packets to foreign nodes, but since OTcl routing is notused, all packets not destined for this node (<strong>and</strong> hence forwarded to the port classifier), are sent to the default target, whichpoints to a routing agent. Packets destined on the node for port 255 are classified as routing packets <strong>and</strong> are also forwarded tothe routing agent.Each node contai<strong>ns</strong> one or more “network stacks” th<strong>at</strong> include a generic S<strong>at</strong>LinkHead <strong>at</strong> the entry point of the link. <strong>The</strong>S<strong>at</strong>LinkHead is intended to serve as an API to get <strong>at</strong> other objects in the link structure, so it contai<strong>ns</strong> a number of pointers(although the API here has not been finalized). Packets leaving the network stack are sent to the node’s entry. An importantfe<strong>at</strong>ure is th<strong>at</strong> each packet leaving a network stack has its iface_ field in the common packet header coded with the uniqueNetworkInterface index corresponding to the link. This value can be used to support distributed routing as describedbelow.<strong>The</strong> base class routing agent is class S<strong>at</strong>RouteAgent; it can be used in conjunction with centralized routing. S<strong>at</strong>RouteAgentscontain a forwarding table th<strong>at</strong> resolves a packet’s address to a particular LinkHead target– it is the job of the S<strong>at</strong>RouteObject182


entry_addrdemuxIP addressportdemuxdefaulttarget_255Src/SinkRTagentclass S<strong>at</strong>Node : public NodeS<strong>at</strong>PositionLinkH<strong>and</strong>offMgrS<strong>at</strong>TraceList of pointers:node_head nodehead_linklist_head linklisthead_Channel* uplink_Channel* downlink_S<strong>at</strong>LinkHeadOther linkobjects...S<strong>at</strong>LinkHeadOther linkobjectsFigure 17.5: Structure of class S<strong>at</strong>Node.to popul<strong>at</strong>e this table correctly. <strong>The</strong> S<strong>at</strong>RouteAgent popul<strong>at</strong>es certain fields in the header <strong>and</strong> then sends the packet down tothe appropr<strong>at</strong>e link. To implement a distributed routing protocol, a new S<strong>at</strong>RouteAgent could be defined– this would learnabout topology by noting the interface index marked in each packet as it came up the stack– a helper function in the nodeintf_to_target() allows it to resolve an index value to a particular LinkHead.<strong>The</strong>re are pointers to three additional objects in a S<strong>at</strong>Node. First, each S<strong>at</strong>Node contai<strong>ns</strong> a position object, discussed in theprevious section. Second, each S<strong>at</strong>Node contai<strong>ns</strong> a LinkH<strong>and</strong>offMgr th<strong>at</strong> monitors for opportunities to h<strong>and</strong> links off <strong>and</strong>coordin<strong>at</strong>es the h<strong>and</strong>offs. S<strong>at</strong>ellite nodes <strong>and</strong> terminal nodes each have their specialized version of a LinkH<strong>and</strong>offMgr.Finally, a number of pointers to objects are contained in a S<strong>at</strong>Node. We discussed linklisthead_ <strong>and</strong> nodehead_ inthe previous subsection. <strong>The</strong> uplink_ <strong>and</strong> downlink_ pointers are used for convenience under the assumption th<strong>at</strong>, inmost simul<strong>at</strong>io<strong>ns</strong>, a s<strong>at</strong>ellite or a terminal has only one uplink <strong>and</strong> downlink channel.17.3.3 Detailed look <strong>at</strong> s<strong>at</strong>ellite linksFigure 17.6 provides a more detailed look <strong>at</strong> how s<strong>at</strong>ellite links are composed. In this section, we describe how packetsmove up <strong>and</strong> down the stack, <strong>and</strong> the key things to note <strong>at</strong> each layer. <strong>The</strong> file ~<strong>ns</strong>/tcl/lib/<strong>ns</strong>-s<strong>at</strong>.tcl contai<strong>ns</strong> the various OTcli<strong>ns</strong>tprocs th<strong>at</strong> assemble links according to Figure 17.6. We describe the composite structure herein as a “network stack.” Mostof the code for the various link components is in ~<strong>ns</strong>/s<strong>at</strong>link.{cc,h}.<strong>The</strong> entry point to a network stack is the S<strong>at</strong>LinkHead object. <strong>The</strong> S<strong>at</strong>LinkHead object derives from Class LinkHead;the aim of link head objects is to provide a uniform API for all network stacks. 4 <strong>The</strong> S<strong>at</strong>LinkHead object contai<strong>ns</strong> pointersto the LL, Queue, MAC, Error model, <strong>and</strong> both Phy objects. <strong>The</strong> S<strong>at</strong>LinkHead object can also be queried as to wh<strong>at</strong> type ofnetwork stack it is– e.g., GSL, interplane ISL, crossseam ISL, etc.. Valid codes for the type_ field are currently found in~<strong>ns</strong>/s<strong>at</strong>.h. Finally, the S<strong>at</strong>LinkHead stores a boolean variable linkup_ th<strong>at</strong> indic<strong>at</strong>es whether the link to <strong>at</strong> least one othernode on the channel is up. <strong>The</strong> C++ implement<strong>at</strong>ion of S<strong>at</strong>LinkHead is found in ~<strong>ns</strong>/s<strong>at</strong>link.{cc,h}.Packets leaving a node pass through the S<strong>at</strong>LinkHead tra<strong>ns</strong>parently to the class S<strong>at</strong>LL object. <strong>The</strong> S<strong>at</strong>LL class derivesfrom LL (link layer). Link layer protocols (like ARQ protocols) can be defined here. <strong>The</strong> current S<strong>at</strong>LL assig<strong>ns</strong> a MAC4 In the author’s opinion, all network stacks in <strong>ns</strong> should eventually have a LinkHead object <strong>at</strong> the front– the class S<strong>at</strong>LinkHead would then disappear.183


from routing agentto Node->entryS<strong>at</strong>LinkHeadNetworkInterfaceLLS<strong>at</strong>/EnqueQueueS<strong>at</strong>/RecvErrormodelS<strong>at</strong>/DropS<strong>at</strong>/DequeMacS<strong>at</strong>/ErrorPhy_txPhy_rxto S<strong>at</strong>Channelfrom S<strong>at</strong>ChannelFigure 17.6: Detailed look <strong>at</strong> network interface stack.address to the packet. Note th<strong>at</strong> in the s<strong>at</strong>ellite case, we do not use an Address Resolution Protocol (ARP); i<strong>ns</strong>tead, we simplyuse the MAC index_ variable as its address, <strong>and</strong> we use a helper function to find the MAC address of the correspondinginterface of the next-hop node. Since class LL derives from class LinkDelay, the delay_ parameter of LinkDelaycan be used to model any processing delay in the link layer; by default this delay is zero.<strong>The</strong> next object an outgoing packet encounters is the interface queue. However, if tracing is enabled, tracing elements maysurround the queue, as shown in Figure 17.6. This part of a s<strong>at</strong>ellite link functio<strong>ns</strong> like a conventional <strong>ns</strong> link.<strong>The</strong> next layer down is the MAC layer. <strong>The</strong> MAC layer draws packets from the queue (or deque trace) object– a h<strong>and</strong>shakingbetween the MAC <strong>and</strong> the queue allows the MAC to draw packets out of the queue as it needs them. <strong>The</strong> tra<strong>ns</strong>mission timeof a packet is modelled in the MAC also– the MAC computes the tra<strong>ns</strong>mission delay of the packet (based on the sum of theLINK_HDRSIZE field defined in s<strong>at</strong>link.h <strong>and</strong> the size field in the common packet header), <strong>and</strong> does not call up foranother packet until the current one has been “sent” to the next layer down. <strong>The</strong>refore, it is important to set the b<strong>and</strong>width ofthe link correctly <strong>at</strong> this layer. For convenience, the tra<strong>ns</strong>mit time is encoded in the mac header; this inform<strong>at</strong>ion can be used<strong>at</strong> the receiving MAC to calcul<strong>at</strong>e how long it must wait to detect a collision on a packet, for example.Next, the packet is sent to a tra<strong>ns</strong>mitting interface (Phy_tx) of class S<strong>at</strong>Phy. This object just sends the packet to the <strong>at</strong>tachedchannel. We noted earlier in this chapter th<strong>at</strong> all interfaces <strong>at</strong>tached to a channel are part of the linked list for th<strong>at</strong> channel.This is not true for tra<strong>ns</strong>mit interfaces, however. Only receive interfaces <strong>at</strong>tached to a channel comprise this linked list, sinceonly receive interfaces should get a copy of tra<strong>ns</strong>mitted packets. <strong>The</strong> use of separ<strong>at</strong>e tra<strong>ns</strong>mit <strong>and</strong> receive interfaces mirrorsthe real world where full-duplex s<strong>at</strong>ellite links are made up of RF channels <strong>at</strong> different frequencies.<strong>The</strong> outgoing packet is next sent to a S<strong>at</strong>Channel, which copies the packet to every receiving interface (of class S<strong>at</strong>Phy)on the channel. <strong>The</strong> Phy_rx sends the packet to the MAC layer. At the MAC layer, the packet is held for the dur<strong>at</strong>ion of itstra<strong>ns</strong>mission time (<strong>and</strong> any appropri<strong>at</strong>e collision detection is performed if the MAC, such as the Aloha MAC, supports it).If the packet is determined to have arrived safely <strong>at</strong> the MAC, it next passes to an ErrorModel object, if it exists. If not,the packet moves through any receive tracing objects to the S<strong>at</strong>LL object. <strong>The</strong> S<strong>at</strong>LL object passes the packet up after aprocessing delay (again, by default, the value for delay_ is zero).184


<strong>The</strong> final object th<strong>at</strong> a received packet passes through is an object of class NetworkInterface. This object stampsthe iface_ field in the common header with the network stack’s unique index value. This is used to keep track of whichnetwork stack a packet arrived on. <strong>The</strong> packet then goes to the entry of the S<strong>at</strong>Node (usually, an address classifier).Finally, “geo-repe<strong>at</strong>er” s<strong>at</strong>ellites exist, as described earlier in this chapter. Geo-repe<strong>at</strong>er network stacks are very simple– theyonly contain a Phy_tx <strong>and</strong> a Phy_rx of class Repe<strong>at</strong>erPhy, <strong>and</strong> a S<strong>at</strong>LinkHead. Packets received by a Phy_rx are sentto the Phy_tx without delay. <strong>The</strong> geo-repe<strong>at</strong>er s<strong>at</strong>ellite is a degener<strong>at</strong>e s<strong>at</strong>ellite node, in th<strong>at</strong> it does not contain things liketracing elements, h<strong>and</strong>off managers, routing agents, or any other link interfaces other than repe<strong>at</strong>er interfaces.17.4 Comm<strong>and</strong>s <strong>at</strong> a glanceFollowing is a list of comm<strong>and</strong>s rel<strong>at</strong>ed to s<strong>at</strong>ellite networking:$<strong>ns</strong>_ node-config -s<strong>at</strong>NodeType This node configur<strong>at</strong>ion declares th<strong>at</strong> the subsequent new nodes cre<strong>at</strong>ed will be of type , where can be one ofthe following: geo, geo-repe<strong>at</strong>er, polar, terminal. Other required fields for s<strong>at</strong>ellite nodes (for setting upinitial links <strong>and</strong> channels) are as follows (see Section 5.3): $<strong>ns</strong>_ node-config -llType $<strong>ns</strong>_ node-config -ifqType $<strong>ns</strong>_ node-config -ifqLen $<strong>ns</strong>_ node-config -macType $<strong>ns</strong>_ node-config -channelType $<strong>ns</strong>_ node-config -downlinkBW (note– s<strong>at</strong>NodeType geo-repe<strong>at</strong>er only requires specifying the channelType– all other optio<strong>ns</strong> are disregarded. Seetcl/ex/s<strong>at</strong>-repe<strong>at</strong>er.tcl for an example.)$<strong>ns</strong>_ s<strong>at</strong>node-polar This a simul<strong>at</strong>or wrapper method for cre<strong>at</strong>ing a polar s<strong>at</strong>ellite node. Two links, uplink <strong>and</strong> downlink, are cre<strong>at</strong>ed along withtwo channels, uplink channel <strong>and</strong> downlink channel. is the polar s<strong>at</strong>ellite altitude, is orbit inclin<strong>at</strong>ion w.r.tequ<strong>at</strong>or, is the longitude of ascending node, gives the initial position of the s<strong>at</strong>ellite along this orbit, defines the plane of the polar s<strong>at</strong>ellite. is a list of link argument optio<strong>ns</strong> th<strong>at</strong> defines the network interface (likeLL, Qtype, Qlim, PHY, MAC etc).$<strong>ns</strong>_ s<strong>at</strong>node-geo This is a wrapper method for cre<strong>at</strong>ing a geo s<strong>at</strong>ellite node th<strong>at</strong> first cre<strong>at</strong>es a s<strong>at</strong>node plus two link interfaces (uplink <strong>and</strong>downlink) plus two s<strong>at</strong>ellite channels (uplink <strong>and</strong> downlink). defines the type of channel.$<strong>ns</strong>_ s<strong>at</strong>node-geo-repe<strong>at</strong>er This is a wrapper method for making a geo s<strong>at</strong>ellite repe<strong>at</strong>er node th<strong>at</strong> first cre<strong>at</strong>es a s<strong>at</strong>node plus two link interfaces (uplink<strong>and</strong> downlink) plus two s<strong>at</strong>ellite channels (uplink <strong>and</strong> downlink).$<strong>ns</strong>_ s<strong>at</strong>node-terminal This is a wrapper method th<strong>at</strong> simply cre<strong>at</strong>es a terminal node. <strong>The</strong> <strong>and</strong> defines the l<strong>at</strong>itude <strong>and</strong> longituderespectively of the terminal.$<strong>ns</strong>_ s<strong>at</strong>node This is a more primitive method for cre<strong>at</strong>ing s<strong>at</strong>nodes of type which can be polar, geo or terminal.$s<strong>at</strong>node add-interface This is an internal method of Node/S<strong>at</strong>Node th<strong>at</strong> sets up link layer, mac layer, interface queue <strong>and</strong> physical layer structuresfor the s<strong>at</strong>ellite nodes.185


$s<strong>at</strong>node add-isl This method cre<strong>at</strong>es an ISL (inter-s<strong>at</strong>ellite link) between the two nodes. <strong>The</strong> link type (inter, intra or cross-seam), BW of thelink, the queue-type <strong>and</strong> queue-limit are all specified.$s<strong>at</strong>node add-gsl This method cre<strong>at</strong>es a GSL (ground to s<strong>at</strong>ellite link). First a network stack is cre<strong>at</strong>ed th<strong>at</strong> is defined by LL, IfQ, Qlim, MAC,BW <strong>and</strong> PHY layers. Next the node is <strong>at</strong>tached to the channel inlink <strong>and</strong> outlink.186


Chapter 18Radio Propag<strong>at</strong>ion ModelsThis chapter describes the radio propag<strong>at</strong>ion models implemented in <strong>ns</strong>. <strong>The</strong>se models are used to predict the received signalpower of each packet. At the physical layer of each wireless node, there is a receiving threshold. When a packet is received,if its signal power is below the receiving threshold, it is marked as error <strong>and</strong> dropped by the MAC layer.Up to now there are three propag<strong>at</strong>ion models in <strong>ns</strong>, which are the free space model 1 , two-ray ground reflection model 2<strong>and</strong> the shadowing model 3 . <strong>The</strong>ir implement<strong>at</strong>ion can be found in ~<strong>ns</strong>/propag<strong>at</strong>ion.{cc,h}, ~<strong>ns</strong>/tworayground.{cc,h} <strong>and</strong>~<strong>ns</strong>/shadowing.{cc,h}. This document<strong>at</strong>ion reflects the APIs in <strong>ns</strong>-2.1b7.18.1 Free space model<strong>The</strong> free space propag<strong>at</strong>ion model assumes the ideal propag<strong>at</strong>ion condition th<strong>at</strong> there is only one clear line-of-sight p<strong>at</strong>hbetween the tra<strong>ns</strong>mitter <strong>and</strong> receiver. H. T. Friis presented the following equ<strong>at</strong>ion to calcul<strong>at</strong>e the received signal power infree space <strong>at</strong> distance d from the tra<strong>ns</strong>mitter [12].P r (d) = P tG t G r λ 2(4π) 2 d 2 L(18.1)where P t is the tra<strong>ns</strong>mitted signal power. G t <strong>and</strong> G r are the antenna gai<strong>ns</strong> of the tra<strong>ns</strong>mitter <strong>and</strong> the receiver respectively.L(L ≥ 1) is the system loss, <strong>and</strong> λ is the wavelength. It is common to select G t = G r = 1 <strong>and</strong> L = 1 in <strong>ns</strong> simul<strong>at</strong>io<strong>ns</strong>.<strong>The</strong> free space model basically represents the communic<strong>at</strong>ion range as a circle around the tra<strong>ns</strong>mitter. If a receiver is withinthe circle, it receives all packets. Otherwise, it loses all packets<strong>The</strong> OTcl interface for utilizing a propag<strong>at</strong>ion model is the node-config comm<strong>and</strong>. One way to use it here is$<strong>ns</strong>_ node-config -propType Propag<strong>at</strong>ion/FreeSpaceAnother way is1 Based on the code contributed to <strong>ns</strong> from the CMU Monarch project.2 Contributed to <strong>ns</strong> from the CMU Monarch project.3 Implemented in <strong>ns</strong> by Wei Ye <strong>at</strong> USC/ISI187


set prop [new Propag<strong>at</strong>ion/FreeSpace]$<strong>ns</strong>_ node-config -propI<strong>ns</strong>tance $prop18.2 Two-ray ground reflection modelA single line-of-sight p<strong>at</strong>h between two mobile nodes is seldom the only mea<strong>ns</strong> of prop<strong>at</strong>ion. <strong>The</strong> two-ray ground reflectionmodel co<strong>ns</strong>iders both the direct p<strong>at</strong>h <strong>and</strong> a ground reflection p<strong>at</strong>h. It is shown [29] th<strong>at</strong> this model gives more accur<strong>at</strong>eprediction <strong>at</strong> a long distance than the free space model. <strong>The</strong> received power <strong>at</strong> distance d is predicted byP r (d) = P tG t G r h t 2 h r2d 4 L(18.2)where h t <strong>and</strong> h r are the heights of the tra<strong>ns</strong>mit <strong>and</strong> receive antennas respectively. Note th<strong>at</strong> the original equ<strong>at</strong>ion in [29]assumes L = 1. To be co<strong>ns</strong>istent with the free space model, L is added here.<strong>The</strong> above equ<strong>at</strong>ion shows a faster power loss than Eqn. (18.1) as distance increases. However, <strong>The</strong> two-ray model does notgive a good result for a short distance due to the oscill<strong>at</strong>ion caused by the co<strong>ns</strong>tructive <strong>and</strong> destructive combin<strong>at</strong>ion of the tworays. I<strong>ns</strong>tead, the free space model is still used when d is small.<strong>The</strong>refore, a cross-over distance d c is calcul<strong>at</strong>ed in this model. When d < d c , Eqn. (18.1) is used. When d > d c , Eqn. (18.2)is used. At the cross-over distance, Eq<strong>ns</strong>. (18.1) <strong>and</strong> (18.2) give the same result. So d c can be calcul<strong>at</strong>ed asd c = (4πh t h r )/λ (18.3)Similarly, the OTcl interface for utilizing the two-ray ground reflection model is as follows.$<strong>ns</strong>_ node-config -propType Propag<strong>at</strong>ion/TwoRayGroundAltern<strong>at</strong>ively, the user can useset prop [new Propag<strong>at</strong>ion/TwoRayGround]$<strong>ns</strong>_ node-config -propI<strong>ns</strong>tance $prop18.3 Shadowing model18.3.1 Backgroud<strong>The</strong> free space model <strong>and</strong> the two-ray model predict the received power as a deterministic function of distance. <strong>The</strong>y bothrepresent the communic<strong>at</strong>ion range as an ideal circle. In reality, the received power <strong>at</strong> certain distance is a r<strong>and</strong>om variabledue to multip<strong>at</strong>h propag<strong>at</strong>ion effects, which is also known as fading effects. In fact, the above two models predicts the meanreceived power <strong>at</strong> distance d. A more general <strong>and</strong> widely-used model is called the shadowing model [29].188


EnvironmentβOutdoor Free space 2Shadowed urban area 2.7 to 5In building Line-of-sight 1.6 to 1.8Obstructed 4 to 6Table 18.1: Some typical values of p<strong>at</strong>h loss exponent βEnvironment σ dB (dB)Outdoor 4 to 12Office, hard partition 7Office, soft partition 9.6Factory, line-of-sight 3 to 6Factory, obstructed 6.8Table 18.2: Some typical values of shadowing devi<strong>at</strong>ion σ dB<strong>The</strong> shadowing model co<strong>ns</strong>ists of two parts. <strong>The</strong> first one is known as p<strong>at</strong>h loss model, which also predicts the mean receivedpower <strong>at</strong> distance d, denoted by P r (d). It uses a close-in distance d 0 as a reference. P r (d) is computed rel<strong>at</strong>ive to P r (d 0 ) asfollows.P r (d 0 )P r (d) = ( dd 0) β(18.4)β is called the p<strong>at</strong>h loss exponent, <strong>and</strong> is usually empirically determined by field measurement. From Eqn. (18.1) we know th<strong>at</strong>β = 2 for free space propag<strong>at</strong>ion. Table 18.1 gives some typical values of β. Larger values correspond to more obstructio<strong>ns</strong><strong>and</strong> hence faster decrease in average received power as distance becomes larger. P r (d 0 ) can be computed from Eqn. (18.1).<strong>The</strong> p<strong>at</strong>h loss is usually measured in dB. So from Eqn. (18.4) we have[ ]P r (d)P r (d 0 )dB( ) d= −10β logd 0(18.5)<strong>The</strong> second part of the shadowing model reflects the vari<strong>at</strong>ion of the received power <strong>at</strong> certain distance. It is a log-normalr<strong>and</strong>om variable, th<strong>at</strong> is, it is of Gaussian distribution if measured in dB. <strong>The</strong> overall shadowing model is represented by[ ] ( )Pr (d)d= −10β log + X dB (18.6)P r (d 0 )dBd 0where X dB is a Gaussian r<strong>and</strong>om variable with zero mean <strong>and</strong> st<strong>and</strong>ard devi<strong>at</strong>ion σ dB . σ dB is called the shadowing devi<strong>at</strong>ion,<strong>and</strong> is also obtained by measurement. Table 18.2 shows some typical values of σ dB . Eqn. (18.6) is also known as a log-normalshadowing model.<strong>The</strong> shadowing model extends the ideal circle model to a richer st<strong>at</strong>istic model: nodes can only probabilistically communic<strong>at</strong>ewhen near the edge of the communic<strong>at</strong>ion range.189


18.3.2 Using shadowing modelBefore using the model, the user should select the values of the p<strong>at</strong>h loss exponent β <strong>and</strong> the shadowing devi<strong>at</strong>ion σ dBaccording to the simul<strong>at</strong>ed environment.<strong>The</strong> OTcl interface is still the node-config comm<strong>and</strong>. One way to use it is as follows, <strong>and</strong> the values for these parametersare just examples.# first set values of shadowing modelPropag<strong>at</strong>ion/Shadowing set p<strong>at</strong>hlossExp_ 2.0Propag<strong>at</strong>ion/Shadowing set std_db_ 4.0Propag<strong>at</strong>ion/Shadowing set dist0_ 1.0Propag<strong>at</strong>ion/Shadowing set seed_ 0;# p<strong>at</strong>h loss exponent;# shadowing devi<strong>at</strong>ion (dB);# reference distance (m);# seed for RNG$<strong>ns</strong>_ node-config -propType Propag<strong>at</strong>ion/Shadowing<strong>The</strong> shadowing model cre<strong>at</strong>es a r<strong>and</strong>om number gener<strong>at</strong>or (RNG) object. <strong>The</strong> RNG has three types of seeds: raw seed,pre-defined seed (a set of known good seeds) <strong>and</strong> the huristic seed (details in Section 25.1). <strong>The</strong> above API only uses thepre-defined seed. If a user want different seeding method, the following API can be used.set prop [new Propag<strong>at</strong>ion/Shadowing]$prop set p<strong>at</strong>hlossExp_ 2.0$prop set std_db_ 4.0$prop set dist0_ 1.0$prop seed 0;# user can specify seeding method$<strong>ns</strong>_ node-config -propI<strong>ns</strong>tance $prop<strong>The</strong> above can be raw, predef or heuristic.18.4 Communic<strong>at</strong>ion rangeIn some applic<strong>at</strong>io<strong>ns</strong>, a user may want to specify the communic<strong>at</strong>ion range of wireless nodes. This can be done by set anappropri<strong>at</strong>e value of the receiving threshold in the network interface, i.e.,Phy/WirelessPhy set RXThresh_ A separ<strong>at</strong>e C program is provided <strong>at</strong> ~<strong>ns</strong>/indep-utils/propag<strong>at</strong>ion/threshold.cc to compute the receiving threshold. It can beused for all the propag<strong>at</strong>ion models discussed in this chapter. Assume you have compiled it <strong>and</strong> get the excutable named asthreshold. You can use it to compute the threshold as followsthreshold -m [other-optio<strong>ns</strong>] distancewhere is either FreeSpace, TwoRayGround or Shadowing, <strong>and</strong> the distance is thecommunic<strong>at</strong>ion range in meter.190


[other-optio<strong>ns</strong>] are used to specify parameters other than their default values. For the shadowing model there is anecessary parameter, -r , which specifies the r<strong>at</strong>e of correct reception <strong>at</strong> the distance. Becausethe communic<strong>at</strong>ion range in the shadowing model is not an ideal circle, an inverse Q-function [29] is used to calcul<strong>at</strong>e thereceiving threshold. For example, if you want 95% of packets can be correctly received <strong>at</strong> the distance of 50m, you cancompute the threshold bythreshold -m Shadowing -r 0.95 50Other available values of [other-optio<strong>ns</strong>] are shown below-pl -std -Pt -fr -Gt -Gr -L -ht -hr -d0 18.5 Comm<strong>and</strong>s <strong>at</strong> a glanceFollowing is a list of comm<strong>and</strong>s for propag<strong>at</strong>ion models.$<strong>ns</strong>_ node-config -propType This comm<strong>and</strong> selects in the simul<strong>at</strong>ion. the can bePropag<strong>at</strong>ion/FreeSpace, Propag<strong>at</strong>ion/TwoRayGround or Propag<strong>at</strong>ion/Shadowing$<strong>ns</strong>_ node-config -propI<strong>ns</strong>tance $propThis comm<strong>and</strong> is another way to utilize a propag<strong>at</strong>ion model. $prop is an i<strong>ns</strong>tance of the .$sprop_ seed This comm<strong>and</strong> seeds the RNG. $sprop_ is an i<strong>ns</strong>tance of the shadowing model.threshold -m [other-optio<strong>ns</strong>] distanceThis is a separ<strong>at</strong>e program <strong>at</strong> ~<strong>ns</strong>/indep-utils/propag<strong>at</strong>ion/threshold.cc, which is used to compute the receiving threshold fora specified communic<strong>at</strong>ion range.191


Chapter 19Energy Model in <strong>ns</strong>Energy Model, as implemented in <strong>ns</strong>, is a node <strong>at</strong>tribute. <strong>The</strong> energy model represents level of energy in a mobile host.<strong>The</strong> energy model in a node has a initial value which is the level of energy the node has <strong>at</strong> the beginning of the simul<strong>at</strong>ion.This is known as initialEnergy_. It also has a given energy usage for every packet it tra<strong>ns</strong>mits <strong>and</strong> receives. <strong>The</strong>seare called txPower_ <strong>and</strong> rxPower_. <strong>The</strong> files where the energy model is defined are <strong>ns</strong>/energymodel[.cc <strong>and</strong>.h]. Otherfunctio<strong>ns</strong>/methods described in this chapter may be found in <strong>ns</strong>/wireless-phy.cc, <strong>ns</strong>/cmu-trace.cc, <strong>ns</strong>/tcl/lib[<strong>ns</strong>-lib.tcl, <strong>ns</strong>node.tcl,<strong>ns</strong>-mobilenode.tcl].19.1 <strong>The</strong> C++ EnergyModel Class<strong>The</strong> basic energy model is very simple <strong>and</strong> is defined by class EnergyModel as shown below:class EnergyModel : public TclObjectpublic:EnergyModel(double energy) energy_ = energy;inline double energy() return energy_;inline void setenergy(double e) energy_ = e;virtual void DecrTxEnergy(double txtime, double P_tx)energy_ -= (P_tx * txtime);virtual void DecrRcvEnergy(double rcvtime, double P_rcv)energy_ -= (P_rcv * rcvtime);protected:double energy_;;As seen from the EnergyModel Class definition above, there is only a single class variable energy_ which represents thelevel of energy in the node <strong>at</strong> any given time. <strong>The</strong> co<strong>ns</strong>tructor EnergyModel(energy) requires the initial-energy to be passedalong as a parameter. <strong>The</strong> other class methods are used to decrease the energy level of the node for every packet tra<strong>ns</strong>mitted( DecrTxEnergy(txtime, P_tx)) <strong>and</strong> every packet received ( DecrRcvEnergy (rcvtime, P_rcv)) by thenode. P_tx <strong>and</strong> P_rcv are the tra<strong>ns</strong>mitting <strong>and</strong> receiving power (respectively) required by the node’s interface or PHY. Atthe beginning of simul<strong>at</strong>ion, energy_ is set to initialEnergy_ which is then decremented for every tra<strong>ns</strong>mission <strong>and</strong>192


eception of packets <strong>at</strong> the node. When the energy level <strong>at</strong> the node goes down to zero, no more packets can be received ortra<strong>ns</strong>mitted by the node. If tracing is turned on, line DEBUG: node dropping pkts due to energy= 0 is printed in the tracefile.19.2 <strong>The</strong> OTcl interfaceSince the energy model is a node <strong>at</strong>tribute, it may be defined by the following node configur<strong>at</strong>ion APIs:$<strong>ns</strong>_ node-config -energyModel $energymodel \-rxPower $p_rx \-txPower $p_tx \-initialEnergy $initialenergyOptional values for above configur<strong>at</strong>ion parameters of the energy model are given in the following table:Attribute optional values default values-energyModel "EnergyModel" none-rxPower receiving power in w<strong>at</strong>ts (e.g 0.3) 281.8mW-txPower tra<strong>ns</strong>mitting power in w<strong>at</strong>ts (e.g 0.4) 281.8mW-initialEnergy energy in joules (e.g 0.1) 0.0193


Chapter 20Directed Diffusion<strong>The</strong> directed diffusion module in <strong>ns</strong> has been ported from SCADDS group’s implement<strong>at</strong>ion of directed diffusion <strong>at</strong> USC/ISI.<strong>The</strong>re is an older version of diffusion in <strong>ns</strong> th<strong>at</strong> was implemented several years back <strong>and</strong> has become rel<strong>at</strong>ively old <strong>and</strong>outd<strong>at</strong>ed. This older version can be found under directory diffusion. And the newer version of diffusion resides under~<strong>ns</strong>//diffusion3. This chapter talks about the newer diffusion model in <strong>ns</strong>. <strong>The</strong> module <strong>and</strong> methods described here canbe found under ~<strong>ns</strong>/tcl/lib/<strong>ns</strong>-diffusion.tcl, <strong>ns</strong>-lib.tcl <strong>and</strong> all relevant C++ code can be found under ~<strong>ns</strong>/diffusion3. Visit theSCADDS group webpage <strong>at</strong> http://www.isi.edu/scadds for details about their implement<strong>at</strong>ion.20.1 Wh<strong>at</strong> is Directed Diffusion?Directed Diffusion is a method of d<strong>at</strong>a dissemin<strong>at</strong>ion especially suitable in distributed se<strong>ns</strong>ing scenarios. It differs from IPmethod of communic<strong>at</strong>ion. For IP “nodes are identified by their end-points, <strong>and</strong> inter-node communic<strong>at</strong>ion is layered onan end-to-end delivery service provided within the network”. Directed diffusion, on the other h<strong>and</strong> is d<strong>at</strong>a-centric. D<strong>at</strong>agener<strong>at</strong>ed by se<strong>ns</strong>or nodes are identified by their <strong>at</strong>tribute-value pair. Sinks or nodes th<strong>at</strong> request d<strong>at</strong>a send out “interest”s intothe network. D<strong>at</strong>a gener<strong>at</strong>ed by “source” nodes th<strong>at</strong> m<strong>at</strong>ch these interests, “flow” towards the sinks. Intermedi<strong>at</strong>e nodes arecapable of caching <strong>and</strong> tra<strong>ns</strong>forming d<strong>at</strong>a. For details on directed diffusion, see “Directed Diffusion: A Scalable <strong>and</strong> RobustCommunic<strong>at</strong>ion Paradigm for Se<strong>ns</strong>or Networks”, authored by Chalermek Intanagonwiw<strong>at</strong>, Ramesh Govindan <strong>and</strong> DeborahEstrin th<strong>at</strong> appeared in MobiCOM, August 2000, Boston, Massachusetts. This <strong>and</strong> other diffusion rel<strong>at</strong>ed papers can beviewed <strong>at</strong> http://www.isi.edu/scadds/public<strong>at</strong>io<strong>ns</strong>.html under public<strong>at</strong>io<strong>ns</strong> section.20.2 <strong>The</strong> diffusion model in <strong>ns</strong><strong>The</strong> directed diffusion model co<strong>ns</strong>ists of a core diffusion layer, a diffusion library provides an applic<strong>at</strong>ion programminginterface for overlying diffusion applic<strong>at</strong>io<strong>ns</strong> <strong>and</strong> finally the applic<strong>at</strong>ion layer which includes both diffusion applic<strong>at</strong>io<strong>ns</strong> <strong>and</strong>filters. <strong>The</strong> core diffusion layer is used to receive/send out packets from/into the network. <strong>The</strong> library provides a interfacefor the overlying applic<strong>at</strong>ion classes for publishing/subscribing etc. <strong>The</strong>se APIs have been described in details in a documentcalled Network Routing API 8.0 <strong>and</strong> can be found <strong>at</strong> http://www.isi.edu/scadds/public<strong>at</strong>io<strong>ns</strong>.html underAPIs section. In the following paragraphs we are going to describe how the diffusion model looks like in <strong>ns</strong>.First we start with a brief description of the diffusion3 directory structure. If the reader wishes to examine the C++ coderel<strong>at</strong>ed to NS Diffusion th<strong>at</strong> underpi<strong>ns</strong> the OTcl script comm<strong>and</strong>s, it may be found in ~<strong>ns</strong>/<strong>ns</strong>/diffustion3.ăHere is a summaryby subdirectory:194


App2 3FilterF1FilterF24 5 6 71Directed Diffusion Core8Figure 20.1: Message flow in directed diffusionapps contai<strong>ns</strong> sample source <strong>and</strong> sink applic<strong>at</strong>io<strong>ns</strong> like gear, ping <strong>and</strong> rmst.lib has DiffusionRouting class definitio<strong>ns</strong> <strong>and</strong> definitio<strong>ns</strong> of diffusion applic<strong>at</strong>ion class. In addition there are sub-dirs calledmain <strong>and</strong> nr. main houses misc diffusion utility code. nr includes <strong>at</strong>tribute definition <strong>and</strong> the class NR which is anabstract factory for the API (so th<strong>at</strong> either ISI or MIT implement<strong>at</strong>io<strong>ns</strong> may derive from it.<strong>ns</strong> contai<strong>ns</strong> <strong>ns</strong> wrappers for diffusion code.ă<strong>The</strong>se wrapper classes allow the core diffusion code <strong>and</strong> the diffusion API to beseamlessly incorpor<strong>at</strong>ed into the NS class hierarchy. <strong>The</strong> DiffRoutingAgent is a wrapper for the Core Diffusion code,<strong>and</strong> DiffAppAgent is a wrapper for the DiffusionRouting (API) code.filter_core has the core diffusion agent.filters holds the different filters supported by diffusion implement<strong>at</strong>ion including two-phase-pull, one-phase-pull, gear, rmst,log, tag <strong>and</strong> srcrt (as of 10/03/03).<strong>The</strong> above Figure 20.1 is from SCADDS’ network routing API document available from their homepage (URL given earlier).<strong>The</strong> document describes <strong>at</strong>tribute factories, m<strong>at</strong>ching rules for <strong>at</strong>tributes, how applic<strong>at</strong>io<strong>ns</strong> interface with the core diffusionlayer, <strong>and</strong> filter/timer APIs. All messages coming from/going out in the network is received <strong>at</strong>/sent out from the core diffusionlayer. Messages can also come to core-diffusion layer from local applic<strong>at</strong>io<strong>ns</strong> <strong>and</strong>/or filters th<strong>at</strong> might be connected to thenode. <strong>The</strong> applic<strong>at</strong>io<strong>ns</strong> use the publish/subscribe/send interface to send interest <strong>and</strong> d<strong>at</strong>a messages to the network.<strong>The</strong> core diffusion agent <strong>and</strong> diffusion applic<strong>at</strong>ion agent are <strong>at</strong>tached to two well-known ports defined in ~<strong>ns</strong>//tcl/lib/<strong>ns</strong>default.tcl.Diffusion applic<strong>at</strong>io<strong>ns</strong> <strong>at</strong>tached to the node call the underlying diffusion applic<strong>at</strong>ion agent for publishing/subscribing/sendingd<strong>at</strong>a.20.3 Some mac issues for diffusion in <strong>ns</strong>In the shim layer th<strong>at</strong> sits between diffusion <strong>and</strong> <strong>ns</strong>, (see diffusion3/<strong>ns</strong> dir for code implementing this layer) all diffusionpackets are encapsul<strong>at</strong>ed within <strong>ns</strong> packets <strong>and</strong> are marked to be broadcasted. In previous versio<strong>ns</strong> all diffusion packets weremarked to be broadcast in <strong>ns</strong>. This is now changed. Now all diffusion pkts in <strong>ns</strong> uses the diffusion next_hop info thus allowingboth broadcast <strong>and</strong> unicast.So previously this only-brdcast fe<strong>at</strong>ure supported for diffusion packets resulted in some problems <strong>at</strong> the mac layer. <strong>The</strong> mac-802.11 doesnot try to re-tra<strong>ns</strong>mit a broadcast packet incase there is a collision <strong>and</strong> the packet is dropped. Coupled to this wasthe fact th<strong>at</strong> mac-802.11 didn’t do r<strong>and</strong>om selection of slots in the contention window before it tra<strong>ns</strong>mitted a packet (a brdcastd<strong>at</strong>a or rts for unicast pkts). As a result there were a high number of collisio<strong>ns</strong> <strong>at</strong> the mac layer <strong>and</strong> a lot of packets were lost.This was fixed by adding r<strong>and</strong>om selection of slots before mac tx’ed a brdcast pkt (or a rts pkt).195


However if we have a large <strong>and</strong> de<strong>ns</strong>e topology, there is a chance th<strong>at</strong> two or more nodes may select the same slot in themac contention window (the contention window size varies from 31 to 1023 for DSSS PHY MIB specific<strong>at</strong>io<strong>ns</strong>). Thus nowwe need to add some extra jitter <strong>at</strong> the higher applic<strong>at</strong>ion layer. Diffusion has a provision to do this by compiling <strong>ns</strong> withthe macro USE_BROADCAST_MAC. Wh<strong>at</strong> this does is it in addition to delaying certain messages (to avoid collisio<strong>ns</strong>),when run with a BROADCAST MAC layer, diffusion will use a different set of values for delays <strong>and</strong> jitters. <strong>The</strong>se differentdelay/jitter values are defined under diffusion3/lib/main/config.hh. Since this might increase the l<strong>at</strong>ency you might want tofine-tune the delay values by h<strong>and</strong>.20.4 APIs for using filters in diffusionAs described earlier (see figure 20.1), filters can be <strong>at</strong>tached to a diffusion node for various reaso<strong>ns</strong>. <strong>The</strong>re can be basic diffusionfilters providing two-phase-pull (GradientFilter) <strong>and</strong> one-phase-pull (OnePhasePullFilter) diffusion routing algorithms.<strong>The</strong>re is the GeoRoutingFilter or gear th<strong>at</strong> provides a certain loc<strong>at</strong>ion (co-ordin<strong>at</strong>e) based routing algorithm. <strong>The</strong>re is alsoother filters for RMST routing algorithm (RmstFilter), logging (LogFilter), source routing (SourceRouteFilter) <strong>and</strong> tagging(TagFilter). See Comm<strong>and</strong>s <strong>at</strong> a glance section for details on APIs for adding filters to a diffusion node.20.5 Ping: an example diffusion applic<strong>at</strong>ion implement<strong>at</strong>ion<strong>The</strong>re is a ping applic<strong>at</strong>ion implemented under diffusion3/apps/ping subdir. <strong>The</strong> applic<strong>at</strong>ion co<strong>ns</strong>ists of a ping sender <strong>and</strong>receiver. <strong>The</strong> receiver requests for d<strong>at</strong>a by sending out “interest”s in the network. <strong>The</strong> interests get diffused through thenetwork. <strong>The</strong> ping-sender on receiving m<strong>at</strong>ching interests, sends out d<strong>at</strong>a.20.5.1 Ping Applic<strong>at</strong>ion as implemented in C++<strong>The</strong> ping-sender <strong>and</strong> -receiver classes, namely PingSenderApp <strong>and</strong> PingReceiverApp both derive from DiffApp, the parentclass for all diffusion based applic<strong>at</strong>io<strong>ns</strong>. See diffusion3/lib/diffapp{.cc,.hh} for detailed implement<strong>at</strong>ion of the DiffApp class.<strong>The</strong> ping-sender uses MySenderReceive object th<strong>at</strong> h<strong>and</strong>les all callbacks for it. Also the ping-sender defines two functio<strong>ns</strong>setupSubscription() <strong>and</strong> setupPublic<strong>at</strong>ion(). <strong>The</strong> first function cre<strong>at</strong>es interest <strong>at</strong>tributes th<strong>at</strong> m<strong>at</strong>ches with d<strong>at</strong>a <strong>at</strong>tributes it(the sender) has to offer. Next it calls the dr-library function subscribe(). <strong>The</strong> subscription is used by the ping-sender to cre<strong>at</strong>ean internal st<strong>at</strong>e agai<strong>ns</strong>t which <strong>at</strong>tributes for interests received from the network are m<strong>at</strong>ched agai<strong>ns</strong>t. Incase of a m<strong>at</strong>ch, them<strong>at</strong>ching d<strong>at</strong>a is sent outinto the network. Function setupPublic<strong>at</strong>ion() cre<strong>at</strong>e <strong>at</strong>tributes for the d<strong>at</strong>a it has to offer <strong>and</strong> callsthe library function publish() which inturn retur<strong>ns</strong> a publish h<strong>and</strong>le. <strong>The</strong> ping-sender uses this h<strong>and</strong>le to periodically send outd<strong>at</strong>a which is forwarded by the gradient to core-diffusion to be sent out into the network only if it finds a m<strong>at</strong>ching interest.<strong>The</strong> ping-receiver object uses a similar callback object called MyReceiverReceive. And it defines a function setupSubscription()th<strong>at</strong> cre<strong>at</strong>es <strong>at</strong>tributes for the interest the receiver will be sending. Next it calls the dr library supported subscribe() whichsends the interest out into the network. <strong>The</strong> recv() function is used to recv m<strong>at</strong>ching d<strong>at</strong>a <strong>and</strong> the receiver then calcul<strong>at</strong>es thel<strong>at</strong>ency for each d<strong>at</strong>a packet received from the ping-sender. <strong>The</strong> ping sender can be found under ping_sender.cc,.h. Andthe ping_receiver is implemented under ping_receiver.cc,.h. Some common defines <strong>and</strong> <strong>at</strong>tribute factories for d<strong>at</strong>a/interest<strong>at</strong>tributes are defined in ping.hh <strong>and</strong> ping_common.cc.196


20.5.2 Tcl APIs for the ping applic<strong>at</strong>ionAn example script for the ping applic<strong>at</strong>ion is under ~<strong>ns</strong>/tcl/ex/diffusion3/simple-diffusion.tcl. <strong>The</strong> example scenario co<strong>ns</strong>istsof 3 nodes of which one is a ping-sender <strong>and</strong> another is a ping-receiver. <strong>The</strong> source <strong>and</strong> sink nodes are far away from oneanother <strong>and</strong> communic<strong>at</strong>e only through a third node. <strong>The</strong> option adhocRouting is defined as Directed_Diffusion. This enablesa core-diffusion agent to be cre<strong>at</strong>ed during the time of node cre<strong>at</strong>ion. Also it cre<strong>at</strong>es a diffusionApplic<strong>at</strong>ion agent if one is notpresent already. <strong>The</strong> option diffusionFilter needs to be provided <strong>at</strong> the time of node configur<strong>at</strong>ion th<strong>at</strong> defines the one or morefilters th<strong>at</strong> would be added to the node. <strong>The</strong>re is also an option for specifying stopTime which is the time the simul<strong>at</strong>ion ends.At this time there is a callback to a function th<strong>at</strong> prints out all st<strong>at</strong>istical d<strong>at</strong>a into /tmp/diffusion-*.out.Node configur<strong>at</strong>ion is done as follows:$<strong>ns</strong>_ node-config -adhocRouting $opt(adhocRouting)-diffusionFilter $opt(filters)-llType $opt(ll)-stopTime $opt(prestop)<strong>The</strong> ping sender applic<strong>at</strong>ion is cre<strong>at</strong>ed in the following way:set src_(0) [new Applic<strong>at</strong>ion/DiffApp/PingSender]$<strong>ns</strong>_ <strong>at</strong>tach-diffapp $node_(0) $src_(0)$<strong>ns</strong>_ <strong>at</strong> 0.123 "$src_(0) publish"<strong>The</strong> first line cre<strong>at</strong>es a ping-sender object. Simul<strong>at</strong>or class method <strong>at</strong>tach-diffapp basically <strong>at</strong>taches the applic<strong>at</strong>ion to the underlyingdiffusionApplic<strong>at</strong>ion agent for th<strong>at</strong> given node. <strong>The</strong> comm<strong>and</strong> publish essentially “starts” the sender applic<strong>at</strong>ion.Similarly the ping sink is cre<strong>at</strong>ed as follows:#Diffusion sink applic<strong>at</strong>io<strong>ns</strong>et snk_(0) [new Applic<strong>at</strong>ion/DiffApp/PingReceiver]$<strong>ns</strong>_ <strong>at</strong>tach-diffapp $node_(2) $snk_(0)$<strong>ns</strong>_ <strong>at</strong> 1.456 "$snk_(0) subscribe"<strong>The</strong> comm<strong>and</strong> subscribe starts the ping-receiver applic<strong>at</strong>ion.Thus in order to cre<strong>at</strong>e your own applic<strong>at</strong>ion, you need to :1. define <strong>at</strong>tribute-factories <strong>and</strong> <strong>at</strong>tributes for applic<strong>at</strong>ion interest/d<strong>at</strong>a.2. cre<strong>at</strong>e the applic<strong>at</strong>ion class (using dr-library APIs)3. add tcl comm<strong>and</strong>s to start the applic<strong>at</strong>ionSee ~<strong>ns</strong>/tcl/lib/<strong>ns</strong>-lib.tcl, <strong>ns</strong>-diffusion.tcl for implement<strong>at</strong>io<strong>ns</strong> of OTcl hooks for directed diffusion. Alo see chapter on Mobilityin this manual for details on mobility model <strong>and</strong> wireless simul<strong>at</strong>io<strong>ns</strong> in <strong>ns</strong>.20.6 Changes required to add yr diffusion applic<strong>at</strong>ion to <strong>ns</strong>Let’s say you have an applic<strong>at</strong>ion (it might even be a certain filter, which also is by class hierarchy, a diffusion applic<strong>at</strong>ion <strong>and</strong>it would derive from class DiffApp) th<strong>at</strong> ru<strong>ns</strong> on the test-bed version. Now you want to run diffusion on <strong>ns</strong> <strong>and</strong> so want to use197


yr applic<strong>at</strong>ion in the <strong>ns</strong> context. <strong>The</strong> few lines describe the changes/additio<strong>ns</strong> you need to make for yr diffusion applic<strong>at</strong>ionto work in <strong>ns</strong> environment.We will co<strong>ns</strong>ider onePhasePullFilter object (under diffusion3/filters/misc/log.*) as an example. As a first step you need tocre<strong>at</strong>e a split object out of the applic<strong>at</strong>ion class object, presumably defined as a pure c++ object. A split object is one th<strong>at</strong> iscre<strong>at</strong>ed by the user in the interpretor (in OTcl space) <strong>and</strong> which is also has a shadow object in the compiled hierarchy (in c++space). In <strong>ns</strong>, a split object is derived from class TclClass as shown below:#ifdef NS_DIFFUSIONst<strong>at</strong>ic class LogFilterClass : public TclClasspublic:LogFilterClass() : TclClass("Applic<strong>at</strong>ion/DiffApp/LogFilter")TclObject * cre<strong>at</strong>e(int argc, co<strong>ns</strong>t char*co<strong>ns</strong>t* argv)return(new LogFilter());class_log_filter;#endif //DIFFUSIONNote th<strong>at</strong> all filter objects specifically have a h<strong>and</strong>le to the DiffAppAgent (the diffusion routing object) passed in the co<strong>ns</strong>tructorcall. Filter objects get cre<strong>at</strong>ed from function cre<strong>at</strong>e-diffusionApp-agent diffFilters defined in <strong>ns</strong>-diffusion.tcl. Usersneed not specifically call the OTcl function cre<strong>at</strong>e-diffusionApp-agent as it is called during node cre<strong>at</strong>ion based on the nodeconfigur<strong>at</strong>ionparameters. See how filters are defined in node-config under comm<strong>and</strong>s <strong>at</strong> a glance section. However applic<strong>at</strong>ionobjects which are not filter objects (like ping_sender, push_receiver etc) are cre<strong>at</strong>ed by users directly from user scripts. Andin th<strong>at</strong> case the h<strong>and</strong>le to DiffAppAgent is passed using $<strong>ns</strong> <strong>at</strong>tach-diffapp $node $app where the applic<strong>at</strong>ion$app is <strong>at</strong>tached to the node object $node.So for the reaso<strong>ns</strong> explained above the co<strong>ns</strong>tructors are different in non NS_DIFFUSION context as shown below.#ifdef NS_DIFFUSIONLogFilter::LogFilter()#elseLogFilter::LogFilter(int argc, char **argv)#endif // NS_DIFFUSION// Cre<strong>at</strong>e Diffusion Routing class#ifndef NS_DIFFUSIONparseComm<strong>and</strong>Line(argc, argv);dr_ = NR::cre<strong>at</strong>eNR(diffusion_port_);#endif // !NS_DIFFUSIONfilter_callback_ = new LogFilterReceive(this);#ifndef NS_DIFFUSION// Set up the filterfilter_h<strong>and</strong>le_ = setupFilter();......#endif // !NS_DIFFUSION198


Next you need to add the c++ function comm<strong>and</strong>(..) th<strong>at</strong> allows execution of tcl comm<strong>and</strong>s through the compiled shadowobject. For example the otcl comm<strong>and</strong> start is used to start a filter applic<strong>at</strong>ion as follows $app start. While comm<strong>and</strong>spublish <strong>and</strong> subscribe are used to start sender <strong>and</strong> receiver applic<strong>at</strong>io<strong>ns</strong> respectively. <strong>The</strong> comm<strong>and</strong> function is added,again with the NS_DIFFUSION scope using ifdef st<strong>at</strong>ements, as follows:#ifdef NS_DIFFUSIONint LogFilter::comm<strong>and</strong>(int argc, co<strong>ns</strong>t char*co<strong>ns</strong>t* argv)if (argc == 2)if (strcmp(argv[1], "start") == 0)run();return TCL_OK;return DiffApp::comm<strong>and</strong>(argc, argv);#endif // NS_DIFFUSIONNote how the parent class comm<strong>and</strong> function is invoked incase the comm<strong>and</strong> string is not found. Look into lib/diffapp.* tosee all otcl comm<strong>and</strong>s supported for the DiffApp class.Once these changes made to your c++ code, you would also need to write a tcl script (see the section on test-suite for exampletcl scripts) th<strong>at</strong> uses your diffusion applic<strong>at</strong>ion using the right tcl APIs.20.7 Test-suites for diffusionwe start with a simple testcase of 3 nodes with 1 ping source <strong>and</strong> 1 ping sender. <strong>The</strong>re are other tests for 2 phase-pull(2pp), 1phase-pull(1pp), push <strong>and</strong> gear (with 2pp <strong>and</strong> push) scenarios. In future we plan to extend the test-suite for testing differentcomponents/functionalities of directed diffusion. All diffusion3 rel<strong>at</strong>ed test cases can be found under ~<strong>ns</strong>/tcl/test/test-suitediffusion3.tcl.20.8 Comm<strong>and</strong>s <strong>at</strong> a glanceFollowing is a list of comm<strong>and</strong>s used for diffusion rel<strong>at</strong>ed simul<strong>at</strong>ion in <strong>ns</strong>.$<strong>ns</strong>_ node-config -adhocRouting $opt(adhocRouting)-llType $opt(ll)...-diffusionFilter $opt(filters)-stopTime $(pre-stop)...where,value of opt(adhocRouting) is set to Directed_DiffusionThis comm<strong>and</strong> is used to enable directed diffusion in wireless nodes.value of opt(filters) can be a list of filters th<strong>at</strong> is required to be <strong>at</strong>tached to diffusion nThis comm<strong>and</strong> allows adding filter objects to diffusion-enabled nodes.199


value of opt(pre-stop) is usually the time simul<strong>at</strong>ion stops when all st<strong>at</strong>istical d<strong>at</strong>a is dumpThis comm<strong>and</strong> allows dumping of st<strong>at</strong>istical d<strong>at</strong>a into an output file after running a diffusio<strong>ns</strong>et src [new Applic<strong>at</strong>ion/DiffApp/PingSender]This comm<strong>and</strong> is used to cre<strong>at</strong>e ping-sender applic<strong>at</strong>ion.set snk [new Applic<strong>at</strong>ion/DiffApp/PingReceiver]This comm<strong>and</strong> is used to cre<strong>at</strong>e ping-receiver applic<strong>at</strong>ion.set src [new Applic<strong>at</strong>ion/DiffApp/PushSender]This comm<strong>and</strong> is used to cre<strong>at</strong>e push-sender applic<strong>at</strong>ion.set snk [new Applic<strong>at</strong>ion/DiffApp/PushReceiver]This comm<strong>and</strong> is used to cre<strong>at</strong>e push-receiver applic<strong>at</strong>ion.set src [new Applic<strong>at</strong>ion/DiffApp/GearSenderApp]This comm<strong>and</strong> is used to cre<strong>at</strong>e gear-sender applic<strong>at</strong>ion.set snk [new Applic<strong>at</strong>ion/DiffApp/GearReceiverApp]This comm<strong>and</strong> is used to cre<strong>at</strong>e gear-receiver applic<strong>at</strong>ion.$gearApp push-pull-optio<strong>ns</strong> This comm<strong>and</strong> defines the type of routing algorithm gear is using. Incase the second option is defined as region, allfour co-ordin<strong>at</strong>es should be defined. While if point is chosen, only X1 <strong>and</strong> Y1 maybe defined.$<strong>ns</strong>_ <strong>at</strong>tach-diffapp $node_ $src_where the diffusion applic<strong>at</strong>ion $src_ gets <strong>at</strong>tached to the given $node_.$src_(0) publishComm<strong>and</strong> to start a ping source (sender).$snk_(0) subscribeComm<strong>and</strong> to start a ping sink (receiver).200


Chapter 21XCP: eXplicit Congestion control ProtocolXCP is a feedback-based congestion control system th<strong>at</strong> uses direct, explicit, router feedback to avoid congestion in thenetwork. It is designed for both scalability <strong>and</strong> generality. It was developed by Dina K<strong>at</strong>abi, starting from a suggestion byMark H<strong>and</strong>ley (refer to [?] for detailed descriptio<strong>ns</strong>). <strong>The</strong> <strong>ns</strong> code for XCP which was originally developed by Dina K<strong>at</strong>abiwas modified, extended <strong>and</strong> integr<strong>at</strong>ed into <strong>ns</strong>-2.28 <strong>at</strong> USC/ISI. It still continues to evolve as of today. If you are interested inlooking <strong>at</strong> Dina’s original source code please go to her website <strong>at</strong> http://www.ana.lcs.mit.edu/dina/XCP/21.1 Wh<strong>at</strong> is XCP?XCP is a congestion control protocol th<strong>at</strong> can be applied to any tra<strong>ns</strong>port protocol. It performs especially well in very highdelay-b<strong>and</strong>width product networks. Typically in large b<strong>and</strong>width-delay product networks, efficiency of TCP goes down inthe event of multiple of packet losses <strong>and</strong> becomes u<strong>ns</strong>table irrespective of queueing schemes used. However in similarenvironments, XCP, using a control theory based feedback model, achieves much more efficiency, stability <strong>and</strong> fairness bysending feedback from the network to the sender for setting the d<strong>at</strong>a flow into the network.XCP’s scalability results from the fact th<strong>at</strong> it requires no per-flow st<strong>at</strong>e in the router to calcul<strong>at</strong>e the feedback. Most routerassistedcongestion control systems maintain per-flow inform<strong>at</strong>ion used to alloc<strong>at</strong>e the resources. XCP keeps very littleinform<strong>at</strong>ion in the router, <strong>and</strong> this inform<strong>at</strong>ion is chosen to minimize both the amount of router st<strong>at</strong>e <strong>and</strong> the per-packetoper<strong>at</strong>io<strong>ns</strong> needed to upd<strong>at</strong>e th<strong>at</strong> st<strong>at</strong>e.For generality, XCP divides the resource alloc<strong>at</strong>ion function between two controllers: a congestion controller th<strong>at</strong> e<strong>ns</strong>uresth<strong>at</strong> flows use all available capacity, <strong>and</strong> a fairness controller th<strong>at</strong> e<strong>ns</strong>ures th<strong>at</strong> flows are alloc<strong>at</strong>ed the capacity fairly. Mostcongestion control systems fail to make this division, much less to implement as two conceptually distinct systems. Thisdivision allows a clear exposition <strong>and</strong> implement<strong>at</strong>ion of two basic resource alloc<strong>at</strong>ion functio<strong>ns</strong> in XCP. XCP sources sendadditional inform<strong>at</strong>ion about their current round-trip times <strong>and</strong> router-assigned throughput in each packet. XCP routers i<strong>ns</strong>ertfeedback into the packets th<strong>at</strong> is interpreted by the sources.Although XCP may be implemented for any tra<strong>ns</strong>port protocol, however as an initial test it has been implemented in TCP.<strong>The</strong> next section gives details of the way XCP is implemented in <strong>ns</strong>.201


21.2 Implement<strong>at</strong>ion of XCP in NSIn <strong>ns</strong>, the XCP implement<strong>at</strong>ion can be found under ~<strong>ns</strong>/xcp directory. <strong>The</strong> protocol needs to be deployed in the TCP endpoints (source <strong>and</strong> receiver) as well within the intermedi<strong>at</strong>e nodes which is mostly the router <strong>and</strong> may sometimes be a linklayerswitch as well. <strong>The</strong> end-point part of XCP code may be found under xcp-end-sys.cc,h <strong>and</strong> the router portion of the codemay be found under xcp.cc,h <strong>and</strong> xcpq.cc,h.21.2.1 Endpoints in XCP<strong>The</strong> end points co<strong>ns</strong>ist of TCP source <strong>and</strong> sink agents using XCP as their congestion control mechanism. <strong>The</strong> intermedi<strong>at</strong>enode or router writes feedback in each packet header as the delta_throughput value, about the d<strong>at</strong>a capacity th<strong>at</strong> may be incrementedif feedback is positive <strong>and</strong> should be decreased if neg<strong>at</strong>ive. When this packet reaches the receiver this delta_throughputvalue is returned to the sender in a reverse_feedback field of a congestion header in the returning packet, which is an ACKpacket in case of TCP.<strong>The</strong> sender upon receiving this reverse_feedback value adjusts its sending r<strong>at</strong>e by increasing or decreasing its congestionwindow size as the case maybe.<strong>The</strong> packet header th<strong>at</strong> is used by XCP is implemented as a structure called hdr_xcp in <strong>ns</strong> <strong>and</strong> is defined as follows:double x_; // idealized inter-packet timedouble rtt_;enum {XCP_DISABLED = 0,XCP_ENABLED,XCP_ACK,} xcp_enabled_; // to indic<strong>at</strong>e th<strong>at</strong> the flow is XCP enabledint xcpId_; // Sender’s ID (debugging only)double cwnd_; // <strong>The</strong> current window (debugging only)double reverse_feedback_;// --- Initialized by source <strong>and</strong> Upd<strong>at</strong>ed by Routerdouble delta_throughput_;u<strong>ns</strong>igned int controlling_hop_;// router ID (debugging only)<strong>The</strong> xcp receiver is respo<strong>ns</strong>ible for copying the delta_throughput value into the reverse_feedback field of the ack packets. I<strong>ns</strong>ome cases where delayed ack is used, the receiver calcul<strong>at</strong>es the sum of the delta_throughput values in arriving packets forcopying into the reverse_feedback field of the outgoing ack packet.<strong>The</strong> controlling_hop_ field th<strong>at</strong> carries the address of the router who has last upd<strong>at</strong>ed the feedback is used for debuggingpurposes only.In case of a packet loss in the network, TCP’s Van Jacobson congestion control should most likely override XCP. Howeverin <strong>ns</strong>this happe<strong>ns</strong> a little differently. With receiving of duplic<strong>at</strong>e acks indic<strong>at</strong>ing packet loss, the cwnd gets halved <strong>and</strong> fastretra<strong>ns</strong>mit <strong>and</strong> fast recovery algorithms come into play. However xcp routers continue to send feedback to the source based onwhich the source tries to open its cwnd. So it seems to be a mish-mash of VJCC <strong>and</strong> XCP algorithms. However for most casesthis issue doesnot arise as XCP router very rarely experiences a pkt drop as the queue is continuously regul<strong>at</strong>ed <strong>and</strong> drainedby XCP. Underst<strong>and</strong>ing the correct behaviour of XCP in face of pkt loss is an area of current study <strong>and</strong> shall be implementedin the future.202


21.2.2 XCP Router<strong>The</strong> XCP router co<strong>ns</strong>ists of a wrapper class th<strong>at</strong> holds virtual queues for XCP, TCP <strong>and</strong> OTHER traffic flows. OTHER flowmaybe anything other than XCP <strong>and</strong> TCP. In the current implement<strong>at</strong>ion, the XCP queue is a drop-tail queue while those forTCP <strong>and</strong> OTHER use RED.<strong>The</strong>se underlying queues are bundled in a wrapper class XCPWrapQ th<strong>at</strong> provides necessary interface to the XCP router.<strong>The</strong> XCP/TCP/OTHER queues are serviced in a Weighted Round-Robin manner. Each queue has a weight th<strong>at</strong> determinesthe percentage of the service it receives. <strong>The</strong> current queue weights of 0.5 each for the XCP <strong>and</strong> TCP allows equal servicebetween the two. <strong>The</strong> third queue reserved for OTHER flows has not been used as yet <strong>and</strong> has a weight of 0.0.OTCL Class Queue/XCP has a flag named tcp_xcp_on_ which is set to a default value of 0. This should be set to 1 for thosesimul<strong>at</strong>io<strong>ns</strong> th<strong>at</strong> use both XCP <strong>and</strong> TCP flows. This flag is used to split the link capacity of the router between the XCP <strong>and</strong>TCP queues in simul<strong>at</strong>io<strong>ns</strong> th<strong>at</strong> use both flow types. This is supposed to be a temporary fix <strong>and</strong> should go away once thedynamic queue weights come into effect. A cave<strong>at</strong> for the tcp_xcp flag is th<strong>at</strong> it is set as an OTcl class variable <strong>and</strong> not peri<strong>ns</strong>tance variable. This might cause some problems in topologies th<strong>at</strong> uses mix of intermittent xcp <strong>and</strong> tcp flows for whichsome router would require to support both TCP <strong>and</strong> XCP <strong>and</strong> some wouldn’t.Every packet received by the wrapper queue class is first marked or assigned a code point depending on the type of the packet.Packets, for the current TCP implement<strong>at</strong>ion, are marked for XCP, TCP/TCP-ACK <strong>and</strong> OTHER packets. This code point isused to enque packets in the right queue. <strong>The</strong> wrapper class is implemented in xcp.cc,h.21.2.3 XCP queue<strong>The</strong> XCP queue is respo<strong>ns</strong>ible for sending back feedback in every packet header which is used by the sender to control r<strong>at</strong>e ofsending d<strong>at</strong>a packets into the network. XCP uses two control algorithms, the congestion controller <strong>and</strong> the fairness controllerth<strong>at</strong> are executed once every estim<strong>at</strong>ion control interval, Te.In <strong>ns</strong> the estim<strong>at</strong>ion_timer is used to maintain this interval which is based on the average rtt values of the (xcp) flows seenthrough the router. However there may be better ways of defining this interval. <strong>The</strong> outst<strong>and</strong>ing queue in the router is measured<strong>at</strong> a separ<strong>at</strong>e interval Tq, for which a queue_timer is used. Finally an rtt_timer is used to measure certain parameters in therouter like packet drops, queue size, utiliz<strong>at</strong>ion etc for a given interval Tr, th<strong>at</strong> may either be set by user from tcl scripts or itmay use the highest rtt value seen for all flows in the router.<strong>The</strong> rtt_timer interval value, Tr maybe set from tcl using the following API:$queue queue-sample-everyrtt $rtt_valuewhere $queue is a h<strong>and</strong>le to the xcp router <strong>and</strong> $rtt_value is the interval for which xcp queue parameters like packet drop ,queue size etc shall be measured. See example script under ~<strong>ns</strong>/tcl/ex/xcp/parking_lot_topo/parking_lot_topo.tcl for use ofthis API.On packet arrival the total input traffic seen <strong>at</strong> the XCP queue is incremented by the size of the packet received. <strong>The</strong> sum ofinversed throughput <strong>and</strong> sum of rtt by throughput is incremented as well. Values for throughput <strong>and</strong> rtt are read from the xcpheader as set by the TCP source. Each value is normalised by the packet size.On the event of the estim<strong>at</strong>ion timer going off, average rtt of all flows is estim<strong>at</strong>ed using the above two sums as followsavg_rtt = sum_rtt_by_throughput/ sum_inv_throughput<strong>The</strong> aggreg<strong>at</strong>e feedback is calcul<strong>at</strong>ed based on the available b<strong>and</strong>width capacity of the router, arriving traffic b<strong>and</strong>width <strong>and</strong>203


the persistent queue length in the router. Further detailed explan<strong>at</strong>ion of calcul<strong>at</strong>io<strong>ns</strong> used by the XCP router algorithm canbe found in XCP specific<strong>at</strong>ion available from XCP’s website <strong>at</strong> http://www.isi.edu/isi-xcp/docs/draft-falk-xcp-spec-00.txtEach packet carries the current throughput value of the flow <strong>and</strong> a throughput adjustment or the delta_throughput in itsheader. <strong>The</strong> XCP router based on the feedback values it calcul<strong>at</strong>es in the estim<strong>at</strong>ion control timeout, calcul<strong>at</strong>es a per-packetthroughput adjustment feedback for every packet. Positive feedback is applied equally per-flow while neg<strong>at</strong>ive feedback ismade proportional to each flow’s capacity. Also a dow<strong>ns</strong>ream router can change the delta_throughput value in a packet’sheader only if the feedback value calcul<strong>at</strong>ed is less than th<strong>at</strong> in the header (written by an less congested upstream router). <strong>The</strong>implement<strong>at</strong>ion of XCP queue in <strong>ns</strong> may be found in xcpq.{cc,h}.21.3 XCP example scriptLet’s walk through a simple xcp script th<strong>at</strong> is similar to ~<strong>ns</strong>/tcl/ex/xcp/xcp_test.tcl <strong>The</strong> example uses a small dumbbelltopology having 3 xcp sources running over a bottleneck link.<strong>The</strong> topology is setup using the node <strong>and</strong> link cre<strong>at</strong>ion APIs. <strong>The</strong> bottleneck is a duplex link th<strong>at</strong> has a xcp router in bothdirectio<strong>ns</strong>. For details on cre<strong>at</strong>ing nodes, links etc in <strong>ns</strong> see Marc Greis’ NS tutorial <strong>at</strong> http://www.isi.edu/<strong>ns</strong>nam/<strong>ns</strong>/tutorial.<strong>The</strong> bottleneck link having a XCP queue is cre<strong>at</strong>ed as follows:set R0 [$<strong>ns</strong> node] ;# cre<strong>at</strong>e Bottleneck between nodes R0 <strong>and</strong> R1set R1 [$<strong>ns</strong> node]$<strong>ns</strong> duplex-link $R0 $R1 Mb ms XCP<strong>The</strong> side links connecting source nodes to the bottleneck link have XCP queues as well. <strong>The</strong> API queue-limit allowsusers to set the buffer size in the queue.<strong>The</strong> xcp source <strong>and</strong> sink is cre<strong>at</strong>ed as follows (very similar to tcp):set xcp [new Agent/TCP/Reno/XCP]$<strong>ns</strong> <strong>at</strong>tach-agent $src_node $xcpset xcp_sink [new Agent/TCPSink/XCPSink]$<strong>ns</strong> <strong>at</strong>tach-agent $rcvr_node $xcp_sink$<strong>ns</strong> connect $xcp $xcp_sink......<strong>The</strong>re is a tcl class GeneralSender used in the example script th<strong>at</strong> sets up xcp agents in the source nodes <strong>and</strong> then connectsthem to the xcp receiver in the destin<strong>at</strong>ion node. An FTP source is used in all the 3 sources.Note th<strong>at</strong> once the topology is set up the link b<strong>and</strong>width inform<strong>at</strong>ion needs to be propag<strong>at</strong>ed to the xcp queue as this is usedby the xcp router for feedback calcul<strong>at</strong>ion. So for every xcp queue use the following tcl comm<strong>and</strong>:$xcp_queue set-link-capacity Next we need to trace variables in thexcp router <strong>and</strong> xcp sources. <strong>The</strong> GeneralSender class procedure trace-xcp sets up tracing for xcp sources using variabletracingin <strong>ns</strong>.204


GeneralSender i<strong>ns</strong>tproc trace-xcp parameters {$self i<strong>ns</strong>tvar tcp_ id_ tcpTrace_global ftracetcp$id_set ftracetcp$id_ [open xcp$id_.tr w]set tcpTrace_ [set ftracetcp$id_]$tcp_ <strong>at</strong>tach-trace [set ftracetcp$id_]if { -1 < [lsearch $parameters cwnd] } { $tcp_ tracevar cwnd_ }if { -1 < [lsearch $parameters seqno] } { $tcp_ tracevar t_seqno_ }}For tracing xcp queue it is required to <strong>at</strong>tach a file descriptor to the xcp queue.$xcpq <strong>at</strong>tach This is an example of how the trace <strong>at</strong> an xcp source looks like:0.00000 2 0 1 0 cwnd_ 1.0000.00000 2 0 1 0 t_seqno_ 00.079 x x x x throughput 0.10.07900 2 0 1 0 t_seqno_ 10.119064 x x x x reverse_feedback_ 00.119064 x x x x controlling_hop_ 00.119064 x x x x newcwnd 10.11906 2 0 1 0 cwnd_ 2.0000.119064 x x x x throughput 500000.11906 2 0 1 0 t_seqno_ 20.119064 x x x x throughput 500000.11906 2 0 1 0 t_seqno_ 3<strong>The</strong> first field gives the timestamp; the next 4 fields give the source id (node/port) <strong>and</strong> destin<strong>at</strong>ion id (node/port) for the xcpflow. <strong>The</strong> next field gives the name of the variable being traced followed by the value of the variable. Note th<strong>at</strong> variables likecwnd_, t_seqno_ are using variable tracing which is a function supported by the OTcl lib. While variables like throughput,reverse_feedback use the XCPAgent class function trace_var defined in xcp-end-sys.cc. For more on variable tracing in <strong>ns</strong>please read section 3.4.3 in the <strong>ns</strong> manual <strong>at</strong> http://www.isi.edu/<strong>ns</strong>nam/<strong>ns</strong>/doc/index.htmlAnd example of trace output <strong>at</strong> a xcp bottleneck router looks like below:Tq_ 0.0472859 0.025queue_bytes_ 0.0472859 0routerId_ 0.0472859 0pos_fbk 0.053544 0neg_fbk 0.053544 0delta_throughput 0.053544 0Thruput2 0.053544 60000pos_fbk 0.054024 0neg_fbk 0.054024 0delta_throughput 0.054024 0205


Thruput2 0.054024 60000residue_pos_fbk_not_alloc<strong>at</strong>ed 0.0638023 0residue_neg_fbk_not_alloc<strong>at</strong>ed 0.0638023 0input_traffic_bytes_ 0.0638023 2480avg_rtt_ 0.0638023 0.04Here the first field describes the name of the variable, the second field gives the timestamp <strong>and</strong> the third field gives the valueof the variable. <strong>The</strong> XCPQueue class function trace_var() is used to trace variables in the xcp queue.Additionally packet traces may be cre<strong>at</strong>ed in <strong>ns</strong> using the following tcl APIs:set f_all [open out.tr w]$<strong>ns</strong> trace-all $f_allFirst open a file <strong>and</strong> then <strong>at</strong>tach the file descriptor to the <strong>ns</strong> trace object such th<strong>at</strong> a trace of each packet as it travels throughthe network is logged <strong>and</strong> dumped into the output file.An example of such a file would look like:+ 0.003 4 0 xcp 40 ------- 2 4.0 1.2 0 0- 0.003 4 0 xcp 40 ------- 2 4.0 1.2 0 0r 0.013016 4 0 xcp 40 ------- 2 4.0 1.2 0 0+ 0.013016 0 1 xcp 40 ------- 2 4.0 1.2 0 0- 0.013016 0 1 xcp 40 ------- 2 4.0 1.2 0 0r 0.023032 0 1 xcp 40 ------- 2 4.0 1.2 0 0+ 0.023032 1 0 ack 40 ------- 2 1.2 4.0 0 1- 0.023032 1 0 ack 40 ------- 2 1.2 4.0 0 1r 0.033048 1 0 ack 40 ------- 2 1.2 4.0 0 1+ 0.033048 0 4 ack 40 ------- 2 1.2 4.0 0 1- 0.033048 0 4 ack 40 ------- 2 1.2 4.0 0 1r 0.043064 0 4 ack 40 ------- 2 1.2 4.0 0 1+ 0.043064 4 0 xcp 1200 ------- 2 4.0 1.2 1 2- 0.043064 4 0 xcp 1200 ------- 2 4.0 1.2 1 2+ 0.043064 4 0 xcp 1200 ------- 2 4.0 1.2 2 3- 0.043544 4 0 xcp 1200 ------- 2 4.0 1.2 2 3Lets try to read the first line:+ 0.003 4 0 xcp 40 ----- 2 4.0 1.2 0 0+ mea<strong>ns</strong> a packet is enqueued in the queue (in node 4) as it hopped between node 4 to node 0. You’ll find traces showingpackets enqued (+) <strong>and</strong> then dequed (-) <strong>at</strong> the queue, after which it is tra<strong>ns</strong>mitted over the link to be received by the next node.packet type is xcp <strong>and</strong> it is of size 40 bytes. <strong>The</strong> xcp flow has an id of 2 <strong>and</strong> the packet header has a source node/port id of4.0 <strong>and</strong> dest node/port id of 1.2 <strong>and</strong> the unique packet id is 0.206


21.4 Test-suites for XCP<strong>The</strong> xcp test-suite uses 3 tests. <strong>The</strong> first one is similar to the one we discussed in the earlier section. It co<strong>ns</strong>ists of a dumb-belltopology where 3 xcp flows share a bottleneck link. <strong>The</strong> second test has a similar topology having 3 xcp <strong>and</strong> 1 tcp flow sharingthe same bottleneck. And finally the last test is built on Dina K<strong>at</strong>abi’s parking-lot experiment referred in her SIGCOMM’02paper. It is a dow<strong>ns</strong>ized version of Dina’s example. <strong>The</strong> test uses a 9-hop link string topology. It has 10 long XCP flows th<strong>at</strong>flow through the entire length of the chain topology. <strong>The</strong>n it has 10 XCP flows th<strong>at</strong> run through each hop, starting <strong>at</strong> (n-1)thhop <strong>and</strong> ending <strong>at</strong> nth hop <strong>and</strong> so on cre<strong>at</strong>ing the intermittent flows. And finally there are long XCP flows in the reversedirection, starting from the last (10th) node <strong>and</strong> ending in the first (1st) node. <strong>The</strong>re is a bottleneck <strong>at</strong> the middle of the chaintopology. Thus the third test employs a large <strong>and</strong> complex topology <strong>and</strong> shows the utiliz<strong>at</strong>ion, queue length <strong>and</strong> packet dropvalues <strong>at</strong> every link.21.5 Comm<strong>and</strong>s <strong>at</strong> a glanceFollowing is a list of comm<strong>and</strong>s used for xcp rel<strong>at</strong>ed simul<strong>at</strong>ion in <strong>ns</strong>.set xcp_src [new Agent/TCP/Reno/XCP]This comm<strong>and</strong> cre<strong>at</strong>es an XCP source agent.set xcp_dst [new Agent/TCPSink/XCPSink]This comm<strong>and</strong> cre<strong>at</strong>es an XCP sink.$<strong>ns</strong> duplex-link $R0 $R1 Mb ms XCPThis code cre<strong>at</strong>es a duplex link with specified b<strong>and</strong>width <strong>and</strong> link delay using an XCP router between node R0 <strong>and</strong> R1.$xcp_queue set-link-capacity This comm<strong>and</strong> propag<strong>at</strong>es the link b<strong>and</strong>width inform<strong>at</strong>ion to the xcp queue which uses it for the router feedback calcul<strong>at</strong>ion.set tfile [open tfile w]$xcp_queue <strong>at</strong>tach $tfileThis Tcl comm<strong>and</strong> allows a file to be <strong>at</strong>tached for tracing xcp queue parameters.$xcp_src <strong>at</strong>tach-trace $xcp_src tracevar This comm<strong>and</strong> allows the xcp sources to trace variables.$queue queue-sample-everyrtt $rtt_valueThis comm<strong>and</strong> allows the user to set rtt interval values <strong>at</strong> which variables like packet_drops <strong>and</strong> queue lengths are measured<strong>at</strong> the xcp queue.Queue/XCP set tcp_xcp_on_ 1This flag lets tcp <strong>and</strong> xcp flows to use the same xcp router. This flag is a temporary fix <strong>and</strong> should go away when dynamicqueue weights come into effect.207


Chapter 22DelayBox: Per-Flow Delay <strong>and</strong> LossDelayBox is an <strong>ns</strong> node th<strong>at</strong> should be placed in between the source <strong>and</strong> destin<strong>at</strong>ion nodes. With Delaybox, packets froma TCP flow can be delayed, dropped, <strong>and</strong>/or forced through a bottleneck link before being passed on to the next node. Adistribution can be used to specify delay, loss, <strong>and</strong>/or bottleneck link speed for a source - destin<strong>at</strong>ion pair. Each flow betweenth<strong>at</strong> source - destin<strong>at</strong>ion pair draws from the distribution to determine its characteristics. Delays in DelayBox are per-flow,r<strong>at</strong>her than per-packet. Since DelayBox distinguishes between flows, the fid_ variable (flow identifier) should be set foreach flow in the simul<strong>at</strong>ion. DelayBox can be used with both Tcp <strong>and</strong> FullTcp agents.22.1 Implement<strong>at</strong>ion DetailsDelayBox maintai<strong>ns</strong> two tables: a rule table <strong>and</strong> a flow table. Entries in the rule table are added by the user in the OTclsimul<strong>at</strong>ion script <strong>and</strong> give an outline of how flows from a source to a destin<strong>at</strong>ion should be tre<strong>at</strong>ed. <strong>The</strong> fields are source,destin<strong>at</strong>ion, delay R<strong>and</strong>om Variable (in ms), loss r<strong>at</strong>e R<strong>and</strong>om Variable (in fraction of packets dropped), <strong>and</strong> bottleneck linkspeed R<strong>and</strong>om Variable (in Mbps). <strong>The</strong> bottleneck link speed field is optional. Entries in the flow table are cre<strong>at</strong>ed internally<strong>and</strong> specify exactly how each flow should be h<strong>and</strong>led. Its values are obtained by sampling from the distributio<strong>ns</strong> given in therule table. <strong>The</strong> fields are source, destin<strong>at</strong>ion, flow ID, delay, loss, <strong>and</strong> bottleneck link speed (if applicable). Full-TCP flowsare defined as beginning <strong>at</strong> the receipt of the first SYN of a new flow ID <strong>and</strong> ending after the sending of the first FIN. Packetsafter the first FIN are forwarded immedi<strong>at</strong>ely (i.e., they are neither delayed nor dropped by DelayBox). For TcpAgent,flows are defined as beginning <strong>at</strong> the receipt of the first 40 byte packet of a new flow ID. Since there are no FIN packets inTcpAgent, TcpAgent flows are never co<strong>ns</strong>idered finished nor are they removed from the flow table.DelayBox also maintai<strong>ns</strong> a set of queues to h<strong>and</strong>le delaying packets. <strong>The</strong>re is one queue per entry in the flow table. <strong>The</strong>sequeues are implemented as delta queues, in th<strong>at</strong> the time to tra<strong>ns</strong>fer the packet is kept only for the head packet. All otherpackets are stored with the difference between the time they should be tra<strong>ns</strong>ferred <strong>and</strong> the time the previous packet shouldbe tra<strong>ns</strong>ferred. <strong>The</strong> actual time the previous packet should be tra<strong>ns</strong>ferred is stored in the variable deltasum_, named sobecause it is the sum of all delta values in the queue (including the head packet’s tra<strong>ns</strong>fer time). If the bottleneck link speedhas been specified for the flow, a processing delay is computed for each packet by dividing the size of the packet by the flow’sbottleneck link speed.When a packet is received, its tra<strong>ns</strong>fer time (current time + delay) is calcul<strong>at</strong>ed. (This tra<strong>ns</strong>fer time is the time th<strong>at</strong> the first bitof the packet will begin tra<strong>ns</strong>fer. Packets th<strong>at</strong> wait in the queue behind this packet must be delayed by the amount of time totra<strong>ns</strong>fer all bits of the packet over the bottleneck link.) <strong>The</strong>re are two scenarios to co<strong>ns</strong>ider in deciding how to set the packet’sdelta:208


1. If the packet is due to be tra<strong>ns</strong>ferred before the last bit of the last packet in the queue, its delta (the time betweentra<strong>ns</strong>ferring the previous packet <strong>and</strong> tra<strong>ns</strong>ferring this packet) is set to the previous packet’s processing delay. Thispacket has to queue behind the previous packet, but will be ready to be tra<strong>ns</strong>mitted as soon as the previous packet hascompleted its tra<strong>ns</strong>fer.2. If the packet is due to be tra<strong>ns</strong>ferred after the last bit of the last packet in the queue, its delta is difference between thispacket’s tra<strong>ns</strong>fer time <strong>and</strong> the previous packet’s tra<strong>ns</strong>fer time.If the current packet is the only packet in the queue, DelayBox schedules a timer for the receipt of the packet. When this timerexpires, DelayBox will pass the packet on to the st<strong>and</strong>ard packet forwarder for processing. Once a packet has been passed up,DelayBox will look for the next packet in the queue to be processed <strong>and</strong> schedule a timer for its tra<strong>ns</strong>fer. All packets, bothd<strong>at</strong>a <strong>and</strong> ACKs, are delayed in this manner.Packets th<strong>at</strong> should be dropped are neither queued nor passed on. All packets in a queue are from the same connection <strong>and</strong>are delayed the same amount (except for delays due to packet size) <strong>and</strong> are dropped with the same probability. Note: Drops<strong>at</strong> DelayBox are not recorded in the trace-queue file.22.2 ExampleMore examples are available in the tcl/ex/delaybox/ directory of the <strong>ns</strong> source code. <strong>The</strong> valid<strong>at</strong>ion script test-suite-delayboxis in tcl/test/ <strong>and</strong> can be run with the comm<strong>and</strong> test-all-delaybox from th<strong>at</strong> directory.# test-delaybox.tcl - NS file tra<strong>ns</strong>fer with DelayBox# setup <strong>ns</strong>remove-all-packet-headers;add-packet-header IP TCP;set <strong>ns</strong> [new Simul<strong>at</strong>or];# removes all packet headers# adds TCP/IP headers# i<strong>ns</strong>tanti<strong>at</strong>e the simul<strong>at</strong>orglobal defaultRNG$defaultRNG seed 999# cre<strong>at</strong>e nodesset n_src [$<strong>ns</strong> node]set db(0) [$<strong>ns</strong> DelayBox]set db(1) [$<strong>ns</strong> DelayBox]set n_sink [$<strong>ns</strong> node]# setup links$<strong>ns</strong> duplex-link $db(0) $db(1) 100Mb 1ms DropTail$<strong>ns</strong> duplex-link $n_src $db(0) 100Mb 1ms DropTail$<strong>ns</strong> duplex-link $n_sink $db(1) 100Mb 1ms DropTailset src [new Agent/TCP/FullTcp]set sink [new Agent/TCP/FullTcp]$src set fid_ 1$sink set fid_ 1# <strong>at</strong>tach agents to nodes$<strong>ns</strong> <strong>at</strong>tach-agent $n_src $src209


$<strong>ns</strong> <strong>at</strong>tach-agent $n_sink $sink# make the connection$<strong>ns</strong> connect $src $sink$sink listen# cre<strong>at</strong>e r<strong>and</strong>om variablesset recvr_delay [new R<strong>and</strong>omVariable/Uniform];$recvr_delay set min_ 1$recvr_delay set max_ 20set sender_delay [new R<strong>and</strong>omVariable/Uniform];$sender_delay set min_ 20$sender_delay set max_ 100set recvr_bw [new R<strong>and</strong>omVariable/Co<strong>ns</strong>tant];$recvr_bw set val_ 100set sender_bw [new R<strong>and</strong>omVariable/Uniform];$sender_bw set min_ 1$sender_bw set max_ 20set loss_r<strong>at</strong>e [new R<strong>and</strong>omVariable/Uniform];$loss_r<strong>at</strong>e set min_ 0$loss_r<strong>at</strong>e set max_ 0.01# delay 1-20 ms# delay 20-100 ms# bw 100 Mbps# bw 1-20 Mbps# loss 0-1% loss# setup rules for DelayBoxes$db(0) add-rule [$n_src id] [$n_sink id] $recvr_delay $loss_r<strong>at</strong>e $recvr_bw$db(1) add-rule [$n_src id] [$n_sink id] $sender_delay $loss_r<strong>at</strong>e $sender_bw# output delays to files$db(0) set-delay-file "db0.out"$db(1) set-delay-file "db1.out"# schedule traffic$<strong>ns</strong> <strong>at</strong> 0.5 "$src advance 10000"$<strong>ns</strong> <strong>at</strong> 1000.0 "$db(0) close-delay-file; $db(1) close-delay-file; exit 0"# start the simul<strong>at</strong>ion$<strong>ns</strong> run22.3 Comm<strong>and</strong>s <strong>at</strong> a Glance<strong>The</strong> following comm<strong>and</strong>s on the DelayBox class can be accessed from OTcl:[$<strong>ns</strong> DelayBox]Cre<strong>at</strong>es a new DelayBox node.$delaybox add-rule [] []Add a rule to the rule table, specifying delay, loss r<strong>at</strong>e, <strong>and</strong> bottleneck link speed R<strong>and</strong>omVariables for packets flowing fromsrcNode to dstNode. Delay is required, but loss r<strong>at</strong>e <strong>and</strong> link speed are optional.$delaybox list-rulesList all rules in the rule table210


$delaybox list-flowsList all flows in the flow table$delaybox set-asymmetricSpecifies th<strong>at</strong> the delay should be only on the d<strong>at</strong>a p<strong>at</strong>h r<strong>at</strong>her than applied to both the d<strong>at</strong>a <strong>and</strong> ACK p<strong>at</strong>hs$delaybox set-delay-file Output delays for each flow to filename. Form<strong>at</strong>: srcNode dstNode fid delay$delaybox close-delay-fileCloses the file where delays are written$delaybox set-debug Set the debugging level• 1: Output when packets are dropped <strong>at</strong> DelayBox• 2: Level 1 +Contents of the queue <strong>at</strong> each queue oper<strong>at</strong>ion211


Chapter 23Changes made to the IEEE 802.15.4Implement<strong>at</strong>ion in NS-2.31In the following, changes made to the IEEE 802.15.4 WPAN module in as of <strong>ns</strong> release 2.31 are described along with thereaso<strong>ns</strong> for the modific<strong>at</strong>io<strong>ns</strong> <strong>and</strong> a list of files affected. This file was authored by Iyappan Ramach<strong>and</strong>ran.23.1 Radio shutdownAbility to put a WPAN node to sleep has been added in this release.1. A macro called SHUTDOWN has been defined in ./wpan/p802_15_4def.h th<strong>at</strong> provides the capability to shut a nodedown when it does not have any packet to tra<strong>ns</strong>mit. Currently, there is no provision to enable/disable radio shutdownfrom the tcl interface directly, but an indirect way exists (see point 4).2. Two functio<strong>ns</strong> Phy802_15_4::wakeupNode() <strong>and</strong> Phy802_15_4::putNodeToSleep() have been added th<strong>at</strong> can be calledto shutdown <strong>and</strong> wake up the radio. <strong>The</strong>se functio<strong>ns</strong> primarily serve to decrement the correct amount of energy co<strong>ns</strong>umedin sleep st<strong>at</strong>e.File affected: ./wpan/p802_15_4phy.cc, ./wpan/p802_15_4phy.h3. A new timer called macWakeupTimer has been added to serve as an alarm clock for the node to wake itself up (forbeacon reception, etc.) before it shuts down. <strong>The</strong> timer on expiry calls Phy802_15_4::wakeupNode().Files changed: ./wpan/p802_15_4mac.cc, ./wpan/p802_15_4mac.h,./wpan/p802_15_4timer.cc,./wpan/p802_15_4timer.h,./wpan/p802_15_4csmaca.h4. Variables P_sleep_ (sleep st<strong>at</strong>e power co<strong>ns</strong>umption), P_tra<strong>ns</strong>ition_ (power co<strong>ns</strong>umption in sleep-wakeup tra<strong>ns</strong>ition)<strong>and</strong> T_tra<strong>ns</strong>ition_ (time taken for sleep-wakeup tra<strong>ns</strong>ition) already exist in mac/wireless-phy.h. T_tra<strong>ns</strong>ition_ was notinitialized earlier <strong>and</strong> now has been. In addition, a new vew variable named T_sleep_ has been added to wireless-phyto indic<strong>at</strong>e the time <strong>at</strong> which radio shutdown is to be enabled. This can be set from the tcl interface using the variablename sleepTime (see ./tcl/ex/wpan_demo_sleep.tcl). Thus, it is possible to keep the SHUTDOWN macro #defined, butset sleepTime to a very large value to keep radio shutdown disabled throughout the simul<strong>at</strong>io<strong>ns</strong>. This provides a mea<strong>ns</strong>to turn on/off radio shutdown from the tcl interface.Files affected: mac/wireless-phy.h212


5. <strong>The</strong> radio if asleep should be woken up when MAC receives a packet to tra<strong>ns</strong>mit. Similarly, a sleeping radio needsto be woken up to receive beaco<strong>ns</strong> whenever they are expected to arrive. If radio shutdown is activ<strong>at</strong>ed, the radioneeds to be put to sleep after tra<strong>ns</strong>mission of a packet. Mac802_15_4::recv() does this by calling functio<strong>ns</strong>Phy802_15_4::wakeupNode() <strong>and</strong> Phy802_15_4::putNodeToSleep(), which decrement energy spent sleeping.Files affected: ./wpan/p802_15_4mac.cc6. After every beacon reception, the node can shut itself down if it doesn’t have a packet pending to be tra<strong>ns</strong>mitted when radioshutdown has been activ<strong>at</strong>ed. This is done by Mac802_15_4::recvBeacon()by calling Phy802_15_4::putNodeToSleep().Files affected: ./wpan/p802_15_4mac.cc7. If the node is being put to sleep when not in use, the sleep-to-idle tra<strong>ns</strong>ition needs to be accounted for. This is done inCsmaCA802_15_4::start(). <strong>The</strong> backoff time for the first backoff stage is calcul<strong>at</strong>ed as wtime=MAX(wtime,ceil(phy→T_tra<strong>ns</strong>ition_locFiles affected: ./wpan/p802_15_4csmaca.cc23.2 Other changes1. After backing off macMaxCSMABackoffs <strong>and</strong> being unable to tra<strong>ns</strong>mit a packet, the MAC has to report a channel accessfailure. <strong>The</strong> older implement<strong>at</strong>ion kept <strong>at</strong>tempting to tra<strong>ns</strong>mit the packet indefinitely, i<strong>ns</strong>tead of reporting channel accessfailure. This has been fixed in the Mac802_15_4::mcps_d<strong>at</strong>a_request() function. Also the node is put to sleep (if needbe) <strong>at</strong> this stage.Files affected: ./wpan/p802_15_4mac.cc2. A new co<strong>ns</strong>tant called aCCATime has been added, which indic<strong>at</strong>es the CCA dur<strong>at</strong>ion in symbol periods.Files affected: ./wpan/p802_15_4co<strong>ns</strong>t.h3. CCA dur<strong>at</strong>ion has been specified to be 8 symbol dur<strong>at</strong>io<strong>ns</strong>. In the older implement<strong>at</strong>ion, CCA was being done right<strong>at</strong> the end of the 8th symbol dur<strong>at</strong>ion to determine channel idleness. As a result, if the channel is busy for the first 8symbol dur<strong>at</strong>io<strong>ns</strong> <strong>and</strong> goes idle after th<strong>at</strong> (which is likely), the implement<strong>at</strong>ion would indic<strong>at</strong>e channel idle while inreality it shouldn’t. This has been fixed by doing the CCA <strong>at</strong> the end of the 4th symbol dur<strong>at</strong>ion, but reporting channelst<strong>at</strong>us <strong>at</strong> the 8th. For this purpose, a new timer CCAReportH has been added which on expiry calls CCAReportH<strong>and</strong>lerth<strong>at</strong> does the reporting. Files affected: ./wpan/p802_15_4phy.cc, ./wpan/p802_15_4phy.h4. <strong>The</strong> Phy802_15_4::PD_DATA_indic<strong>at</strong>ion() function calls WirelessChannel::sendUp() to check if the packet has beenreceived correctly <strong>and</strong> to decrement the energy co<strong>ns</strong>umed in the packet reception. <strong>The</strong> SendUp() function is alreadybeing called by recv() <strong>and</strong> calling it a second time causes energy to be decremented twice. This bug has been fixed inPhy802_15_4::PD_DATA_indic<strong>at</strong>ion().Files affected: ./wpan/p802_15_4phy.cc5. Phy802_15_4::recv() function th<strong>at</strong> receives packets from the channel checks if the packet has been received correctlyusing WirelessPhy::sendUp(), failing which the packet is freed. sendUp() retur<strong>ns</strong> a 0 either when the node is asleepor when the packets received power is less than the CS threshold. In the former case, the variables rxTotPower <strong>and</strong>rxTotNum need to be upd<strong>at</strong>ed for CS purposes before dropping the packet, while in the l<strong>at</strong>ter case the packet simplyneeds to be dropped. Zheng’s implement<strong>at</strong>ion was dropping all packets without upd<strong>at</strong>ing the variables. This has beenfixed in Phy802_15_4::recv().Files affected: ./wpan/p802_15_4phy.cc6. <strong>The</strong> receiver has to be turned on for the carrier se<strong>ns</strong>ing oper<strong>at</strong>ion <strong>and</strong> therefore receive power P r is co<strong>ns</strong>umed duringthis period. <strong>The</strong> earlier implement<strong>at</strong>ion did not decrement receive energy due to carrier se<strong>ns</strong>ing. This has been addedin function Phy802_15_4::CarrierSe<strong>ns</strong>er(). Also, energy is spent during the tx-rx turnaround. This has been accountedfor as well.Files affected: ./wpan/p802_15_4phy.cc213


Part IIISupport214


Chapter 24Debugging <strong>ns</strong><strong>ns</strong>is a simul<strong>at</strong>or engine built in C++ <strong>and</strong> has an OTcl (Object-oriented Tcl) interface th<strong>at</strong> is used for configur<strong>at</strong>ion <strong>and</strong>comm<strong>and</strong>s. Thus in order to debug <strong>ns</strong>we will have to deal with debugging issues involving both OTcl <strong>and</strong> C++. This chaptergives debugging tips <strong>at</strong> Tcl <strong>and</strong> C++ level <strong>and</strong> shows how to move to-fro the Tcl <strong>and</strong> C++ boundaries. It also briefly coversmemory debugging <strong>and</strong> memory co<strong>ns</strong>erv<strong>at</strong>ion in <strong>ns</strong>.24.1 Tcl-level DebuggingNs supports Don Libs’ Tcl debugger ( see its Postscript document<strong>at</strong>ion <strong>at</strong> http://expect.nist.gov/tcl-debug/tcl-debug.ps.Z <strong>and</strong>its source code <strong>at</strong> http://expect.nist.gov/tcl-debug/tcl-debug.tar.gz ). I<strong>ns</strong>tall the program or leave the source code in a directoryparallel to <strong>ns</strong>-2 <strong>and</strong> it will be built. Unlike expect, described in the tcl-debug document<strong>at</strong>ion, we do not support the -Dflag. To enter the debugger, add the lines "debug 1" to your script <strong>at</strong> the appropri<strong>at</strong>e loc<strong>at</strong>ion. In order to build <strong>ns</strong> withthe debugging flag turned on, configure <strong>ns</strong> with configur<strong>at</strong>ion option "–enable-debug" <strong>and</strong> incase the Tcl debugger has beeni<strong>ns</strong>talled in a directory not parallel to <strong>ns</strong>-2, provide the p<strong>at</strong>h with configur<strong>at</strong>ion option "–with-tcldebug=".An useful debugging comm<strong>and</strong> is $<strong>ns</strong>_ gen-map which may be used to list all OTcl objects in a raw form. This is usefulto correl<strong>at</strong>e the position <strong>and</strong> function of an object given its name. <strong>The</strong> name of the object is the OTcl h<strong>and</strong>le, usually of theform _o###. For TclObjects, this is also available in a C++ debugger, such as gdb, as this->name_.24.2 C++-Level DebuggingDebugging <strong>at</strong> C++ level can be done using any st<strong>and</strong>ard debugger. <strong>The</strong> following macro for gdb makes it easier to see wh<strong>at</strong>happe<strong>ns</strong> in Tcl-based subroutines:## for Tcl codedefine pargvcset $i=0while $i < argcp argv[$i]set $i=$i+1215


endenddocument pargvcPrint out argc argv[i]’s common in Tcl code.(presumes th<strong>at</strong> argc <strong>and</strong> argv are defined)end24.3 Mixing Tcl <strong>and</strong> C debuggingIt is a painful reality th<strong>at</strong> when looking <strong>at</strong> the Tcl code <strong>and</strong> debugging Tcl level stuff, one wants to get <strong>at</strong> the C-level classes, <strong>and</strong>vice versa. This is a smallish hint on how one can make th<strong>at</strong> task easier. If you are running <strong>ns</strong> through gdb, then the followingincant<strong>at</strong>ion (shown below) gets you access to the Tcl debugger. <strong>Notes</strong> on how you can then use this debugger <strong>and</strong> wh<strong>at</strong> youcan do with it are documented earlier in this chapter <strong>and</strong> <strong>at</strong> this URL (http://expect.nist.gov/tcl-debug/tcl-debug.ps.Z).(gdb) runStarting program: /nfs/prot/kannan/PhD/simul<strong>at</strong>ors/<strong>ns</strong>/<strong>ns</strong>-2/<strong>ns</strong>...Breakpoint 1, AddressClassifier::AddressClassifier (this=0x12fbd8)<strong>at</strong> classifier-addr.cc:47(gdb) p this->name_$1 = 0x2711e8 "_o73"(gdb) call Tcl::i<strong>ns</strong>tance().eval("debug 1")15: lappend auto_p<strong>at</strong>h $dbg_librarydbg15.3> w*0: applic<strong>at</strong>ion15: lappend auto_p<strong>at</strong>h /usr/local/lib/dbgdbg15.4> Simul<strong>at</strong>or info i<strong>ns</strong>tances_o1dbg15.5> _o1 now0dbg15.6> # <strong>and</strong> other fun stuffdbg15.7> _o73 info classClassifier/Addrdbg15.8> _o73 info varsslots_ shift_ off_ip_ offset_ off_flags_ mask_ off_cmn_dbg15.9> c(gdb) wAmbiguous comm<strong>and</strong> "w": while, wh<strong>at</strong>is, where, w<strong>at</strong>ch.(gdb) where#0 AddressClassifier::AddressClassifier (this=0x12fbd8)<strong>at</strong> classifier-addr.cc:47#1 0x5c68 in AddressClassifierClass::cre<strong>at</strong>e (this=0x10d6c8, argc=4,argv=0xefffcdc0) <strong>at</strong> classifier-addr.cc:63...(gdb)In a like manner, if you have started <strong>ns</strong> through gdb, then you can always get gdb’s <strong>at</strong>tention by sending an interrupt, usuallya on berkeloidrones. However, note th<strong>at</strong> these do tamper with the stack frame, <strong>and</strong> on occasion, may (sometimescan (<strong>and</strong> rarely, does)) screw up the stack so th<strong>at</strong>, you may not be in a position to resume execution. To its credit, gdb appearsto be smart enough to warn you about such i<strong>ns</strong>tances when you should tread softly, <strong>and</strong> carry a big stick.216


24.4 Memory Debugging<strong>The</strong> first thing to do if you run out of memory is to make sure you can use all the memory on your system. Some systems bydefault limit the memory available for individual programs to something less than all available memory. To relax this, use thelimit or ulimit comm<strong>and</strong>. <strong>The</strong>se are shell functio<strong>ns</strong>—see the manual page for your shell for details. Limit is for csh, ulimit isfor sh/bash.Simul<strong>at</strong>io<strong>ns</strong> of large networks can co<strong>ns</strong>ume a lot of memory. Ns-2.0b17 supports Gray W<strong>at</strong>son’s dmalloc library (see its webdocument<strong>at</strong>ion <strong>at</strong> http://www.letters.com/dmalloc/ <strong>and</strong> get the source code from ftp://ftp.letters.com/src/dmalloc/dmalloc.tar.gz). To add it, i<strong>ns</strong>tall it on your system or leave its source in a directory parallel to <strong>ns</strong>-2 <strong>and</strong> specify –with-dmalloc when configuring<strong>ns</strong>. <strong>The</strong>n build all components of <strong>ns</strong> for which you want memory inform<strong>at</strong>ion with debugging symbols (this shouldinclude <strong>at</strong> least <strong>ns</strong>-2, possibly tclcl <strong>and</strong> otcl <strong>and</strong> maybe also tcl).24.4.1 Using dmallocIn order to use dmalloc do the following:• Define an aliasfor csh: alias dmalloc ’eval ‘\dmalloc -C \!*‘’,for bash: function dmalloc { eval ‘comm<strong>and</strong> dmalloc -b $*‘ }%$• Next turn debugging on by typing dmalloc -l logfile low• Run your program (which was configured <strong>and</strong> built with dmalloc as described above).• Interpret logfile by running dmalloc_summarize <strong>ns</strong>


24.4.2 Memory Co<strong>ns</strong>erv<strong>at</strong>ion TipsSome tips to saving memory (some of these use examples from the cmcast-100.tcl script): If you have many links or nodes:Avoid trace-all: $<strong>ns</strong> trace-all $f causes trace objects to be pushed on all links. If you only want to trace onelink, there’s no need for this overhead. Saving is about 14 KB/link.Use arrays for sequences of variables : Each variable, say n$i in set n$i [$<strong>ns</strong> node], has a certain overhead. If asequence of nodes are cre<strong>at</strong>ed as an array, i.e. n($i), then only one variable is cre<strong>at</strong>ed, co<strong>ns</strong>uming much less memory.Saving is about 40+ Byte/variable.Avoid unnecessary variables : If an object will not be referred to l<strong>at</strong>er on, avoid naming the object. E.g. set cmcast(1)[new CtrMcast $<strong>ns</strong> $n(1) $ctrmcastcomp [list 1 1]] would be better if replaced by new CtrMcast$<strong>ns</strong> $n(1) $ctrmcastcomp [list 1 1]. Saving is about 80 Byte/variable.Run on top of FreeBSD : malloc() overhead on FreeBSD is less than on some other systems. We will eventually port th<strong>at</strong>alloc<strong>at</strong>or to other pl<strong>at</strong>ofrms.Dynamic binding : Using bind() in C++ co<strong>ns</strong>umes memory for each object you cre<strong>at</strong>e. This approach can be very expe<strong>ns</strong>iveif you cre<strong>at</strong>e many identical objects. Changing bind() to delay_bind() changes this memory requirement toper-class. See <strong>ns</strong>/object.cc for an example of how to do binding, either way.Disabling packet headers : For packet-inte<strong>ns</strong>ive simul<strong>at</strong>io<strong>ns</strong>, disabling all packet headers th<strong>at</strong> you will not use in yoursimul<strong>at</strong>ion may significantly reduce memory usage. See Section 12.1 for detail.24.4.3 Some st<strong>at</strong>istics collected by dmallocA memory co<strong>ns</strong>umption problem occured in recent simul<strong>at</strong>io<strong>ns</strong> (cmcast-[150,200,250].tcl), so we decided to take a closerlook <strong>at</strong> scaling issue. See page http://www-mash.cs.berkeley.edu/<strong>ns</strong>/<strong>ns</strong>-scaling.html which demostr<strong>at</strong>es the efforts in findingthe bottlneck.<strong>The</strong> following table summarises the results of investig<strong>at</strong>ing the bottleneck:KBytes cmcast-50.tcl(217 Links) cmcast-100.tcl(950 Links)trace-all 8,084 28,541turn off trace-all 5,095 15,465use array 5,091 15,459remove unnecessay variables 5,087 15,451on SunOS 5,105 15,48424.5 Memory LeaksThis section deals with memory leak problems in <strong>ns</strong>, both in Tcl as well as C/C++.218


24.5.1 OTclOTcl, especially TclCL, provides a way to alloc<strong>at</strong>e new objects. However, it does not accordingly provide a garbage collectionmechanism for these alloc<strong>at</strong>ed objects. This can easily lead to unintentional memory leaks. Important: tools such as dmalloc<strong>and</strong> purify are unable to detect this kind of memory leaks. For example, co<strong>ns</strong>ider this simple piece of OTcl script:set <strong>ns</strong> [new Simul<strong>at</strong>or]for set i 0 $i < 500 incr iset a [new R<strong>and</strong>omVariable/Co<strong>ns</strong>tant]One would expect th<strong>at</strong> the memory usage should stay the same after the first R<strong>and</strong>omVariable is alloc<strong>at</strong>ed. However, becauseOTcl does not have garbage collection, when the second R<strong>and</strong>omVariable is alloc<strong>at</strong>ed, the previous one is not freed <strong>and</strong>hence results in memory leak. Unfortun<strong>at</strong>ely, there is no easy fix for this, because garbage collection of alloc<strong>at</strong>ed objects isessentially incomp<strong>at</strong>ible with the spirit of Tcl. <strong>The</strong> only way to fix this now is to always explicitly free every alloc<strong>at</strong>ed OTclobject in your script, in the same way th<strong>at</strong> you take care of malloc-ed object in C/C++.24.5.2 C/C++Another source of memory leak is in C/C++. This is much easier to track given tools th<strong>at</strong> are specifically designed for thistask, e.g., dmalloc <strong>and</strong> purify. <strong>ns</strong>has a special target <strong>ns</strong>-pure to build purified <strong>ns</strong> executable. First make sure th<strong>at</strong> the macroPURIFY in the <strong>ns</strong> Makefile contai<strong>ns</strong> the right -collector for your linker (check purify man page if you don’t know wh<strong>at</strong> thisis). <strong>The</strong>n simply type make <strong>ns</strong>-pure. See earlier sectio<strong>ns</strong> in this chapter on how to use <strong>ns</strong> with libdmalloc.219


Chapter 25M<strong>at</strong>hem<strong>at</strong>ical Support<strong>The</strong> simul<strong>at</strong>or includes a small collection of m<strong>at</strong>hem<strong>at</strong>ical functio<strong>ns</strong> used to implement r<strong>and</strong>om vari<strong>at</strong>e gener<strong>at</strong>ion <strong>and</strong> integr<strong>at</strong>ion.This area of the simul<strong>at</strong>or is currently undergoing some changes.<strong>The</strong> procedures <strong>and</strong> functio<strong>ns</strong> described in this chapter can be found in ~<strong>ns</strong>/tools/rng.{cc, h}, ~<strong>ns</strong>/tools/r<strong>and</strong>om.{cc, h},~<strong>ns</strong>/tools/ranvar.{cc, h}, ~<strong>ns</strong>/tools/pareto.{cc, h}, ~<strong>ns</strong>/tools/expoo.{cc, h}, ~<strong>ns</strong>/tools/integr<strong>at</strong>or.{cc, h}, <strong>and</strong> ~<strong>ns</strong>/tcl/lib/<strong>ns</strong>r<strong>and</strong>om.tcl.25.1 R<strong>and</strong>om Number Gener<strong>at</strong>ion<strong>The</strong> RNG class contai<strong>ns</strong> an implement<strong>at</strong>ion of the combined multiple recursive gener<strong>at</strong>or MRG32k3a proposed by L’Ecuyer[16]. <strong>The</strong> C++ code was adapted from [18]. This replaces the previous implement<strong>at</strong>ion of RNG, which used the minimalst<strong>and</strong>ard multiplic<strong>at</strong>ive linear congruential gener<strong>at</strong>or of Park <strong>and</strong> Miller [27]. <strong>The</strong> newer (MRG32k3a) RNG is used in <strong>ns</strong>versio<strong>ns</strong> 2.1b9 <strong>and</strong> l<strong>at</strong>er.<strong>The</strong> MRG32k3a gener<strong>at</strong>or provides 1.8x10 19 independent streams of r<strong>and</strong>om numbers, each of which co<strong>ns</strong>ists of 2.3x10 15substreams. Each substream has a period (i.e., the number of r<strong>and</strong>om numbers before overlap) of 7.6x10 22 . <strong>The</strong> period of theentire gener<strong>at</strong>or is 3.1x10 57 . Figure 25.1 provides a graphical idea of how the streams <strong>and</strong> substreams fit together.A default RNG (defaultRNG), cre<strong>at</strong>ed <strong>at</strong> simul<strong>at</strong>or initializ<strong>at</strong>ion time, is provided. If multiple r<strong>and</strong>om variables are used ina simul<strong>at</strong>ion, each r<strong>and</strong>om variable should use a separ<strong>at</strong>e RNG object. When a new RNG object is cre<strong>at</strong>ed, it is autom<strong>at</strong>icallyseeded to the beginning of the next independent stream of r<strong>and</strong>om numbers. Used in this manner, the implement<strong>at</strong>ion allowsfor a maximum of 1.8x10 19 r<strong>and</strong>om variables.Often, multiple independent replic<strong>at</strong>io<strong>ns</strong> of a simul<strong>at</strong>ion are needed (i.e., to perform st<strong>at</strong>istical analysis given multiple ru<strong>ns</strong>with fixed parameters). For each replic<strong>at</strong>ion, a different substream should be used to e<strong>ns</strong>ure th<strong>at</strong> the r<strong>and</strong>om number streamsare independent. (This process is given as an OTcl example l<strong>at</strong>er.) This implement<strong>at</strong>ion allows for a maximum of 2.3x10 15independent replic<strong>at</strong>io<strong>ns</strong>. Each r<strong>and</strong>om variable in a single replic<strong>at</strong>ion can produce up to 7.6x10 22 r<strong>and</strong>om numbers beforeoverlapping.Note: Only the most common functio<strong>ns</strong> are described here. For more inform<strong>at</strong>ion, see [18] <strong>and</strong> the source code found intools/rng.h <strong>and</strong> tools/rng.cc. For a comparison of this RNG to the more common LCG16807 RNG (<strong>and</strong> whyLCG16807 is not a good RNG), see [17].220


Figure 25.1: Overall arrangement of streams <strong>and</strong> substreams. [18]25.1.1 Seeding <strong>The</strong> RNGDue to the n<strong>at</strong>ure of the RNG <strong>and</strong> its implement<strong>at</strong>ion, it is not necessary to set a seed (the default is 12345). If you wish tochange the seed, functio<strong>ns</strong> are available. You should only set the seed of the default RNG. Any other RNGs you cre<strong>at</strong>e areautom<strong>at</strong>ically seeded such th<strong>at</strong> they produce independent streams. <strong>The</strong> range of valid seeds is 1 to MAXINT.To get non-deterministic behavior, set the seed of the default RNG to 0. This will set the seed based on the current time ofday <strong>and</strong> a counter. This method should not be used to set seeds for independent replic<strong>at</strong>io<strong>ns</strong>. <strong>The</strong>re is no guarantee th<strong>at</strong>the streams produced by two r<strong>and</strong>om seeds will not overlap. <strong>The</strong> only way to guarantee th<strong>at</strong> two streams do not overlap is touse the substream capability provided by the RNG implement<strong>at</strong>ion.Example# Usage: <strong>ns</strong> rng-test.tcl [replic<strong>at</strong>ion number]if {$argc > 1} {puts "Usage: <strong>ns</strong> rng-test.tcl \[replic<strong>at</strong>ion number\]"exit}set run 1if {$argc == 1} {221


set run [lindex $argv 0]}if {$run < 1} {set run 1}# seed the default RNGglobal defaultRNG$defaultRNG seed 9999# cre<strong>at</strong>e the RNGs <strong>and</strong> set them to the correct substreamset arrivalRNG [new RNG]set sizeRNG [new RNG]for {set j 1} {$j < $run} {incr j} {$arrivalRNG next-substream$sizeRNG next-substream}# arrival_ is a exponential r<strong>and</strong>om variable describing the time# between co<strong>ns</strong>ecutive packet arrivalsset arrival_ [new R<strong>and</strong>omVariable/Exponential]$arrival_ set avg_ 5$arrival_ use-rng $arrivalRNG# size_ is a uniform r<strong>and</strong>om variable describing packet sizesset size_ [new R<strong>and</strong>omVariable/Uniform]$size_ set min_ 100$size_ set max_ 5000$size_ use-rng $sizeRNG# print the first 5 arrival times <strong>and</strong> sizesfor {set j 0} {$j < 5} {incr j} {puts [form<strong>at</strong> "%-8.3f %-4d" [$arrival_ value] \[expr round([$size_ value])]]}Output% <strong>ns</strong> rng-test.tcl 16.358 47835.828 17321.469 21880.732 30764.002 626% <strong>ns</strong> rng-test.tcl 50.691 11870.204 49248.849 8572.111 45053.200 1143222


25.1.2 OTcl SupportComm<strong>and</strong>s<strong>The</strong> following comm<strong>and</strong>s on the RNG class can be accessed from OTcl <strong>and</strong> are found in tools/rng.cc:seed n – seed the RNG to n, if n == 0, the seed is set according to the current time <strong>and</strong> a counternext-r<strong>and</strong>om – return the next r<strong>and</strong>om numberseed – return the current value of the seednext-substream – advance to the next substreamreset-start-substream – reset the stream to the beginning of the current substreamnormal avg std – return a number sampled from a normal distribution with the given average <strong>and</strong> st<strong>and</strong>ard devi<strong>at</strong>ionlognormal avg std – return a number sampled from a lognormal distribution with the given average <strong>and</strong> st<strong>and</strong>ard devi<strong>at</strong>ion<strong>The</strong> following comm<strong>and</strong>s on the RNG class can be accessed from OTcl <strong>and</strong> are found in tcl/lib/<strong>ns</strong>-r<strong>and</strong>om.tcl:exponential mu – return a number sampled from an exponential distribution with mean muuniform min max – return an integer sampled from a uniform distribution on [min, max]integer k – return an integer sampled from a uniform distribution on [0, k-1]Example# Usage: <strong>ns</strong> rng-test2.tcl [replic<strong>at</strong>ion number]if {$argc > 1} {puts "Usage: <strong>ns</strong> rng-test2.tcl \[replic<strong>at</strong>ion number\]"exit}set run 1if {$argc == 1} {set run [lindex $argv 0]}if {$run < 1} {set run 1}# the default RNG is seeded with 12345# cre<strong>at</strong>e the RNGs <strong>and</strong> set them to the correct substreamset arrivalRNG [new RNG]set sizeRNG [new RNG]for {set j 1} {$j < $run} {incr j} {$arrivalRNG next-substream223


}$sizeRNG next-substream# print the first 5 arrival times <strong>and</strong> sizesfor {set j 0} {$j < 5} {incr j} {puts [form<strong>at</strong> "%-8.3f %-4d" [$arrivalRNG lognormal 5 0.1] \[expr round([$sizeRNG normal 5000 100])]]}Output% <strong>ns</strong> rng-test2.tcl 1142.776 5038174.365 5024147.160 4984169.693 4981187.972 4982% <strong>ns</strong> rng-test2.tcl 5160.993 4907119.895 4956149.468 5131137.678 4985158.936 487125.1.3 C++ SupportMember Functio<strong>ns</strong><strong>The</strong> r<strong>and</strong>om number gener<strong>at</strong>or is implemented by the RNG class <strong>and</strong> is defined in tools/rng.h.Note: <strong>The</strong> R<strong>and</strong>om class in tools/r<strong>and</strong>om.h is an older interface to the st<strong>and</strong>ard r<strong>and</strong>om number stream.Member functio<strong>ns</strong> provide the following oper<strong>at</strong>io<strong>ns</strong>:void set_seed (long seed) – set the seed of the RNG, if seed == 0, the seed is set according to the current time<strong>and</strong> a counterlong seed (void) – return the current seedlong next (void) – return the next r<strong>and</strong>om number as an integer on [0, MAXINT]double next_double (void) – return the next r<strong>and</strong>om number on [0, 1]void reset_start_substream (void) – reset the stream to the beginning of the current substreamvoid reset_next_substream (void) – advance to the next substreamint uniform (int k) – return an integer sampled from a uniform distribution on [0, k-1]double uniform (double r) – return a number sampled from a uniform distribution on [0, r]224


double uniform (double a, double b) – return a number sampled from a uniform distribution on [a, b]double exponential (void) – return a number sampled from an exponential distribution with mean 1.0double exponential (double k) – return a number sampled from an exponential distribution with mean kdouble normal (double avg, double std) – return a number sampled from a normal distribution with thegiven average <strong>and</strong> st<strong>and</strong>ard devi<strong>at</strong>iondouble lognormal (double avg, double std) – return a number sampled from a lognormal distribution withthe given average <strong>and</strong> st<strong>and</strong>ard devi<strong>at</strong>ionExample/* cre<strong>at</strong>e new RNGs */RNG arrival (23456);RNG size;/* set the RNGs to the appropri<strong>at</strong>e substream */for (int i = 1; i < 3; i++) {arrival.reset_next_substream();size.reset_next_substream();}/* print the first 5 arrival times <strong>and</strong> sizes */for (int j = 0; j < 5; j++) {printf ("%-8.3f %-4d\n", arrival.lognormal(5, 0.1),int(size.normal(500, 10)));}Output161.826 506160.591 503157.145 509137.715 507118.573 49625.2 R<strong>and</strong>om Variables<strong>The</strong> class R<strong>and</strong>omVariable provides a thin layer of functionality on top of the base r<strong>and</strong>om number gener<strong>at</strong>or <strong>and</strong> thedefault r<strong>and</strong>om number stream. It is defined in ~<strong>ns</strong>/ranvar.h:class R<strong>and</strong>omVariable : public TclObject {public:virtual double value() = 0;int comm<strong>and</strong>(int argc, co<strong>ns</strong>t char*co<strong>ns</strong>t* argv);R<strong>and</strong>omVariable();225


protected:RNG* rng_;};Classes derived from this abstract class implement specific distributio<strong>ns</strong>. Each distribution is parameterized with the valuesof appropri<strong>at</strong>e parameters. <strong>The</strong> value method is used to return a value from the distribution.<strong>The</strong> currently defined distributio<strong>ns</strong>, <strong>and</strong> their associ<strong>at</strong>ed parameters are:class UniformR<strong>and</strong>omVariableclass ExponentialR<strong>and</strong>omVariableclass ParetoR<strong>and</strong>omVariableclass ParetoIIR<strong>and</strong>omVariableclass Co<strong>ns</strong>tantR<strong>and</strong>omVariableclass HyperExponentialR<strong>and</strong>omVariableclass NormalR<strong>and</strong>omVariableclass LogNormalR<strong>and</strong>omVariablemin_, max_avg_avg_, shape_avg_, shape_val_avg_, cov_avg_, std_avg_, std_<strong>The</strong> R<strong>and</strong>omVariable class is available in OTcl. For i<strong>ns</strong>tance, to cre<strong>at</strong>e a r<strong>and</strong>om variable th<strong>at</strong> gener<strong>at</strong>es number uniformly on[10, 20]:set u [new R<strong>and</strong>omVariable/Uniform]$u set min_ 10$u set max_ 20$u valueBy default, R<strong>and</strong>omVariable objects use the default r<strong>and</strong>om number gener<strong>at</strong>or described in the previous section. <strong>The</strong> use-rngmethod can be used to associ<strong>at</strong>e a R<strong>and</strong>omVariable with a non-default RNG:set rng [new RNG]$rng seed 0set e [new R<strong>and</strong>omVariable/Exponential]$e use-rng $rng25.3 Integrals<strong>The</strong> class Integr<strong>at</strong>or supports the approxim<strong>at</strong>ion of (continuous) integr<strong>at</strong>ion by (discrete) sums; it is defined in~<strong>ns</strong>/integr<strong>at</strong>or.h asFrom integr<strong>at</strong>or.h:class Integr<strong>at</strong>or : public TclObject {public:Integr<strong>at</strong>or();void set(double x, double y);void newPoint(double x, double y);int comm<strong>and</strong>(int argc, co<strong>ns</strong>t char*co<strong>ns</strong>t* argv);226


protected:double lastx_;double lasty_;double sum_;};From integr<strong>at</strong>or.cc:Integr<strong>at</strong>or::Integr<strong>at</strong>or() : lastx_(0.), lasty_(0.), sum_(0.){bind("lastx_", &lastx_);bind("lasty_", &lasty_);bind("sum_", &sum_);}void Integr<strong>at</strong>or::set(double x, double y){lastx_ = x;lasty_ = y;sum_ = 0.;}void Integr<strong>at</strong>or::newPoint(double x, double y){sum_ += (x - lastx_) * lasty_;lastx_ = x;lasty_ = y;}int Integr<strong>at</strong>or::comm<strong>and</strong>(int argc, co<strong>ns</strong>t char*co<strong>ns</strong>t* argv){if (argc == 4) {if (strcmp(argv[1], "newpoint") == 0) {double x = <strong>at</strong>of(argv[2]);double y = <strong>at</strong>of(argv[3]);newPoint(x, y);return (TCL_OK);}}return (TclObject::comm<strong>and</strong>(argc, argv));}This class provides a base class used by other classes such as QueueMonitor th<strong>at</strong> keep running sums. Each new elementof the running sum is added by the newPoint(x, y) function. After the kth execution of newPoint, the running sum isequal to ∑ ki=1 y i−1(x i − x i−1 ) where x 0 = y 0 = 0 unless lastx_, lasty_, or sum_ are reset via OTcl. Note th<strong>at</strong> a newpoint in the sum can be added either by the C++ member newPoint or the OTcl member newpoint. <strong>The</strong> use of integralsto compute certain types of averages (e.g. mean queue lengths) is given in (pp. 429–430, [15]).25.4 <strong>ns</strong>-r<strong>and</strong>om<strong>ns</strong>-r<strong>and</strong>omis an obsolete way to gener<strong>at</strong>e r<strong>and</strong>om numbers. This inform<strong>at</strong>ion is provided only for backward comp<strong>at</strong>ibility.227


<strong>ns</strong>-r<strong>and</strong>om is implemented in ~<strong>ns</strong>/misc.{cc,h}. When called with no argument, it gener<strong>at</strong>es a r<strong>and</strong>om number with uniformdistribution between 0 <strong>and</strong> MAXINT. When an integer argument is provided, it seeds the r<strong>and</strong>om gener<strong>at</strong>er with the givennumber. A special case is when <strong>ns</strong>-r<strong>and</strong>om 0 is called, it r<strong>and</strong>omly seeds the gener<strong>at</strong>or based on current time. This fe<strong>at</strong>ureis useful to produce non-deterministic results across ru<strong>ns</strong>.25.5 Some m<strong>at</strong>hem<strong>at</strong>ical-support rel<strong>at</strong>ed objectsINTEGRATOR OBJECTS Integr<strong>at</strong>or Objects support the approxim<strong>at</strong>e comput<strong>at</strong>ion of continuous integrals using discrete sums.<strong>The</strong> running sum(integral) is computed as: sum_ += [lasty_ * (x lastx_)] where (x, y) is the last element entered<strong>and</strong> (lastx_, lasty_) was the element previous to th<strong>at</strong> added to the sum. lastx_ <strong>and</strong> lasty_ are upd<strong>at</strong>ed as new elements areadded. <strong>The</strong> first sample point defaults to (0,0) th<strong>at</strong> can be changed by changing the values of (lastx_,lasty_). $integr<strong>at</strong>ornewpoint Add the point (x,y) to the sum. Note th<strong>at</strong> it does not make se<strong>ns</strong>e for x to be less than lastx_.<strong>The</strong>re are no configur<strong>at</strong>ion parameters specific to this object.St<strong>at</strong>e Variables are:lastx_ x-coordin<strong>at</strong>e of the last sample point.lasty_ y-coordin<strong>at</strong>e of the last sample point.sum_ Running sum (i.e. the integral) of the sample points.SAMPLES OBJECT Samples Objects support the comput<strong>at</strong>ion of mean <strong>and</strong> variance st<strong>at</strong>istics for a given sample.$samples meanRetur<strong>ns</strong> mean of the sample.$samples varianceRetur<strong>ns</strong> variance of the sample.$samples cntRetur<strong>ns</strong> a count of the sample points co<strong>ns</strong>idered.$samples resetReset the Samples object to monitor a fresh set of samples.<strong>The</strong>re are no configur<strong>at</strong>ion parameters or st<strong>at</strong>e variables specific to this object.25.6 Comm<strong>and</strong>s <strong>at</strong> a glanceFollowing is a list of m<strong>at</strong>hem<strong>at</strong>ical support rel<strong>at</strong>ed comm<strong>and</strong>s commonly used in simul<strong>at</strong>ion scripts:set rng [new RNG]This cre<strong>at</strong>es a new r<strong>and</strong>om number gener<strong>at</strong>or.228


$rng seed This comm<strong>and</strong> seeds the RNG. If 0 is specified, the RNG is seeded heuristically. Otherwise the RNG is seeded with thevalue .$rng next-r<strong>and</strong>omThis retur<strong>ns</strong> the next r<strong>and</strong>om number from RNG.$rng uniform This retur<strong>ns</strong> a number uniformly distributed on <strong>and</strong> .$rng integer This retur<strong>ns</strong> an integer uniformly distributed on 0 <strong>and</strong> k-1.$rng exponentialThis retur<strong>ns</strong> a number th<strong>at</strong> has exponential distribution with average 1.set rv [new R<strong>and</strong>omvariable/]This cre<strong>at</strong>es an i<strong>ns</strong>tance of a r<strong>and</strong>om variable object th<strong>at</strong> gener<strong>at</strong>es r<strong>and</strong>om variables with specific distribution. <strong>The</strong> differenttypes of r<strong>and</strong>om variables derived from the base class are:R<strong>and</strong>omVariable/Uniform, R<strong>and</strong>omVariable/Exponential, R<strong>and</strong>omVariable/Pareto, R<strong>and</strong>omVariable/Co<strong>ns</strong>tant,R<strong>and</strong>omVariable/HyperExponential. Each of these distribution types are parameterized with values of appropri<strong>at</strong>eparameters. For details see section 25.2 of this chapter.$rv use-rng This method is used to associ<strong>at</strong>ed a r<strong>and</strong>om variable object with a non-default RNG. Otherwise by default, the r<strong>and</strong>omvariable object is associ<strong>at</strong>ed with the default r<strong>and</strong>om number gener<strong>at</strong>or.229


Chapter 26Trace <strong>and</strong> Monitoring Support<strong>The</strong> procedures <strong>and</strong> functio<strong>ns</strong> described in this chapter can be found in ~<strong>ns</strong>/trace.{cc, h}, ~<strong>ns</strong>/tcl/lib/<strong>ns</strong>-trace.tcl, ~<strong>ns</strong>/queuemonitor.{cc,h}, ~<strong>ns</strong>/tcl/lib/<strong>ns</strong>-link.tcl, ~<strong>ns</strong>/packet.h, ~<strong>ns</strong>/flowmon.cc, <strong>and</strong> ~<strong>ns</strong>/classifier-hash.cc.<strong>The</strong>re are a number of ways of collecting output or trace d<strong>at</strong>a on a simul<strong>at</strong>ion. Generally, trace d<strong>at</strong>a is either displayed directlyduring execution of the simul<strong>at</strong>ion, or (more commonly) stored in a file to be post-processed <strong>and</strong> analyzed. <strong>The</strong>re are twoprimary but distinct types of monitoring capabilities currently supported by the simul<strong>at</strong>or. <strong>The</strong> first, called traces, record eachindividual packet as it arrives, departs, or is dropped <strong>at</strong> a link or queue. Trace objects are configured into a simul<strong>at</strong>ion as nodesin the network topology, usually with a Tcl “Channel” object hooked to them, representing the destin<strong>at</strong>ion of collected d<strong>at</strong>a(typically a trace file in the current directory). <strong>The</strong> other types of objects, called monitors, record counts of various interestingquantities such as packet <strong>and</strong> byte arrivals, departures, etc. Monitors can monitor counts associ<strong>at</strong>ed with all packets, or on aper-flow basis using a flow monitor below (Section 26.7).To support traces, there is a special common header included in each packet (this form<strong>at</strong> is defined in ~<strong>ns</strong>/packet.h ashdr_cmn). It presently includes a unique identifier on each packet, a packet type field (set by agents when they gener<strong>at</strong>epackets), a packet size field (in bytes, used to determine the tra<strong>ns</strong>mission time for packets), <strong>and</strong> an interface label (usedfor computing multicast distribution trees).Monitors are supported by a separ<strong>at</strong>e set of objects th<strong>at</strong> are cre<strong>at</strong>ed <strong>and</strong> i<strong>ns</strong>erted into the network topology around queues.<strong>The</strong>y provide a place where arrival st<strong>at</strong>istics <strong>and</strong> times are g<strong>at</strong>hered <strong>and</strong> make use of the class Integr<strong>at</strong>or (Section 25.3)to compute st<strong>at</strong>istics over time intervals.26.1 Trace Support<strong>The</strong> trace support in OTcl co<strong>ns</strong>ists of a number of specialized classes visible in OTcl but implemented in C++, combined witha set of Tcl helper procedures <strong>and</strong> classes defined in the <strong>ns</strong> library.All following OTcl classes are supported by underlying C++ classes defined in ~<strong>ns</strong>/trace.cc. Objects of the following typesare i<strong>ns</strong>erted directly in-line in the network topology:230


Trace/HopTrace/EnqueTrace/DequeTrace/DropTrace/RecvSnoopQueue/InSnoopQueue/OutSnoopQueue/DropSnoopQueue/EDroptrace a “hop” (XXX wh<strong>at</strong> does this mean exactly; it is not really used XXX)a packet arrival (usually <strong>at</strong> a queue)a packet departure (usually <strong>at</strong> a queue)packet drop (packet delivered to drop-target)packet receive event <strong>at</strong> the destin<strong>at</strong>ion node of a linkon input, collect a time/size sample (pass packet on)on output, collect a time/size sample (pass packet on)on drop, collect a time/size sample (pass packet on)on an "early" drop, collect a time/size sample (pass packet on)Objects of the following types are added in the simul<strong>at</strong>ion <strong>and</strong> a referenced by the objects listed above. <strong>The</strong>y are used toaggreg<strong>at</strong>e st<strong>at</strong>istics collected by the SnoopQueue objects:QueueMonitorQueueMonitor/EDQueueMonitor/ED/FlowmonQueueMonitor/ED/FlowQueueMonitor/Comp<strong>at</strong>receive <strong>and</strong> aggreg<strong>at</strong>e collected samples from snoopersqueue-monitor capable of distinguishing between “early” <strong>and</strong> st<strong>and</strong>ard packet dropsper-flow st<strong>at</strong>istics monitor (manager)per-flow st<strong>at</strong>istics containera replacement for a st<strong>and</strong>ard QueueMonitor when <strong>ns</strong> v1 comp<strong>at</strong>ibility is in use26.1.1 OTcl Helper Functio<strong>ns</strong><strong>The</strong> following helper functio<strong>ns</strong> may be used within simul<strong>at</strong>ion scripts to help in <strong>at</strong>taching trace elements (see ~<strong>ns</strong>/tcl/lib/<strong>ns</strong>lib.tcl);they are i<strong>ns</strong>tance procedures of the class Simul<strong>at</strong>or:flush-trace {}cre<strong>at</strong>e-trace { type file src dst }trace-queue { n1 n2 file }trace-callback{ <strong>ns</strong> comm<strong>and</strong> }monitor-queue { n1 n2 }drop-trace { n1 n2 trace }flush buffers for all trace objects in simul<strong>at</strong>ioncre<strong>at</strong>e a trace object of type type between the given src <strong>and</strong> destnodes. If file is non-null, it is interpreted as a Tcl channel <strong>and</strong> is<strong>at</strong>tached to the newly-cre<strong>at</strong>ed trace object. <strong>The</strong> procedure retur<strong>ns</strong>the h<strong>and</strong>le to the newly cre<strong>at</strong>ed trace object.arrange for tracing on the link between nodes n1 <strong>and</strong> n2. This functioncalls cre<strong>at</strong>e-trace, so the same rules apply with respect to the fileargument.arranges to call comm<strong>and</strong> when a line is to be traced. <strong>The</strong> proceduretre<strong>at</strong>s comm<strong>and</strong> as a string <strong>and</strong> evalu<strong>at</strong>es it for every line traced. See~<strong>ns</strong>/tcl/ex/callback_demo.tcl for additional details on usage.this function calls the init-monitor function on the link betweennodes n1 <strong>and</strong> n2.the given trace object is made the drop-target of the queue associ<strong>at</strong>edwith the link between nodes n1 <strong>and</strong> n2.<strong>The</strong> cre<strong>at</strong>e-trace{} procedure is used to cre<strong>at</strong>e a new Trace object of the appropri<strong>at</strong>e kind <strong>and</strong> <strong>at</strong>tach an Tcl I/O channelto it (typically a file h<strong>and</strong>le). <strong>The</strong> src_ <strong>and</strong> dst_ fields are are used by the underlying C++ object for producing the traceoutput file so th<strong>at</strong> trace output can include the node addresses defining the endpoints of the link which is being traced. Noteth<strong>at</strong> they are not used for m<strong>at</strong>ching. Specifically, these values in no way rel<strong>at</strong>e to the packet header src <strong>and</strong> dst fields, whichare also displayed when tracing. See the description of the Trace class below (Section 26.3).<strong>The</strong> trace-queue function enables Enque, Deque, <strong>and</strong> Drop tracing on the link between nodes n1 <strong>and</strong> n2. <strong>The</strong> Linktrace procedure is described below (Section 26.2).231


<strong>The</strong> monitor-queue function is co<strong>ns</strong>tructed similarly to trace-queue. By calling the link’s init-monitor procedure,it arranges for the cre<strong>at</strong>ion of objects (SnoopQueue <strong>and</strong> QueueMonitor objects) which can, in turn, be used toascertain time-aggreg<strong>at</strong>ed queue st<strong>at</strong>istics.<strong>The</strong> drop-trace function provides a way to specify a Queue’s drop target without having a direct h<strong>and</strong>le of the queue.26.2 Library support <strong>and</strong> examples<strong>The</strong> Simul<strong>at</strong>or procedures described above require the trace <strong>and</strong> init-monitor methods associ<strong>at</strong>ed with the OTclLink class. Several subclasses of link are defined, the most common of which is called SimpleLink. Thus, the trace<strong>and</strong> init-monitor methods are actually part of the SimpleLink class r<strong>at</strong>her than the Link base class. <strong>The</strong> tracefunction is defined as follows (in <strong>ns</strong>-link.tcl):## Build trace objects for this link <strong>and</strong># upd<strong>at</strong>e the object linkage#SimpleLink i<strong>ns</strong>tproc trace { <strong>ns</strong> f } {$self i<strong>ns</strong>tvar enqT_ deqT_ drpT_ queue_ link_ head_ fromNode_ toNode_$self i<strong>ns</strong>tvar drophead_set enqT_ [$<strong>ns</strong> cre<strong>at</strong>e-trace Enque $f $fromNode_ $toNode_]set deqT_ [$<strong>ns</strong> cre<strong>at</strong>e-trace Deque $f $fromNode_ $toNode_]set drpT_ [$<strong>ns</strong> cre<strong>at</strong>e-trace Drop $f $fromNode_ $toNode_]$drpT_ target [$drophead_ target]$drophead_ target $drpT_$queue_ drop-target $drpT_$deqT_ target [$queue_ target]$queue_ target $deqT_}if { [$head_ info class] == "networkinterface" } {$enqT_ target [$head_ target]$head_ target $enqT_# puts "head is i/f"} else {$enqT_ target $head_set head_ $enqT_# puts "head is not i/f"}This function establishes Enque, Deque, <strong>and</strong> Drop traces in the simul<strong>at</strong>or $<strong>ns</strong> <strong>and</strong> directs their output to I/O h<strong>and</strong>le $f.<strong>The</strong> function assumes a queue has been associ<strong>at</strong>ed with the link. It oper<strong>at</strong>es by first cre<strong>at</strong>ing three new trace objects <strong>and</strong>i<strong>ns</strong>erting the Enque object before the queue, the Deque object after the queue, <strong>and</strong> the Drop object between the queue <strong>and</strong>its previous drop target. Note th<strong>at</strong> all trace output is directed to the same I/O h<strong>and</strong>le.This function performs one other additional tasks. It checks to see if a link contai<strong>ns</strong> a network interface, <strong>and</strong> if so, leaves it asthe first object in the chain of objects in the link, but otherwise i<strong>ns</strong>erts the Enque object as the first one.232


<strong>The</strong> following functio<strong>ns</strong>, init-monitor <strong>and</strong> <strong>at</strong>tach-monitor, are used to cre<strong>at</strong>e a set of objects used to monitor queuesizes of a queue associ<strong>at</strong>ed with a link. <strong>The</strong>y are defined as follows:SimpleLink i<strong>ns</strong>tproc <strong>at</strong>tach-monitors { i<strong>ns</strong>noop outsnoop dropsnoop qmon } {$self i<strong>ns</strong>tvar queue_ head_ snoopIn_ snoopOut_ snoopDrop_$self i<strong>ns</strong>tvar drophead_ qMonitor_set snoopIn_ $i<strong>ns</strong>noopset snoopOut_ $outsnoopset snoopDrop_ $dropsnoop$snoopIn_ target $head_set head_ $snoopIn_$snoopOut_ target [$queue_ target]$queue_ target $snoopOut_$snoopDrop_ target [$drophead_ target]$drophead_ target $snoopDrop_}$snoopIn_ set-monitor $qmon$snoopOut_ set-monitor $qmon$snoopDrop_ set-monitor $qmo<strong>ns</strong>et qMonitor_ $qmon## I<strong>ns</strong>ert objects th<strong>at</strong> allow us to monitor the queue size# of this link. Return the name of the object th<strong>at</strong># can be queried to determine the average queue size.#SimpleLink i<strong>ns</strong>tproc init-monitor { <strong>ns</strong> qtrace sampleInterval} {$self i<strong>ns</strong>tvar qMonitor_ <strong>ns</strong>_ qtrace_ sampleInterval_set <strong>ns</strong>_ $<strong>ns</strong>set qtrace_ $qtraceset sampleInterval_ $sampleIntervalset qMonitor_ [new QueueMonitor]$self <strong>at</strong>tach-monitors [new SnoopQueue/In] \[new SnoopQueue/Out] [new SnoopQueue/Drop] $qMonitor_}set bytesInt_ [new Integr<strong>at</strong>or]$qMonitor_ set-bytes-integr<strong>at</strong>or $bytesInt_set pktsInt_ [new Integr<strong>at</strong>or]$qMonitor_ set-pkts-integr<strong>at</strong>or $pktsInt_return $qMonitor_<strong>The</strong>se functio<strong>ns</strong> establish queue monitoring on the SimpleLink object in the simul<strong>at</strong>or <strong>ns</strong>. Queue monitoring is implementedby co<strong>ns</strong>tructing three SnoopQueue objects <strong>and</strong> one QueueMonitor object. <strong>The</strong> SnoopQueue objects arelinked in around a Queue in a way similar to Trace objects. <strong>The</strong> SnoopQueue/In(Out) object monitors packet arrivals(departures)<strong>and</strong> reports them to an associ<strong>at</strong>ed QueueMonitor agent. In addition, a SnoopQueue/Out object is233


also used to accumul<strong>at</strong>e packet drop st<strong>at</strong>istics to an associ<strong>at</strong>ed QueueMonitor object. For init-monitor the sameQueueMonitor object is used in all cases. <strong>The</strong> C++ definitio<strong>ns</strong> of the SnoopQueue <strong>and</strong> QueueMonitor classes aredescribed below.26.3 <strong>The</strong> C++ Trace ClassUnderlying C++ objects are cre<strong>at</strong>ed in support of the interface specified in Section 26.3 <strong>and</strong> are linked into the network topologyas network elements. <strong>The</strong> single C++ Trace class is used to implement the OTcl classes Trace/Hop, Trace/Enque,Trace/Deque, <strong>and</strong> Trace/Drop. <strong>The</strong> type_ field is used to differenti<strong>at</strong>e among the various types of traces any particularTrace object might implement. Currently, this field may contain one of the following symbolic characters: + for enque,- for deque, h for hop, <strong>and</strong> d for drop. <strong>The</strong> overall class is defined as follows in ~<strong>ns</strong>/trace.cc:class Trace : public Connector {protected:int type_;<strong>ns</strong>addr_t src_;<strong>ns</strong>addr_t dst_;Tcl_Channel channel_;int callback_;char wrk_[256];void form<strong>at</strong>(int tt, int s, int d, Packet* p);void annot<strong>at</strong>e(co<strong>ns</strong>t char* s);int show_tcphdr_; // bool flags; backward comp<strong>at</strong>public:Trace(int type);~Trace();int comm<strong>and</strong>(int argc, co<strong>ns</strong>t char*co<strong>ns</strong>t* argv);void recv(Packet* p, H<strong>and</strong>ler*);void dump();inline char* buffer() { return (wrk_); }};<strong>The</strong> src_, <strong>and</strong> dst_ internal st<strong>at</strong>e is used to label trace output <strong>and</strong> is independent of the corresponding field names in packetheaders. <strong>The</strong> main recv() method is defined as follows:void Trace::recv(Packet* p, H<strong>and</strong>ler* h){form<strong>at</strong>(type_, src_, dst_, p);dump();/* hack: if trace object not <strong>at</strong>tached to anything free packet */if (target_ == 0)Packet::free(p);elsesend(p, h); /* Connector::send() */}<strong>The</strong> function merely form<strong>at</strong>s a trace entry using the source, destin<strong>at</strong>ion, <strong>and</strong> particular trace type character. <strong>The</strong> dump functionwrites the form<strong>at</strong>ted entry out to the I/O h<strong>and</strong>le associ<strong>at</strong>ed with channel_. <strong>The</strong> form<strong>at</strong> function, in effect, dict<strong>at</strong>es thetrace file form<strong>at</strong>.234


26.4 Trace File Form<strong>at</strong><strong>The</strong> Trace::form<strong>at</strong>() method defines the trace file form<strong>at</strong> used in trace files produced by the Trace class. It is co<strong>ns</strong>tructedto maintain backward comp<strong>at</strong>ibility with output files in earlier versio<strong>ns</strong> of the simul<strong>at</strong>or (i.e., <strong>ns</strong> v1) so th<strong>at</strong> <strong>ns</strong> v1post-processing scripts continue to oper<strong>at</strong>e. <strong>The</strong> important pieces of its implement<strong>at</strong>ion are as follows:// this function should retain some backward-comp<strong>at</strong>ibility, so th<strong>at</strong>// scripts don’t break.void Trace::form<strong>at</strong>(int tt, int s, int d, Packet* p){hdr_cmn *th = (hdr_cmn*)p->access(off_cmn_);hdr_ip *iph = (hdr_ip*)p->access(off_ip_);hdr_tcp *tcph = (hdr_tcp*)p->access(off_tcp_);hdr_rtp *rh = (hdr_rtp*)p->access(off_rtp_);packet_t t = th->ptype();co<strong>ns</strong>t char* name = packet_info.name(t);if (name == 0)abort();int seqno;/* XXX *//* CBR’s now have seqno’s too */if (t == PT_RTP || t == PT_CBR)seqno = rh->seqno();else if (t == PT_TCP || t == PT_ACK)seqno = tcph->seqno();elseseqno = -1;...if (!show_tcphdr_) {sprintf(wrk_, "%c %g %d %d %s %d %s %d %d.%d %d.%d %d %d",tt,Scheduler::i<strong>ns</strong>tance().clock(),s,d,name,th->size(),flags,iph->flowid() /* was p->class_ */,iph->src() >> 8, iph->src() & 0xff, // XXXiph->dst() >> 8, iph->dst() & 0xff,seqno,th->uid() /* was p->uid_ */);// XXX} else {sprintf(wrk_,"%c %g %d %d %s %d %s %d %d.%d %d.%d %d %d %d 0x%x %d",tt,Scheduler::i<strong>ns</strong>tance().clock(),s,d,235


}name,th->size(),flags,iph->flowid() /* was p->class_ */,iph->src() >> 8, iph->src() & 0xff,iph->dst() >> 8, iph->dst() & 0xff,seqno,th->uid(), /* was p->uid_ */tcph->ackno(),tcph->flags(),tcph->hlen());// XXX// XXXThis function is somewh<strong>at</strong> unelegant, primarily due to the desire to maintain backward comp<strong>at</strong>ibility. It form<strong>at</strong>s the source,destin<strong>at</strong>ion, <strong>and</strong> type fields defined in the trace object (not in the packet headers), the current time, along with various packetheader fields including, type of packet (as a name), size, flags (symbolically), flow identifier, source <strong>and</strong> destin<strong>at</strong>ion packetheader fields, sequence number (if present), <strong>and</strong> unique identifier. <strong>The</strong> show_tcphdr_ variable indic<strong>at</strong>es whether thetrace output should append tcp header inform<strong>at</strong>ion (ack number, flags, header length) <strong>at</strong> the end of each output line. Thisis especially useful for simul<strong>at</strong>io<strong>ns</strong> using FullTCP agents (Section 34.3). An example of a trace file (without the tcp headerfields) might appear as follows:+ 1.84375 0 2 cbr 210 ------- 0 0.0 3.1 225 610- 1.84375 0 2 cbr 210 ------- 0 0.0 3.1 225 610r 1.84471 2 1 cbr 210 ------- 1 3.0 1.0 195 600r 1.84566 2 0 ack 40 ------- 2 3.2 0.1 82 602+ 1.84566 0 2 tcp 1000 ------- 2 0.1 3.2 102 611- 1.84566 0 2 tcp 1000 ------- 2 0.1 3.2 102 611r 1.84609 0 2 cbr 210 ------- 0 0.0 3.1 225 610+ 1.84609 2 3 cbr 210 ------- 0 0.0 3.1 225 610d 1.84609 2 3 cbr 210 ------- 0 0.0 3.1 225 610- 1.8461 2 3 cbr 210 ------- 0 0.0 3.1 192 511r 1.84612 3 2 cbr 210 ------- 1 3.0 1.0 196 603+ 1.84612 2 1 cbr 210 ------- 1 3.0 1.0 196 603- 1.84612 2 1 cbr 210 ------- 1 3.0 1.0 196 603+ 1.84625 3 2 cbr 210 ------- 1 3.0 1.0 199 612Here we see 14 trace entries, five enque oper<strong>at</strong>io<strong>ns</strong> (indic<strong>at</strong>ed by “+” in the first column), four deque oper<strong>at</strong>io<strong>ns</strong> (indic<strong>at</strong>ed by“-”), four receive events (indic<strong>at</strong>ed by “r”), <strong>and</strong> one drop event. (this had better be a trace fragment, or some packets wouldhave just vanished!). <strong>The</strong> simul<strong>at</strong>ed time (in seconds) <strong>at</strong> which each event occurred is listed in the second column. <strong>The</strong> nexttwo fields indic<strong>at</strong>e between which two nodes tracing is happening. <strong>The</strong> next field is a descriptive name for the the type ofpacket seen (Section 26.5). <strong>The</strong> next field is the packet’s size, as encoded in its IP header.<strong>The</strong> next field contai<strong>ns</strong> the flags, which not used in this example. <strong>The</strong> flags are defined in the flags[] array in trace.cc. Fourof the flags are used for ECN: “E” for Congestion Experienced (CE) <strong>and</strong> “N” for ECN-Capable-Tra<strong>ns</strong>port (ECT) indic<strong>at</strong>io<strong>ns</strong>in the IP header, <strong>and</strong> “C” for ECN-Echo <strong>and</strong> “A” for Congestion Window Reduced (CWR) in the TCP header. For the otherflags, “P” is for priority, <strong>and</strong> “F” is for TCP Fast Start.<strong>The</strong> next field gives the IP flow identifier field as defined for IP version 6. 1 . <strong>The</strong> subsequent two fields indic<strong>at</strong>e the packet’ssource <strong>and</strong> destin<strong>at</strong>ion node addresses, respectively. <strong>The</strong> following field indic<strong>at</strong>es the sequence number. 2 <strong>The</strong> last field is a1 In <strong>ns</strong> v1, each packet included a class field, which was used by CBQ to classify packets. It then found additional use to differenti<strong>at</strong>e between “flows”<strong>at</strong> one trace point. In <strong>ns</strong> v2, the flow ID field is available for this purpose, but any additional inform<strong>at</strong>ion (which was commonly overloaded into the classfield in <strong>ns</strong> v1) should be placed in its own separ<strong>at</strong>e field, possibly in some other header2 In <strong>ns</strong> v1, all packets contained a sequence number, whereas in <strong>ns</strong> v2 only those Agents interested in providing sequencing will gener<strong>at</strong>e sequencenumbers. Thus, this field may not be useful in <strong>ns</strong> v2 for packets gener<strong>at</strong>ed by agents th<strong>at</strong> have not filled in a sequence number. It is used here to remainbackward comp<strong>at</strong>ible with <strong>ns</strong> v1.236


unique packet identifier. Each new packet cre<strong>at</strong>ed in the simul<strong>at</strong>ion is assigned a new, unique identifier.26.5 Packet TypesEach packet contai<strong>ns</strong> a packet type field used by Trace::form<strong>at</strong> to print out the type of packet encountered. <strong>The</strong> type fieldis defined in the TraceHeader class, <strong>and</strong> is co<strong>ns</strong>idered to be part of the trace support; it is not interpreted elsewhere in thesimul<strong>at</strong>or. Initializ<strong>at</strong>ion of the type field in packets is performed by the Agent::allocpkt(void) method. <strong>The</strong> type field isset to integer values associ<strong>at</strong>ed with the definition passed to the Agent co<strong>ns</strong>tructor (Section 10.6.3). <strong>The</strong> currently-supporteddefinitio<strong>ns</strong>, their values, <strong>and</strong> their associ<strong>at</strong>ed symblic names are as follows (defined in ~<strong>ns</strong>/packet.h):enum packet_t {PT_TCP,PT_UDP,PT_CBR,PT_AUDIO,PT_VIDEO,PT_ACK,PT_START,PT_STOP,PT_PRUNE,PT_GRAFT,PT_GRAFTACK,PT_JOIN,PT_ASSERT,PT_MESSAGE,PT_RTCP,PT_RTP,PT_RTPROTO_DV,PT_CtrMcast_Encap,PT_CtrMcast_Decap,PT_SRM,/* simple signalling messages */PT_REQUEST,PT_ACCEPT,PT_CONFIRM,PT_TEARDOWN,PT_LIVE,// packet from live networkPT_REJECT,PT_TELNET,// not needed: telnet use TCPPT_FTP,PT_PARETO,PT_EXP,PT_INVAL,PT_HTTP,/* new encapsul<strong>at</strong>or */PT_ENCAPSULATED,PT_MFTP,/* CMU/Monarch’s ext<strong>ns</strong>io<strong>ns</strong> */PT_ARP,PT_MAC,237


PT_TORA,PT_DSR,PT_AODV,// i<strong>ns</strong>ert new packet types herePT_NTYPE // This MUST be the LAST one};<strong>The</strong> co<strong>ns</strong>tructor of class p_info glues these co<strong>ns</strong>tants with their string values:p_info() {name_[PT_TCP]= "tcp";name_[PT_UDP]= "udp";name_[PT_CBR]= "cbr";name_[PT_AUDIO]= "audio";...name_[PT_NTYPE]= "undefined";}See also section 12.2.2 for more details.26.6 Queue MonitoringQueue monitoring refers to the capability of tracking the dynamics of packets <strong>at</strong> a queue (or other object). A queue monitortracks packet arrival/departure/drop st<strong>at</strong>istics, <strong>and</strong> may optionally compute averages of these values. Monitoring may beapplied to all packets (aggreg<strong>at</strong>e st<strong>at</strong>istics), or per-flow st<strong>at</strong>istics (using a Flow Monitor).Several classes are used in supporting queue monitoring. When a packet arrives <strong>at</strong> a link where queue monitoring is enabled, itgenerally passes through a SnoopQueue object when it arrives <strong>and</strong> leaves (or is dropped). <strong>The</strong>se objects contain a referenceto a QueueMonitor object.A QueueMonitor is defined as follows (~<strong>ns</strong>/queue-monitor.cc):class QueueMonitor : public TclObject {public:QueueMonitor() : bytesInt_(NULL), pktsInt_(NULL), delaySamp_(NULL),size_(0), pkts_(0),parrivals_(0), barrivals_(0),pdepartures_(0), bdepartures_(0),pdrops_(0), bdrops_(0),srcId_(0), dstId_(0), channel_(0) {bind("size_", &size_);bind("pkts_", &pkts_);bind("parrivals_", &parrivals_);bind("barrivals_", &barrivals_);bind("pdepartures_", &pdepartures_);bind("bdepartures_", &bdepartures_);238


};bind("pdrops_", &pdrops_);bind("bdrops_", &bdrops_);bind("off_cmn_", &off_cmn_);int size() co<strong>ns</strong>t { return (size_); }int pkts() co<strong>ns</strong>t { return (pkts_); }int parrivals() co<strong>ns</strong>t { return (parrivals_); }int barrivals() co<strong>ns</strong>t { return (barrivals_); }int pdepartures() co<strong>ns</strong>t { return (pdepartures_); }int bdepartures() co<strong>ns</strong>t { return (bdepartures_); }int pdrops() co<strong>ns</strong>t { return (pdrops_); }int bdrops() co<strong>ns</strong>t { return (bdrops_); }void printSt<strong>at</strong>s();virtual void in(Packet*);virtual void out(Packet*);virtual void drop(Packet*);virtual void edrop(Packet*) { abort(); }; // not herevirtual int comm<strong>and</strong>(int argc, co<strong>ns</strong>t char*co<strong>ns</strong>t* argv);...// packet arrival to a queuevoid QueueMonitor::in(Packet* p){hdr_cmn* hdr = (hdr_cmn*)p->access(off_cmn_);double now = Scheduler::i<strong>ns</strong>tance().clock();int pktsz = hdr->size();}barrivals_ += pktsz;parrivals_++;size_ += pktsz;pkts_++;if (bytesInt_)bytesInt_->newPoint(now, double(size_));if (pktsInt_)pktsInt_->newPoint(now, double(pkts_));if (delaySamp_)hdr->timestamp() = now;if (channel_)printSt<strong>at</strong>s();... in(), out(), drop() are all defined similarly ...It addition to the packet <strong>and</strong> byte counters, a queue monitor may optionally refer to objects th<strong>at</strong> keep an integral of the queuesize over time using Integr<strong>at</strong>or objects, which are defined in Section 25.3. <strong>The</strong> Integr<strong>at</strong>or class provides a simpleimplement<strong>at</strong>ion of integral approxim<strong>at</strong>ion by discrete sums.All bound variables beginning with p refer to packet counts, <strong>and</strong> all variables beginning with b refer to byte counts. <strong>The</strong>variable size_ records the i<strong>ns</strong>tantaneous queue size in bytes, <strong>and</strong> the variable pkts_ records the same value in packets.When a QueueMonitor is configured to include the integral functio<strong>ns</strong> (on bytes or packets or both), it computes theapproxim<strong>at</strong>e integral of the queue size (in bytes) with respect to time over the interval [t 0 , now], where t 0 is either the start ofthe simul<strong>at</strong>ion or the last time the sum_ field of the underlying Integr<strong>at</strong>or class was reset.239


<strong>The</strong> QueueMonitor class is not derived from Connector, <strong>and</strong> is not linked directly into the network topology. R<strong>at</strong>her,objects of the SnoopQueue class (or its derived classes) are i<strong>ns</strong>erted into the network topology, <strong>and</strong> these objects containreferences to an associ<strong>at</strong>ed queue monitor. Ordinarily, multiple SnoopQueue objects will refer to the same queue monitor.Objects co<strong>ns</strong>tructed out of these classes are linked in the simul<strong>at</strong>ion topology as described above <strong>and</strong> call QueueMonitorout, in, or drop procedures, depending on the particular type of snoopy queue.26.7 Per-Flow MonitoringA collection of specialized classes are used to to implement per-flow st<strong>at</strong>istics g<strong>at</strong>hering. <strong>The</strong>se classes include:QueueMonitor/ED/Flowmon, QueueMonitor/ED/Flow, <strong>and</strong> Classifier/Hash. Typically, an arriving packetis i<strong>ns</strong>pected to determine to which flow it belongs. This i<strong>ns</strong>pection <strong>and</strong> flow mapping is performed by a classifier object(described in section 26.7.1). Once the correct flow is determined, the packet is passed to a flow monitor, which is respo<strong>ns</strong>iblefor collecting per-flow st<strong>at</strong>e. Per-flow st<strong>at</strong>e is contained in flow objects in a one-to-one rel<strong>at</strong>io<strong>ns</strong>hip to the flows known by theflow monitor. Typically, a flow monitor will cre<strong>at</strong>e flow objects on-dem<strong>and</strong> when packets arrive th<strong>at</strong> cannot be mapped to analready-known flow.26.7.1 <strong>The</strong> Flow Monitor<strong>The</strong> QueueMonitor/ED/Flowmon class is respo<strong>ns</strong>ible for managing the cre<strong>at</strong>ion of new flow objects when packets arriveon previously unknown flows <strong>and</strong> for upd<strong>at</strong>ing existing flow objects. Because it is a subclass of QueueMonitor, each flowmonitor contai<strong>ns</strong> an aggreg<strong>at</strong>e count of packet <strong>and</strong> byte arrivals, departures, <strong>and</strong> drops. Thus, it is not necessary to cre<strong>at</strong>e asepar<strong>at</strong>e queue monitor to record aggreg<strong>at</strong>e st<strong>at</strong>istics. It provides the following OTcl interface:classifier<strong>at</strong>tachdumpflowsget(set) classifier to map packets to flows<strong>at</strong>tach a Tcl I/O channel to this monitordump contents of flow monitor to Tcl channelreturn string of flow object names known to this monitor<strong>The</strong> classifier function sets or gets the name of the previously-alloc<strong>at</strong>ed object which will perform packet-to-flowmapping for the flow monitor. Typically, the type of classifier used will have to do with the notion of “flow” held by the user.One of the hash based classifiers th<strong>at</strong> i<strong>ns</strong>pect various IP-level header fields is typically used here (e.g. fid, src/dst, src/dst/fid).Note th<strong>at</strong> while classifiers usually receive packets <strong>and</strong> forward them on to dow<strong>ns</strong>tream objects, the flow monitor uses theclassifier only for its packet mapping capability, so the flow monitor acts as a passive monitor only <strong>and</strong> does not activelyforward packets.<strong>The</strong> <strong>at</strong>tach <strong>and</strong> dump functio<strong>ns</strong> are used to associ<strong>at</strong>e a Tcl I/O stream with the flow monitor, <strong>and</strong> dump its contentson-dem<strong>and</strong>. <strong>The</strong> file form<strong>at</strong> used by the dump comm<strong>and</strong> is described below.<strong>The</strong> flows function retur<strong>ns</strong> a list of the names of flows known by the flow monitor in a way underst<strong>and</strong>able to Tcl. Thisallows tcl code to interrog<strong>at</strong>e a flow monitor in order to obtain h<strong>and</strong>les to the individual flows it maintai<strong>ns</strong>.26.7.2 Flow Monitor Trace Form<strong>at</strong><strong>The</strong> flow monitor defines a trace form<strong>at</strong> which may be used by post-processing scripts to determine various counts on aper-flow basis. <strong>The</strong> form<strong>at</strong> is defined by the following code in ~<strong>ns</strong>/flowmon.cc:240


voidFlowMon::fform<strong>at</strong>(Flow* f){double now = Scheduler::i<strong>ns</strong>tance().clock();sprintf(wrk_, "%8.3f %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d%d",now,f->flowid(), // flowid0, // c<strong>at</strong>egoryf->ptype(), // type (from common header)f->flowid(), // flowid (<strong>formerly</strong> class)f->src(),f->dst(),f->parrivals(), // arrivals this flow (pkts)f->barrivals(), // arrivals this flow (bytes)f->epdrops(), // early drops this flow (pkts)f->ebdrops(), // early drops this flow (bytes)parrivals(), // all arrivals (pkts)barrivals(), // all arrivals (bytes)epdrops(), // total early drops (pkts)ebdrops(), // total early drops (bytes)pdrops(), // total drops (pkts)bdrops(), // total drops (bytes)f->pdrops(), // drops this flow (pkts) [includes edrops]f->bdrops() // drops this flow (bytes) [includes edrops]);};Most of the fields are explained in the code comments. <strong>The</strong> “c<strong>at</strong>egory” is historical, but is used to maintain loose backwardcomp<strong>at</strong>ibilitywith the flow manager form<strong>at</strong> in <strong>ns</strong> version 1.26.7.3 <strong>The</strong> Flow Class<strong>The</strong> class QueueMonitor/ED/Flow is used by the flow monitor for containing per-flow counters. As a subclass ofQueueMonitor, it inherits the st<strong>and</strong>ard counters for arrivals, departures, <strong>and</strong> drops, both in packets <strong>and</strong> bytes. In addition,because each flow is typically identified by some combin<strong>at</strong>ion of the packet source, destin<strong>at</strong>ion, <strong>and</strong> flow identifier fields,these objects contain such fields. Its OTcl interface contai<strong>ns</strong> only bound variables:src_dst_flowid_source address on packets for this flowdestin<strong>at</strong>ion address on packets for this flowflow id on packets for this flowNote th<strong>at</strong> packets may be mapped to flows (by classifiers) using criteria other than a src/dst/flowid triple. In such circumstances,only those fields actually used by the classifier in performing the packet-flow mapping should be co<strong>ns</strong>idered reliable.26.8 Comm<strong>and</strong>s <strong>at</strong> a glanceFollowing is a list of trace rel<strong>at</strong>ed comm<strong>and</strong>s commonly used in simul<strong>at</strong>ion scripts:241


$<strong>ns</strong>_ trace-all This is the comm<strong>and</strong> used to setup tracing in <strong>ns</strong>. All traces are written in the .$<strong>ns</strong>_ namtrace-all This comm<strong>and</strong> sets up nam tracing in <strong>ns</strong>. All nam traces are written in to the .$<strong>ns</strong>_ namtrace-all-wireless This comm<strong>and</strong> sets up wireless nam tracing. <strong>and</strong> are the x-y co-ordin<strong>at</strong>es for the wireless topology <strong>and</strong> allwireless nam traces are written into the .$<strong>ns</strong>_ nam-end-wireless This tells nam the simul<strong>at</strong>ion stop time given in .$<strong>ns</strong>_ trace-all-s<strong>at</strong>links This is a method to trace s<strong>at</strong>ellite links <strong>and</strong> write traces into .$<strong>ns</strong>_ flush-traceThis comm<strong>and</strong> flushes the trace buffer <strong>and</strong> is typically called before the simul<strong>at</strong>ion run ends.$<strong>ns</strong>_ get-nam-traceallRetur<strong>ns</strong> the namtrace file descriptor stored as the Simul<strong>at</strong>or i<strong>ns</strong>tance variable called namtraceAllFile_.$<strong>ns</strong>_ get-<strong>ns</strong>-traceallSimilar to get-nam-traceall. This retur<strong>ns</strong> the file descriptor for <strong>ns</strong> tracefile which is stored as the Simul<strong>at</strong>or i<strong>ns</strong>tance calledtraceAllFile_.$<strong>ns</strong>_ cre<strong>at</strong>e-trace This comm<strong>and</strong> cre<strong>at</strong>es a trace object of type between the <strong>and</strong> nodes. <strong>The</strong> traces are written into the. is the argument th<strong>at</strong> may be used to specify the type of trace, like nam. if is not defined, the default traceobject cre<strong>at</strong>ed is for <strong>ns</strong>traces.$<strong>ns</strong>_ trace-queue This is a wrapper method for cre<strong>at</strong>e-trace. This comm<strong>and</strong> cre<strong>at</strong>es a trace object for tracing events on the linkrepresented by the nodes <strong>and</strong> .$<strong>ns</strong>_ namtrace-queue This is used to cre<strong>at</strong>e a trace object for namtracing on the link between nodes <strong>and</strong> . This method is very similar to<strong>and</strong> is the namtrace counterpart of method trace-queue.$<strong>ns</strong>_ drop-trace This comm<strong>and</strong> makes the given object a drop-target for the queue associ<strong>at</strong>ed with the link between nodes <strong>and</strong>.$<strong>ns</strong>_ monitor-queue This sets up a monitor th<strong>at</strong> keeps track of average queue length of the queue on the link between nodes <strong>and</strong> . <strong>The</strong>default value of sampleinterval is 0.1.$link trace-dynamics Trace the dynamics of this link <strong>and</strong> write the output to fileID fileh<strong>and</strong>le.<strong>ns</strong> is an i<strong>ns</strong>tance of the Simul<strong>at</strong>or or MultiSim object th<strong>at</strong> was cre<strong>at</strong>ed to invoke the simul<strong>at</strong>ion.<strong>The</strong> tracefile form<strong>at</strong> is backward comp<strong>at</strong>ible with the output files in the <strong>ns</strong> version 1 simul<strong>at</strong>or so th<strong>at</strong> <strong>ns</strong>-1 postprocessingscripts can still be used. Trace records of traffic for link objects with Enque, Deque, receive or Drop Tracing have thefollowing form: 242


where := [hd+-] h=hop d=drop +=enque -=deque r=receive :=simul<strong>at</strong>ion time in seconds := first node address of hop/queuing link := second node address of hop/queuing link := := tcp|telnet|cbr|ack etc. := packet size in bytes := [CP] C=congestion, P=priority := flow identifier field as defined for IPv6 := tra<strong>ns</strong>port address (src=node,sport=agent) := tra<strong>ns</strong>port address (dst=node,dport=agent) := packet sequence number := unique identifer for every new packetOnly those agents interested in providing sequencing will gener<strong>at</strong>e sequence numbers <strong>and</strong> hence this field may not be usefulfor packets gener<strong>at</strong>ed by some agents. For links th<strong>at</strong> use RED g<strong>at</strong>eways, there are additional trace records as follows: where := [Qap] Q=queue size, a=average queue size, p=packet droppingprobability := simul<strong>at</strong>ion time in seconds := valueTrace records for link dynamics are of the form: where := [v] := simul<strong>at</strong>ion time in seconds := [link-up | link-down] := first node address of link := second node address of link243


Chapter 27Test Suite Support<strong>The</strong> <strong>ns</strong> distribution contai<strong>ns</strong> many test suites under ~<strong>ns</strong>/tcl/test, which used by valid<strong>at</strong>ion programs (~<strong>ns</strong>/valid<strong>at</strong>e, valid<strong>at</strong>ewired,valid<strong>at</strong>e-wireless, <strong>and</strong> valid<strong>at</strong>e.win32) to verify th<strong>at</strong> the i<strong>ns</strong>tall<strong>at</strong>ion of <strong>ns</strong> is correct. If you modify or add new modulesto <strong>ns</strong>, you are encouraged to run the valid<strong>at</strong>ion programs to make sure th<strong>at</strong> your changes do not affect other parts in <strong>ns</strong>.27.1 Test Suite ComponentsEach test suite under ~<strong>ns</strong>/tcl/test is written to verify the correctness of a certain module in <strong>ns</strong>. It has 3 components:• A shell script (test-all-xxx) to start the test;• A <strong>ns</strong> tcl script (test-suite-xxx.tcl) to actually run through the tests defined.• A subdirectory (test-output-xxx) under ~<strong>ns</strong>/tcl/test, which contai<strong>ns</strong> thecorrect trace files gener<strong>at</strong>ed by the test suite.<strong>The</strong>se files are used to verify if the test suite ru<strong>ns</strong> correctly with your <strong>ns</strong>.(Note: xxx st<strong>and</strong>s for the name of the test suite.)27.2 Write a Test SuiteYou can take one of the test suites under ~<strong>ns</strong>/tcl/test as a templ<strong>at</strong>e when you are writing your own, for example the test suitewritten for wireless lan (test-all-wireless-lan, test-suite-wireless-lan.tcl, <strong>and</strong> test-output-wireless-lan).To write a test suite, you first need to write the shell script (test-all-xxx). In the shell script, you specify the module to betested, the name of the <strong>ns</strong> tcl script <strong>and</strong> the output subdirectory. You can run this shell script in quiet mode. Below is theexample (test-all-wireless-lan):# To run in quiet mode: "./test-all-wireless-lan quiet".f="wireless-lan" # Specify the name of the module to test.244


file="test-suite-$f.tcl" # <strong>The</strong> name of the <strong>ns</strong> script.directory="test-output-$f" # Subdirectory to hold the test resultsversion="v2" # Speficy the <strong>ns</strong> version.# Pass the arguments to test-all-templ<strong>at</strong>e1, which will run through# all the test cases defined in test-suite-wireless-lan.tcl../test-all-templ<strong>at</strong>e1 $file $directory $version $@You also need to cre<strong>at</strong>e several test cases in the <strong>ns</strong> script (test-suite-xxx.tcl) by defining a subclass of TestSuite for eachdifferent test. For example, in test-suite-wireless-lan.tcl, each test case uses a different Ad Hoc routing protocol. <strong>The</strong>y aredefined as:Class TestSuite# wireless model using destin<strong>at</strong>ion sequence distance vectorClass Test/dsdv -superclass TestSuite# wireless model using dynamic source routingClass Test/dsr -superclass TestSuite... ...Each test case is basically a simul<strong>at</strong>ion scenario. In the super class TestSuite, you can define some functio<strong>ns</strong>, like init <strong>and</strong>finish to do the work required by each test case, for example setting up the network topology <strong>and</strong> <strong>ns</strong> trace. <strong>The</strong> test specificconfigur<strong>at</strong>io<strong>ns</strong> are defined within the corresponding sub-class. Each sub-class also has a run function to start the simul<strong>at</strong>ion.TestSuite i<strong>ns</strong>tproc init {} {global opt tracefd topo chan propglobal node_ god_$self i<strong>ns</strong>tvar <strong>ns</strong>_ testName_set <strong>ns</strong>_[new Simul<strong>at</strong>or]... ...}TestSuite i<strong>ns</strong>tproc finish {} {$self i<strong>ns</strong>tvar <strong>ns</strong>_global quiet$<strong>ns</strong>_ flush-trace}puts "finishing.."exit 0Test/dsdv i<strong>ns</strong>tproc init {} {global opt node_ god_$self i<strong>ns</strong>tvar <strong>ns</strong>_ testName_set testName_ dsdv... ...$self next245


... ...}$<strong>ns</strong>_ <strong>at</strong> $opt(stop).1 "$self finish"Test/dsdv i<strong>ns</strong>tproc run {} {$self i<strong>ns</strong>tvar <strong>ns</strong>_puts "Starting Simul<strong>at</strong>ion..."$<strong>ns</strong>_ run}All the tests are started by the function runtest in the <strong>ns</strong> script.proc runtest {arg} {global quietset quiet 0}set b [llength $arg]if {$b == 1} {set test $arg} elseif {$b == 2} {set test [lindex $arg 0]if {[lindex $arg 1] == "QUIET"} {set quiet 1}} else {usage}set t [new Test/$test]$t runglobal argv arg0runtest $argvWhen you run the tests, trace files are gener<strong>at</strong>ed <strong>and</strong> saved to the output subdirectory. <strong>The</strong>se trace files are compared to thethose correct trace coming with the test suite. If the compar<strong>at</strong>ion shows difference, the test is failed.246


Chapter 28<strong>ns</strong> Code StylesWe recommend the following coding guidelines for <strong>ns</strong>28.1 Indent<strong>at</strong>ion style• We recommend using the BSD Kernel Normal Form coding style loc<strong>at</strong>ed <strong>at</strong>http://cvsweb.netbsd.org/bsdweb.cgi/sharesrc/share/misc/style?rev=HEAD&content-type=text/x-cvsweb-markup• Although KNF is specified for C, it also applies reasonably well to C++ <strong>and</strong> Tcl. Most of <strong>ns</strong> already follows KNF <strong>and</strong>it is also exte<strong>ns</strong>ively used for the BSD <strong>and</strong> Linux kernels.• <strong>The</strong> high order bit is 8-space indents. Using 8-space indents avoid confusion about wh<strong>at</strong> a "tab" character represents. Adow<strong>ns</strong>ide is it makes deeply nested looping structures hard to fit in 80 colum<strong>ns</strong>. (Some people co<strong>ns</strong>ider this a fe<strong>at</strong>ure.:-)28.2 Variable Naming Conventio<strong>ns</strong>• I<strong>ns</strong>tance variables of a class should all end in an underscore. This helps distinguish i<strong>ns</strong>tance variables from global <strong>and</strong>local variables.• C++ <strong>and</strong> Tcl bound variables should have the same names This helps identify the bound variables quickly <strong>and</strong> reducescomplexity28.3 Miscellaneous• Avoid the use of C++ templ<strong>at</strong>es. Ns is supported on multiple pl<strong>at</strong>forms <strong>and</strong> templ<strong>at</strong>es are not very portable <strong>and</strong> areoften difficult to debug. Exception: This guideline has been relaxed for some imported code, but the core of <strong>ns</strong> shouldbuild <strong>and</strong> run without templ<strong>at</strong>es.• For NsObjects, use the debug_ i<strong>ns</strong>tance variable to enable debugging functionality. This avoids repetitive defin<strong>at</strong>io<strong>ns</strong>of debug st<strong>at</strong>ements <strong>and</strong> allows debugging a particular Nsobject without recompil<strong>at</strong>ion.247


Example: To enable debugging in Queue object include the following st<strong>at</strong>ement in your tcl script.Queue set debug_ trueDebugging st<strong>at</strong>ments can be i<strong>ns</strong>erted in the classes inheriting from Queue as follows:debug("This is a debug st<strong>at</strong>ement %d",variable_to_debug);All debugging st<strong>at</strong>ements are sent to stdout.• Error messages which cause the program to exit should be sent to stderr. All other messages should be sent to stdout248


Part IVRouting249


Chapter 29Unicast RoutingThis section describes the structure of unicast routing in <strong>ns</strong>. We begin by describing the interface to the user (Section 29.1),through methods in the class Simul<strong>at</strong>or <strong>and</strong> the class RouteLogic. We then describe configur<strong>at</strong>ion mechanismsfor specialized routing (Section 29.2) such as asymmetric routing, or equal cost multip<strong>at</strong>h routing <strong>The</strong> next section describesthe the configur<strong>at</strong>ion mechanisms for individual routing str<strong>at</strong>egies <strong>and</strong> protocols (Section 29.3). We conclude with a comprehe<strong>ns</strong>ivelook <strong>at</strong> the internal architecture (Section 29.4) of routing in <strong>ns</strong>.<strong>The</strong> procedures <strong>and</strong> functio<strong>ns</strong> described in this chapter can be found in ~<strong>ns</strong>/tcl/lib/<strong>ns</strong>-route.tcl, ~<strong>ns</strong>/tcl/rtglib/route-proto.tcl,~<strong>ns</strong>/tcl/mcast/McastProto.tcl, <strong>and</strong> ~<strong>ns</strong>/rtProtoDV.{cc, h}.29.1 <strong>The</strong> Interface to the Simul<strong>at</strong>ion Oper<strong>at</strong>or (<strong>The</strong> API)<strong>The</strong> user level simul<strong>at</strong>ion script requires one comm<strong>and</strong>: to specify the unicast routing str<strong>at</strong>egy or protocols for the simul<strong>at</strong>ion.A routing str<strong>at</strong>egy is a general mechanism by which <strong>ns</strong> will compute routes for the simul<strong>at</strong>ion. <strong>The</strong>re are four routing str<strong>at</strong>egiesin <strong>ns</strong>: St<strong>at</strong>ic, Session, Dynamic <strong>and</strong> <strong>Manual</strong>. Conversely, a routing protocol is a realiz<strong>at</strong>ion of a specific algorithm. Currently,St<strong>at</strong>ic <strong>and</strong> Session routing use the Dijkstra’s all-pairs SPF algorithm []; one type of dynamic routing str<strong>at</strong>egy is currentlyimplemented: the Distributed Bellman-Ford algorithm []. In <strong>ns</strong>, we blur the distinction between str<strong>at</strong>egy <strong>and</strong> protocol forst<strong>at</strong>ic <strong>and</strong> session routing, co<strong>ns</strong>idering them simply as protocols 1 .rtproto{} is the i<strong>ns</strong>tance procedure in the class Simul<strong>at</strong>or th<strong>at</strong> specifies the unicast routing protocol to be used inthe simul<strong>at</strong>ion. It takes multiple arguments, the first of which is m<strong>and</strong><strong>at</strong>ory; this first argument identifies the routing protocolto be used. Subsequent arguments specify the nodes th<strong>at</strong> will run the i<strong>ns</strong>tance of this protocol. <strong>The</strong> default is to run thesame routing protocol on all the nodes in the topology. As an example, the following comm<strong>and</strong>s illustr<strong>at</strong>e the use of thertproto{} comm<strong>and</strong>.$<strong>ns</strong> rtproto St<strong>at</strong>ic;# Enable st<strong>at</strong>ic route str<strong>at</strong>egy for the simul<strong>at</strong>ion$<strong>ns</strong> rtproto Session;# Enable session routing for this simul<strong>at</strong>ion$<strong>ns</strong> rtproto DV $n1 $n2 $n3 ;# Run DV agents on nodes $n1, $n2, <strong>and</strong> $n3$<strong>ns</strong> rtproto LS $n1 $n2;# Run link st<strong>at</strong>e routing on specified nodesIf a simul<strong>at</strong>ion script does not specify any rtproto{} comm<strong>and</strong>, then <strong>ns</strong> will run St<strong>at</strong>ic routing on all the nodes in thetopology.1 <strong>The</strong> co<strong>ns</strong>ider<strong>at</strong>ion is th<strong>at</strong> st<strong>at</strong>ic <strong>and</strong> session routing str<strong>at</strong>egies/protocols are implemented as agents derived from the class Agent/rtProto similarto how the different dynamic routing protocols are implemented; hence the blurred distinctio<strong>ns</strong>.250


Multiple rtproto{} lines for the same or different routing protocols can occur in a simul<strong>at</strong>ion script. However, a simul<strong>at</strong>ioncannot use both centralized routing mechanisms such as st<strong>at</strong>ic or session routing <strong>and</strong> detailed dynamic routing protocols suchas DV.In dynamic routing, each node can be running more than one routing protocol. In such situ<strong>at</strong>io<strong>ns</strong>, more than one routingprotocol can have a route to the same destin<strong>at</strong>ion. <strong>The</strong>refore, each protocol affixes a preference value to each of its routes.<strong>The</strong>se values are non-neg<strong>at</strong>ive integers in the range 0. . . 255. <strong>The</strong> lower the value, the more preferred the route. When multiplerouting protocol agents have a route to the same destin<strong>at</strong>ion, the most preferred route is chosen <strong>and</strong> i<strong>ns</strong>talled in the node’sforwarding tables. If more than one agent has the most preferred routes, the ones with the lowest metric is chosen. We callthe least cost route from the most preferred protocol the “c<strong>and</strong>id<strong>at</strong>e” route. If there are multiple c<strong>and</strong>id<strong>at</strong>e routes from thesame or different protocols, then, currently, one of the agent’s routes is r<strong>and</strong>omly chosen 2 .Preference Assignment <strong>and</strong> Control Each protocol agent stores an array of route preferences, rtpref_. <strong>The</strong>re is oneelement per destin<strong>at</strong>ion, indexed by the node h<strong>and</strong>le. <strong>The</strong> default preference values used by each protocol are derived from aclass variable, preference_, for th<strong>at</strong> protocol. <strong>The</strong> current defaults are:Agent/rtProto set preference_ 200Agent/rtProto/Direct 3 set preference_ 100Agent/rtProto/DV set preference_ 120;# global default preferenceA simul<strong>at</strong>ion script can control routing by altering the preference for routes in one of three ways: alter the preference for aspecific route learned via a particular protocol agent, alter the preference for all routes learned by the agent, or alter the classvariables for the agent before the agent is cre<strong>at</strong>ed.Link Cost Assignment <strong>and</strong> Control In the currently implemented route protocols, the metric of a route to a destin<strong>at</strong>ion,<strong>at</strong> a node, is the cost to reach the destin<strong>at</strong>ion from th<strong>at</strong> node. It is possible to change the link costs <strong>at</strong> each of the links.<strong>The</strong> i<strong>ns</strong>tance procedure cost{} is invoked as $<strong>ns</strong> cost 〈node1〉 〈node2〉 〈cost〉,<strong>and</strong> sets the cost of the link from〈node1〉 to 〈node2〉 to 〈cost〉.$<strong>ns</strong> cost $n1 $n2 10 ;# set cost of link from $n1 to $n2 to 10$<strong>ns</strong> cost $n2 $n1 5 ;# set cost of link in reverse direction to 5[$<strong>ns</strong> link $n1 $n2] cost? ;# query cost of link from $n1 to $n2[$<strong>ns</strong> link $n2 $n1] cost?;# query cost of link in reverse directionNotice th<strong>at</strong> the procedure sets the cost along one direction only. Similarly, the procedure cost?{} retur<strong>ns</strong> the cost oftraversing the specified unidirectional link. <strong>The</strong> default cost of a link is 1.29.2 Other Configur<strong>at</strong>ion Mechanisms for Specialised RoutingIt is possible to adjust preference <strong>and</strong> cost mechanisms to get two special types of route configur<strong>at</strong>io<strong>ns</strong>: asymmetric routing,<strong>and</strong> multip<strong>at</strong>h routing.2 This really is undesirable, <strong>and</strong> may be fixed <strong>at</strong> some point. <strong>The</strong> fix will probably be to favor the agents in class preference order. A user level simul<strong>at</strong>ionrelying on this behavior, or getting into this situ<strong>at</strong>ion in specific topologies is not recommended.3 Direct is a special routing str<strong>at</strong>egy th<strong>at</strong> is used in conjunction with Dynamic routing. We will describe this in gre<strong>at</strong>er detail as part of the route architecturedescription.251


Asymmetric Routing Asymmetric routing occurs when the p<strong>at</strong>h from node n 1 to node n 2 is different from the p<strong>at</strong>h fromn 2 to n 1 . <strong>The</strong> following shows a simple topology, <strong>and</strong> cost configur<strong>at</strong>ion th<strong>at</strong> can achieve such a result:Nodes n 1 <strong>and</strong> n 2 use differentp<strong>at</strong>hs to reach each other. Allother pairs of nodes use symmetricp<strong>at</strong>hs to reach each other.n1r1r2n2$<strong>ns</strong> cost $n1 $r1 2$<strong>ns</strong> cost $n2 $r2 2$<strong>ns</strong> cost $r1 $n2 3Any routing protocol th<strong>at</strong> uses link costs as the metric can observe such asymmetric routing if the link costs are appropri<strong>at</strong>elyconfigured 4 .MultiP<strong>at</strong>h Routing Each node can be individually configured to use multiple separ<strong>at</strong>e p<strong>at</strong>hs to a particular destin<strong>at</strong>ion.<strong>The</strong> i<strong>ns</strong>tance variable multiP<strong>at</strong>h_ determines whether or not th<strong>at</strong> node will use multiple p<strong>at</strong>hs to any destin<strong>at</strong>ion. Eachnode initialises its i<strong>ns</strong>tance variable from a class variable of the same name. If multiple c<strong>and</strong>id<strong>at</strong>e routes to a destin<strong>at</strong>ionare available, all of which are learned through the same protocol, then th<strong>at</strong> node can use all of the different routes to thedestin<strong>at</strong>ion simultaneously. A typical configur<strong>at</strong>ion is as shown below:Node set multiP<strong>at</strong>h_ 1or altern<strong>at</strong>elyset n1 [$<strong>ns</strong> Node]$n1 set multiP<strong>at</strong>h_ 1;# All new nodes in the simul<strong>at</strong>ion use multiP<strong>at</strong>hs where applicable;# only enable $n1 to use multiP<strong>at</strong>hs where applicableCurrently, only DV routing can gener<strong>at</strong>e multip<strong>at</strong>h routes.29.3 Protocol Specific Configur<strong>at</strong>ion ParametersSt<strong>at</strong>ic Routing <strong>The</strong> st<strong>at</strong>ic route comput<strong>at</strong>ion str<strong>at</strong>egy is the default route comput<strong>at</strong>ion mechanism in <strong>ns</strong>. This str<strong>at</strong>egyuses the Dijkstra’s all-pairs SPF algorithm []. <strong>The</strong> route comput<strong>at</strong>ion algorithm is run exactly once prior to the start of thesimul<strong>at</strong>ion. <strong>The</strong> routes are computed using an adjacency m<strong>at</strong>rix <strong>and</strong> link costs of all the links in the topology.(Note th<strong>at</strong> st<strong>at</strong>ic routing is st<strong>at</strong>ic in the se<strong>ns</strong>e th<strong>at</strong> it is computed once when the simul<strong>at</strong>ion starts, as opposed to session <strong>and</strong>DV routing th<strong>at</strong> allow routes to change mid-simul<strong>at</strong>ion. An altern<strong>at</strong>ive to st<strong>at</strong>ic routing is <strong>Manual</strong> routing where routes arenot computed but i<strong>ns</strong>tead are set (manually) by the user.)Session Routing <strong>The</strong> st<strong>at</strong>ic routing str<strong>at</strong>egy described earlier only computes routes for the topology once in the course of asimul<strong>at</strong>ion. If the above st<strong>at</strong>ic routing is used <strong>and</strong> the topology changes while the simul<strong>at</strong>ion is in progress, some sources <strong>and</strong>destin<strong>at</strong>io<strong>ns</strong> may become temporarily unreachable from each other for a short time.Session routing str<strong>at</strong>egy is almost identical to st<strong>at</strong>ic routing, in th<strong>at</strong> it ru<strong>ns</strong> the Dijkstra all-pairs SPF algorithm prior to thestart of the simul<strong>at</strong>ion, using the adjacency m<strong>at</strong>rix <strong>and</strong> link costs of the links in the topology. However, it will also run thesame algorithm to recompute routes in the event th<strong>at</strong> the topology changes during the course of a simul<strong>at</strong>ion. In other words,route recomput<strong>at</strong>ion <strong>and</strong> recovery is done i<strong>ns</strong>tantaneously <strong>and</strong> there will not be tra<strong>ns</strong>ient routing outage as in st<strong>at</strong>ic routing.Session routing provides complete <strong>and</strong> i<strong>ns</strong>tantaneous routing changes in the presence of topology dynamics. If the topology isalways connected, there is end-to-end connectivity <strong>at</strong> all times during the course of the simul<strong>at</strong>ion. However, the user should4 Link costs can also be used to favour or disregard specific links in order to achieve particular topology configur<strong>at</strong>io<strong>ns</strong>.252


note th<strong>at</strong> the i<strong>ns</strong>tantaneous route recomput<strong>at</strong>ion of session routing does not prevent temporary viol<strong>at</strong>io<strong>ns</strong> of causality, such aspacket reordering, around the i<strong>ns</strong>tant th<strong>at</strong> the topology changes.DV Routing DV routing is the implement<strong>at</strong>ion of Distributed Bellman-Ford (or Distance Vector) routing in <strong>ns</strong>. <strong>The</strong>implement<strong>at</strong>ion sends periodic route upd<strong>at</strong>es every advertInterval. This variable is a class variable in the classAgent/rtProto/DV. Its default value is 2 seconds.In addition to periodic upd<strong>at</strong>es, each agent also sends triggered upd<strong>at</strong>es; it does this whenever the forwarding tables in thenode change. This occurs either due to changes in the topology, or because an agent <strong>at</strong> the node received a route upd<strong>at</strong>e, <strong>and</strong>recomputed <strong>and</strong> i<strong>ns</strong>talled new routes.Each agent employs the split horizon with poisoned reverse mechanisms to advertise its routes to adjacent peers. “Splithorizon” is the mechanism by which an agent will not advertise the route to a destin<strong>at</strong>ion out of the interface th<strong>at</strong> it is usingto reach th<strong>at</strong> destin<strong>at</strong>ion. In a “Split horizon with poisoned reverse” mechanism, the agent will advertise th<strong>at</strong> route out of th<strong>at</strong>interface with a metric of infinity.Each DV agent uses a default preference_ of 120. <strong>The</strong> value is determined by the class variable of the same name.Each agent uses the class variable INFINITY (set <strong>at</strong> 32) to determine the validity of a route.<strong>Manual</strong> Routing <strong>Manual</strong> routing is not a route comput<strong>at</strong>ion protocol (like the others), but simply a way for users toconfigure the routing table by h<strong>and</strong>, much as you would with the “route” comm<strong>and</strong> on a workst<strong>at</strong>ion.To use manual routing, enable it with rtproto, then set each nodes routing tables with the add-route-to-adj-node comm<strong>and</strong>.For example:$<strong>ns</strong> rtproto <strong>Manual</strong>set n1 [$<strong>ns</strong> node]set n2 [$<strong>ns</strong> node]$<strong>ns</strong> duplex-link $n1 $n2 10Mb 100ms DropTail$n1 add-route-to-adj-node -default $n2$n2 add-route-to-adj-node -default $n1For a more complete example, see tcl/ex/many_tcp.tcl.29.4 Internals <strong>and</strong> Architecture of RoutingWe start with a discussion of the classes associ<strong>at</strong>ed with unicast routing, <strong>and</strong> the code p<strong>at</strong>h used to configure <strong>and</strong> executeeach of the different routing protocols. We conclude with a description of the interface between unicast routing <strong>and</strong> networkdynamics, <strong>and</strong> th<strong>at</strong> between unicast <strong>and</strong> multicast routing.29.4.1 <strong>The</strong> classes<strong>The</strong>re are four main classes, the class RouteLogic, the class rtObject, the class rtPeer, <strong>and</strong> the base class Agent/rtProto for allprotocols. In addition, the routing architecture extends the classes Simul<strong>at</strong>or, Link, Node <strong>and</strong> Classifier.253


class RouteLogic This class defines two methods to configure unicast routing, <strong>and</strong> one method to query it for routeinform<strong>at</strong>ion. It also defines an i<strong>ns</strong>tance procedure th<strong>at</strong> is applicable when the topology is dynamic. We discuss this lastprocedure in conjunction with the interface to network dynamics.• <strong>The</strong> i<strong>ns</strong>tance procedure register{} is invoked by Simul<strong>at</strong>or::rtproto{}. It takes the protocol <strong>and</strong> a list ofnodes as arguments, <strong>and</strong> co<strong>ns</strong>tructs an i<strong>ns</strong>tance variable, rtprotos_, as an array; the array index is the name of theprotocol, <strong>and</strong> the value is the list of nodes th<strong>at</strong> will run this protocol.• <strong>The</strong> configure{} reads the rtprotos_ i<strong>ns</strong>tance variable, <strong>and</strong> for each element in the array, invokes route protocolmethods to perform the appropri<strong>at</strong>e initializ<strong>at</strong>io<strong>ns</strong>. It is invoked by the simul<strong>at</strong>or run procedure.For each protocol 〈rt-proto〉 indexed in the rtprotos_ array, this routine invokes Agent/rtProto/〈rt-proto〉init-all rtprotos_(〈rt-proto〉).If there are no elements in rtprotos_, the routine invokes St<strong>at</strong>ic routing, as Agent/rtProto/St<strong>at</strong>ic init-all.• <strong>The</strong> i<strong>ns</strong>tance procedure lookup{} takes two node numbers, nodeId 1 <strong>and</strong> nodeId 2 , as argument; it retur<strong>ns</strong> the id ofthe neighbor node th<strong>at</strong> nodeId 1 uses to reach nodeId 2 .<strong>The</strong> procedure is used by the st<strong>at</strong>ic route comput<strong>at</strong>ion procedure to query the computed routes <strong>and</strong> popul<strong>at</strong>e the routes<strong>at</strong> each of the nodes. It is also used by the multicast routing protocols to perform the appropri<strong>at</strong>e RPF check.Note th<strong>at</strong> this procedure overloads an i<strong>ns</strong>tproc-like of the same name. <strong>The</strong> procedure queries the appropri<strong>at</strong>e rtObjectentities if they exist (which they will if dynamic routing str<strong>at</strong>egies are used in the simul<strong>at</strong>ion); otherwise, the procedureinvokes the i<strong>ns</strong>tproc-like to obtain the relevant inform<strong>at</strong>ion.class rtObject is used in simul<strong>at</strong>io<strong>ns</strong> th<strong>at</strong> use dynamic routing. Each node has a rtObject associ<strong>at</strong>ed with it, th<strong>at</strong> actsas a co-ordin<strong>at</strong>or for the different routing protocols th<strong>at</strong> oper<strong>at</strong>e <strong>at</strong> a node. At any node, the rtObject <strong>at</strong> th<strong>at</strong> node tracks eachof the protocols oper<strong>at</strong>ing <strong>at</strong> th<strong>at</strong> node; it computes <strong>and</strong> i<strong>ns</strong>talls the nest route to each destin<strong>at</strong>ion available via each of theprotocols. In the event th<strong>at</strong> the routing tables change, or the topology changes, the rtObject will alert the protocols to take theappropri<strong>at</strong>e action.<strong>The</strong> class defines the procedure init-all{}; this procedure takes a list of nodes as arguments, <strong>and</strong> cre<strong>at</strong>es a rtObject <strong>at</strong>each of the nodes in its argument list. It subsequently invokes its compute-routes.<strong>The</strong> assumption is th<strong>at</strong> the co<strong>ns</strong>tructor for each of the new objects will i<strong>ns</strong>tanti<strong>at</strong>e the “Direct” route protocol <strong>at</strong> eachof these nodes. This route protocol is respo<strong>ns</strong>ible for computing the routes to immedi<strong>at</strong>ely adjacent neighbors. Whencompute-routes{} is run by the init-all{} procedure, these direct routes are i<strong>ns</strong>talled in the node by the appropri<strong>at</strong>eroute object.<strong>The</strong> other i<strong>ns</strong>tance procedures in this class are:• init{} <strong>The</strong> co<strong>ns</strong>tructor sets up pointers from itself to the node, in its i<strong>ns</strong>tance variable node_, <strong>and</strong> from the node toitself, through the Node i<strong>ns</strong>tance procedure init-routing{} <strong>and</strong> the Node i<strong>ns</strong>tance variable rtObject_. It theninitializes an array of nextHop_, rtpref_, metric_, rtVia_. <strong>The</strong> index of each of these arrays is the h<strong>and</strong>le ofthe destin<strong>at</strong>ion node.<strong>The</strong> nextHop_ contai<strong>ns</strong> the link th<strong>at</strong> will be used to reach the particular destin<strong>at</strong>ion; rtpref_ <strong>and</strong> metric_ are thepreference <strong>and</strong> metric for the route i<strong>ns</strong>talled in the node; rtVia_ is the name of the agent whose route is i<strong>ns</strong>talled inthe node.<strong>The</strong> co<strong>ns</strong>tructor also cre<strong>at</strong>es the i<strong>ns</strong>tance of the Direct route protocol, <strong>and</strong> invokes compute-routes{} for th<strong>at</strong>protocol.• add-proto{} cre<strong>at</strong>es an i<strong>ns</strong>tance of the protocol, stores a reference to it in its array of protocols, rtProtos_. <strong>The</strong>index of the array is the name of the protocol. It also <strong>at</strong>taches the protocol object to the node, <strong>and</strong> retur<strong>ns</strong> the h<strong>and</strong>le ofthe protocol object.254


• lookup{} takes a destin<strong>at</strong>ion node h<strong>and</strong>le, <strong>and</strong> retur<strong>ns</strong> the id of the neighbor node th<strong>at</strong> is used to reach the destin<strong>at</strong>ion.If multiple p<strong>at</strong>hs are in use, then it retur<strong>ns</strong> a list of the neighbor nodes th<strong>at</strong> will be used.If the node does not have a route to the destin<strong>at</strong>ion, the procedure will return -1.• compute-routes{} is the core procedure in this class. It first checks to see if any of the routing protocols <strong>at</strong> thenode have computed any new routes. If they have, it will determine the best route to each destin<strong>at</strong>ion from amongall the protocols. If any routes have changed, the procedure will notify each of the protocols of the number of suchchanges, in case any of these protocols wants to send a fresh upd<strong>at</strong>e. Finally, it will also notify any multicast protocolth<strong>at</strong> new unicast route tables have been computed.<strong>The</strong> routine checks the protocol agent’s i<strong>ns</strong>tance variable, rtsChanged_ to see if any of the routes in th<strong>at</strong> protocolhave changed since the protocol was last examined. It then uses the protocol’s i<strong>ns</strong>tance variable arrays, nextHop_,rtpref_, <strong>and</strong> metric_ to compute its own arrays. <strong>The</strong> rtObject will i<strong>ns</strong>tall or modify any of the routes as thechanges are found.If any of the routes <strong>at</strong> the node have changed, the rtObject will invoke the protocol agent’s i<strong>ns</strong>tance procedures,send-upd<strong>at</strong>es{} with the number of changes as argument. It will then invoke the multicast route object, if itexists.<strong>The</strong> next set of routines are used to query the rtObject for various st<strong>at</strong>e inform<strong>at</strong>ion.• dump-routes{} takes a output file descriptor as argument, <strong>and</strong> writes out the routing table <strong>at</strong> th<strong>at</strong> node on th<strong>at</strong> filedescriptor.A typical dump output is:• rtProto?{} takes a route protocol as argument, <strong>and</strong> retur<strong>ns</strong> a h<strong>and</strong>le to the i<strong>ns</strong>tance of the protocol running <strong>at</strong> thenode.• nextHop?{} takes a destin<strong>at</strong>ion node h<strong>and</strong>le, <strong>and</strong> retur<strong>ns</strong> the link th<strong>at</strong> is used to reach th<strong>at</strong> destin<strong>at</strong>ion.• Similarly, rtpref?{} <strong>and</strong> metric?{} take a destin<strong>at</strong>ion node h<strong>and</strong>le as argument, <strong>and</strong> return the preference <strong>and</strong>metric of the route to the destin<strong>at</strong>ion i<strong>ns</strong>talled <strong>at</strong> the node.<strong>The</strong> class rtPeer is a container class used by the protocol agents. Each object stores the address of the peer agent, <strong>and</strong>the metric <strong>and</strong> preference for each route advertised by th<strong>at</strong> peer. A protocol agent will store one object per peer. <strong>The</strong> classmaintai<strong>ns</strong> the i<strong>ns</strong>tance variable addr_, <strong>and</strong> the i<strong>ns</strong>tance variable arrays, metric_ <strong>and</strong> rtpref_; the array indices are thedestin<strong>at</strong>ion node h<strong>and</strong>les.<strong>The</strong> class i<strong>ns</strong>tance procedures, metric{} <strong>and</strong> preference{}, take one destin<strong>at</strong>ion <strong>and</strong> value, <strong>and</strong> set the respective arrayvariable. <strong>The</strong> procedures, metric?{} <strong>and</strong> preference?{}, take a destin<strong>at</strong>ion <strong>and</strong> return the current value for th<strong>at</strong>destin<strong>at</strong>ion. <strong>The</strong> i<strong>ns</strong>tance procedure addr?{} retur<strong>ns</strong> the address of the peer agent.class Agent/rtProto This class is the base class from which all routing protocol agents are derived. Each protocolagent must define the procedureinit-all{} to initialize the complete protocol, <strong>and</strong> possibly i<strong>ns</strong>tance procedures init{},compute-routes{}, <strong>and</strong> send-upd<strong>at</strong>es{}. In addition, if the topology is dynamic, <strong>and</strong> the protocol supports routecomput<strong>at</strong>ion to react to changes in the topology, then the protocol should define the procedure compute-all{}, <strong>and</strong> possiblythe i<strong>ns</strong>tance procedure intf-changed{}. In this section, we will briefly describe the interface for the basic procedures.We will defer the description of compute-all{} <strong>and</strong> intf-changed{} to the section on network dynamics. We alsodefer the description of the details of each of the protocols to their separ<strong>at</strong>e section <strong>at</strong> the end of the chapter.255


— <strong>The</strong> procedure init-all{} is a global initializ<strong>at</strong>ion procedure for the class. It may be given a list of the nodes asan argument. This the list of nodes th<strong>at</strong> should run this routing protocol. However, centralized routing protocols suchas st<strong>at</strong>ic <strong>and</strong> session routing will ignore this argument; detailed dynamic routing protocols such as DV will use thisargument list to i<strong>ns</strong>tanti<strong>at</strong>e protocols agents <strong>at</strong> each of the nodes specified.Note th<strong>at</strong> derived classes in OTcl do not inherit the procedures defined in the base class. <strong>The</strong>refore, every derivedrouting protocol class must define its own procedures explicitly.— <strong>The</strong> i<strong>ns</strong>tance procedure init{} is the co<strong>ns</strong>tructor for protocol agents th<strong>at</strong> are cre<strong>at</strong>ed. <strong>The</strong> base class co<strong>ns</strong>tructorinitializes the default preference for objects in this class, identifies the interfaces incident on the node <strong>and</strong> their currentst<strong>at</strong>us. <strong>The</strong> interfaces are indexed by the neighbor h<strong>and</strong>le <strong>and</strong> stored in the i<strong>ns</strong>tance variable array, ifs_; thecorresponding st<strong>at</strong>us i<strong>ns</strong>tance variable array is ifst<strong>at</strong>_.Centralized routing protocols such as st<strong>at</strong>ic <strong>and</strong> session routing do not cre<strong>at</strong>e separ<strong>at</strong>e agents per node, <strong>and</strong> therefore donot access any of these i<strong>ns</strong>tance procedures.— <strong>The</strong> i<strong>ns</strong>tance procedure compute-routes{} computes the actual routes for the protocol. <strong>The</strong> comput<strong>at</strong>ion is basedon the routes learned by the protocol, <strong>and</strong> varies from protocol to protocol.This routine is invoked by the rtObject whenever the topology changes. It is also invoked when the node receives anupd<strong>at</strong>e for the protocol.If the routine computes new routes, rtObject::compute-routes{} needs to be invoked to recompute <strong>and</strong> possiblyi<strong>ns</strong>tall new routes <strong>at</strong> the node. <strong>The</strong> actual invoking of the rtObject is done by the procedure th<strong>at</strong> invoked this routinein the first place.— <strong>The</strong> i<strong>ns</strong>tance procedure send-upd<strong>at</strong>es{} is invoked by the rtObject whenever the node routing tables have changed,<strong>and</strong> fresh upd<strong>at</strong>es have to be sent to all peers. <strong>The</strong> rtObject passes as argument the number of changes th<strong>at</strong> were done.This procedure may also be invoked when there are no changes to the routes, but the topology incident on the nodechanges st<strong>at</strong>e. <strong>The</strong> number of changes is used to determine the list of peers to which a route upd<strong>at</strong>e must be sent.Other procedures rel<strong>at</strong>e to responding to topology changes <strong>and</strong> are described l<strong>at</strong>er (Section 29.4.2).Other Exte<strong>ns</strong>io<strong>ns</strong> to the Simul<strong>at</strong>or, Node, Link, <strong>and</strong> Classifier— We have discussed the methods rtproto{} <strong>and</strong> cost{} in the class Simul<strong>at</strong>or earlier (Section 29.1). <strong>The</strong> one othermethod used internally is get-routelogic{}; this procedure retur<strong>ns</strong> the i<strong>ns</strong>tance of routelogic in the simul<strong>at</strong>ion.<strong>The</strong> method is used by the class Simul<strong>at</strong>or, <strong>and</strong> unicast <strong>and</strong> multicast routing.— <strong>The</strong> class Node contai<strong>ns</strong> these additional i<strong>ns</strong>tance procedures to support dynamic unicast routing: init-routing{},add-routes{}, delete-routes{}, <strong>and</strong> rtObject?{}.<strong>The</strong> i<strong>ns</strong>tance procedure init-routing{} is invoked by the rtObject <strong>at</strong> the node. It stores a pointer to the rtObject,in its i<strong>ns</strong>tance variable rtObject_, for l<strong>at</strong>er manipul<strong>at</strong>ion or retrieval. It also checks its class variable to see if it shoulduse multiP<strong>at</strong>h routing, <strong>and</strong> sets up an i<strong>ns</strong>tance variable to th<strong>at</strong> effect. If multiP<strong>at</strong>h routing could be used, the i<strong>ns</strong>tancevariable array routes_ stores a count of the number of p<strong>at</strong>hs i<strong>ns</strong>talled for each destin<strong>at</strong>ion. This is the only array inunicast routing th<strong>at</strong> is indexed by the node id, r<strong>at</strong>her than the node h<strong>and</strong>le.<strong>The</strong> i<strong>ns</strong>tance procedure rtObject?{} retur<strong>ns</strong> the rtObject h<strong>and</strong>le for th<strong>at</strong> node.<strong>The</strong> i<strong>ns</strong>tance procedure add-routes{} takes a node id, <strong>and</strong> a list of links. It will add the list of links as the routesto reach the destin<strong>at</strong>ion identified by the node id. <strong>The</strong> realiz<strong>at</strong>ion of multiP<strong>at</strong>h routing is done by using a separ<strong>at</strong>eClassifier/multiP<strong>at</strong>h. For any given destin<strong>at</strong>ion id d, if this node has multiple p<strong>at</strong>hs to d, then the main classifier pointsto this multip<strong>at</strong>h classifier i<strong>ns</strong>tead of the link to reach the destin<strong>at</strong>ion. Each of the multiple p<strong>at</strong>hs identified by theinterfaces being used is i<strong>ns</strong>talled in the multip<strong>at</strong>h classifier. <strong>The</strong> multip<strong>at</strong>h classifier will use each of the links i<strong>ns</strong>talledin it for succeeding packets forwarded to it.256


<strong>The</strong> i<strong>ns</strong>tance procedure delete-routes{} takes a node id, a list of interfaces, <strong>and</strong> a nullAgent. It removes each ofthe interfaces in the list from the i<strong>ns</strong>talled list of interfaces. If the entry did not previously use a multip<strong>at</strong>h classifier,then it must have had only one route, <strong>and</strong> the route entry is set to point to the nullAgent specified.Q: WHY DOES IT NOT POINT TO NULLAGENT IF THE ENTRIES IN THE MPATHCLASSIFIER GOES TOZERO?— <strong>The</strong> main exte<strong>ns</strong>ion to the class Link for unicast routing is to support the notion of link costs. <strong>The</strong> i<strong>ns</strong>tance variablecost_ contai<strong>ns</strong> the cost of the unidirectional link. <strong>The</strong> i<strong>ns</strong>tance procedures cost{} <strong>and</strong> cost?{} set <strong>and</strong> get the coston the link.Note th<strong>at</strong> cost{} takes the cost as argument. It is preferable to use the simul<strong>at</strong>or method to set the cost variable,similar to the simul<strong>at</strong>or i<strong>ns</strong>tance procedures to set the queue or delay on a link.— <strong>The</strong> class Classifier contai<strong>ns</strong> three new procedures, two of which overloads an existing i<strong>ns</strong>tproc-like, <strong>and</strong> theother two provide new functionality.<strong>The</strong> i<strong>ns</strong>tance procedure i<strong>ns</strong>tall{} overloads the existing i<strong>ns</strong>tproc-like of the same name. <strong>The</strong> procedure stores theentry being i<strong>ns</strong>talled in the i<strong>ns</strong>tance variable array, elements_, <strong>and</strong> then invokes the i<strong>ns</strong>tproc-like.<strong>The</strong> i<strong>ns</strong>tance procedure i<strong>ns</strong>tallNext{} also overloads the existing i<strong>ns</strong>tproc-like of the same name. This i<strong>ns</strong>tproclikesimply i<strong>ns</strong>talls the entry into the next available slot.<strong>The</strong> i<strong>ns</strong>tance procedure adjacents{} retur<strong>ns</strong> a list of 〈key, value〉 pairs of all elements i<strong>ns</strong>talled in the classifier.29.4.2 Interface to Network Dynamics <strong>and</strong> MulticastThis section describes the methods applied in unicast routing to respond to changes in the topology. <strong>The</strong> complete sequenceof actio<strong>ns</strong> th<strong>at</strong> cause the changes in the topology, <strong>and</strong> fire the appropri<strong>at</strong>e actio<strong>ns</strong> is described in a different section. <strong>The</strong>respo<strong>ns</strong>e to topology changes falls into two c<strong>at</strong>egories: actio<strong>ns</strong> taken by individual agents <strong>at</strong> each of the nodes, <strong>and</strong> actio<strong>ns</strong> tobe taken globally for the entire protocol.Detailed routing protocols such as the DV implement<strong>at</strong>ion require actio<strong>ns</strong> to be performed by individual protocol agents <strong>at</strong>the affected nodes. Centralized routing protocols such as st<strong>at</strong>ic <strong>and</strong> session routing fall into the l<strong>at</strong>ter c<strong>at</strong>egory exclusively.Detailed routing protocols could use such techniques to g<strong>at</strong>her st<strong>at</strong>istics rel<strong>at</strong>ed to the oper<strong>at</strong>ion of the routing protocol;however, no such code is currently implemented in <strong>ns</strong>.Actio<strong>ns</strong> <strong>at</strong> the individual nodes Following any change in the topology, the network dynamics models will first invokertObject::intf-changed{} <strong>at</strong> each of the affected nodes. For each of the unicast routing protocols oper<strong>at</strong>ing <strong>at</strong> th<strong>at</strong>node, rtObject::intf-changed{} will invoke each individual protocol’s i<strong>ns</strong>tance procedure, intf-changed{},followed by th<strong>at</strong> protocol’s compute-routes{}.After each protocol has computed its individual routes rtObject::intf-changed{} invokes compute-routes{}to possibly i<strong>ns</strong>tall new routes. If new routes were i<strong>ns</strong>talled in the node, rtObject::compute-routes{} will invokesend-upd<strong>at</strong>es{} for each of the protocols oper<strong>at</strong>ing <strong>at</strong> the node. <strong>The</strong> procedure will also flag the multicast route object ofthe route changes <strong>at</strong> the node, indic<strong>at</strong>ing the number of changes th<strong>at</strong> have been executed. rtObject::flag-multicast{}will, in turn, notify the multicast route object to take appropri<strong>at</strong>e action.<strong>The</strong> one exception to the interface between unicast <strong>and</strong> multicast routing is the interaction between dynamic de<strong>ns</strong>e modemulticast <strong>and</strong> detailed unicast routing. This dynamicDM implement<strong>at</strong>ion in <strong>ns</strong> assumes neighbor nodes will send an implicitupd<strong>at</strong>e whenever their routes change, without actually sending the upd<strong>at</strong>e. It then uses this implicit inform<strong>at</strong>ion to computeappropri<strong>at</strong>e parent-child rel<strong>at</strong>io<strong>ns</strong>hips for the multicast spanning trees. <strong>The</strong>refore, detailed unicast routing will invokertObject_ flag-multicast 1 whenever it receives a route upd<strong>at</strong>e as well, even if th<strong>at</strong> upd<strong>at</strong>e does not result in anychange in its own routing tables.257


Global Actio<strong>ns</strong> Once the detailed actio<strong>ns</strong> <strong>at</strong> each of the affected nodes is completed, the network dynamics models willnotify the RouteLogic i<strong>ns</strong>tance (RouteLogic::notify{}) of changes to topology. This procedure invokes the procedurecompute-all{} for each of the protocols th<strong>at</strong> were ever i<strong>ns</strong>talled <strong>at</strong> any of the nodes. Centralized routing protocols suchas session routing use this signal to recompute the routes to the topology. Finally, the RouteLogic::notify{} procedurenotifies any i<strong>ns</strong>tances of centralized multicast th<strong>at</strong> are oper<strong>at</strong>ing <strong>at</strong> the node.29.5 Protocol InternalsIn this section, we describe any leftover details of each of the routing protocol agents. Note th<strong>at</strong> this is the only place wherewe describe the internal route protocol agent, “Direct” routing.Direct Routing This protocol tracks the st<strong>at</strong>e of the incident links, <strong>and</strong> maintai<strong>ns</strong> routes to immedi<strong>at</strong>ely adjacent neighborsonly. As with the other protocols, it maintai<strong>ns</strong> i<strong>ns</strong>tance variable arrays of nextHop_, rtpref_, <strong>and</strong> metric_, indexed bythe h<strong>and</strong>le of each of the possible destin<strong>at</strong>io<strong>ns</strong> in the topology.<strong>The</strong> i<strong>ns</strong>tance procedure compute-routes{} computes routes based on the current st<strong>at</strong>e of the link, <strong>and</strong> the previouslyknown st<strong>at</strong>e of the incident links.No other procedures or i<strong>ns</strong>tance procedures are defined for this protocol.St<strong>at</strong>ic Routing <strong>The</strong> procedure compute-routes{} in the class RouteLogic first cre<strong>at</strong>es the adjacency m<strong>at</strong>rix, <strong>and</strong>then invokes the C++ method, compute_routes() of the shadow object. Finally, the procedure retrieves the result of theroute comput<strong>at</strong>ion, <strong>and</strong> i<strong>ns</strong>erts the appropri<strong>at</strong>e routes <strong>at</strong> each of the nodes in the topology.<strong>The</strong> class only defines the procedure init-all{} th<strong>at</strong> invokes compute-routes{}.Session Routing <strong>The</strong> class defines the procedure init-all{} to compute the routes <strong>at</strong> the start of the simul<strong>at</strong>ion. It alsodefines the procedure compute-all{} to compute the routes when the topology changes. Each of these procedures directlyinvokes compute-routes{}.DV Routing In a dynamic routing str<strong>at</strong>egy, nodes send <strong>and</strong> receive messages, <strong>and</strong> compute the routes in the topology basedon the messages exchanged. <strong>The</strong> procedure init-all{} takes a list of nodes as the argument; the default is the list ofnodes in the topology. At each of the nodes in the argument, the procedure starts the class rtObject <strong>and</strong> a classAgent/rtProto/DV agents. It then determines the DV peers for each of the newly cre<strong>at</strong>ed DV agents, <strong>and</strong> cre<strong>at</strong>es therelevant rtPeer objects.<strong>The</strong> co<strong>ns</strong>tructor for the DV agent initializes a number of i<strong>ns</strong>tance variables; each agent stores an array, indexed by thedestin<strong>at</strong>ion node h<strong>and</strong>le, of the preference <strong>and</strong> metric, the interface (or link) to the next hop, <strong>and</strong> the remote peer incident onthe interface, for the best route to each destin<strong>at</strong>ion computed by the agent. <strong>The</strong> agent cre<strong>at</strong>es these i<strong>ns</strong>tance variables, <strong>and</strong>then schedules sending its first upd<strong>at</strong>e within the first 0.5 seconds of simul<strong>at</strong>ion start.Each agent stores the list of its peers indexed by the h<strong>and</strong>le of the peer node. Each peer is a separ<strong>at</strong>e peer structure th<strong>at</strong> holdsthe address of the peer agent, the metric <strong>and</strong> preference of the route to each destin<strong>at</strong>ion advertised by th<strong>at</strong> peer. We discuss thertPeer structure l<strong>at</strong>er when discuss the route architecture. <strong>The</strong> peer structures are initialized by the procedure add-peer{}invoked by init-all{}.258


<strong>The</strong> routine send-periodic-upd<strong>at</strong>e{} invokes send-upd<strong>at</strong>es{} to send the actual upd<strong>at</strong>es. It then reschedulessending the next periodic upd<strong>at</strong>e after advertInterval jittered slightly to avoid possible synchroniz<strong>at</strong>ion effects.send-upd<strong>at</strong>es{} will send upd<strong>at</strong>es to a select set of peers. If any of the routes <strong>at</strong> th<strong>at</strong> node have changed, or for periodicupd<strong>at</strong>es, the procedure will send upd<strong>at</strong>es to all peers. Otherwise, if some incident links have just recovered, the procedurewill send upd<strong>at</strong>es to the adjacent peers on those incident links only.send-upd<strong>at</strong>es{} uses the procedure send-to-peer{} to send the actual upd<strong>at</strong>es. This procedure packages the upd<strong>at</strong>e,taking the split-horizon <strong>and</strong> poison reverse mechanisms into account. It invokes the i<strong>ns</strong>tproc-like, send-upd<strong>at</strong>e{} (Notethe singular case) to send the actual upd<strong>at</strong>e. <strong>The</strong> actual route upd<strong>at</strong>e is stored in the class variable msg_ indexed by a nondecreasinginteger as index. <strong>The</strong> i<strong>ns</strong>tproc-like only sends the index to msg_ to the remote peer. This elimin<strong>at</strong>es the need toconvert from OTcl strings to altern<strong>at</strong>e form<strong>at</strong>s <strong>and</strong> back.When a peer receives a route upd<strong>at</strong>e it first checks to determine if the upd<strong>at</strong>e from differs from the previous ones. <strong>The</strong> agentwill compute new routes if the upd<strong>at</strong>e contai<strong>ns</strong> new inform<strong>at</strong>ion.29.6 Unicast routing objectsRoutelogic <strong>and</strong> rtObject are two objects th<strong>at</strong> are significant to unicast routing in <strong>ns</strong>. Routelogic, essentially, represents therouting table th<strong>at</strong> is cre<strong>at</strong>ed <strong>and</strong> maintained centrally for every unicast simul<strong>at</strong>ion. rtObject is the object th<strong>at</strong> every nodetaking part in dynamic unicast routing, has an i<strong>ns</strong>tance of. Note th<strong>at</strong> nodes will not have an i<strong>ns</strong>tance of this object if Sessionrouting is done as a detailed routing protocol is not being simul<strong>at</strong>ed in this case. <strong>The</strong> methods for RouteLogic <strong>and</strong> rtObjectare described in the next section.29.7 Comm<strong>and</strong>s <strong>at</strong> a glanceFollowing is a list of unicast routing rel<strong>at</strong>ed comm<strong>and</strong>s used in simul<strong>at</strong>ion scripts:$<strong>ns</strong>_ rtproto where defines the type of routing protocol to be used, like St<strong>at</strong>ic, <strong>Manual</strong>, Session , DV etc. args may definethe list of nodes on which the protocol is to be run. <strong>The</strong> node list defaults to all nodes in the topology.Internal methods:$<strong>ns</strong>_ compute-routesThis comm<strong>and</strong> computes next_hop inform<strong>at</strong>ion for all nodes in the topology using the topology connectivity. Thisnext_hop info is then used to popul<strong>at</strong>e the node classifiers or the routing tables. compute-routes calls compute-fl<strong>at</strong>-routesor compute-hier-routes depending on the type of addressing being used for the simul<strong>at</strong>ion.$<strong>ns</strong>_ get-routelogicThis retur<strong>ns</strong> a h<strong>and</strong>le to the RouteLogic object (the routing table), if one has been cre<strong>at</strong>ed. Otherwise a new routing tableobject is cre<strong>at</strong>ed.$<strong>ns</strong>_ dump-routelogic-nh259


This dumps next hop inform<strong>at</strong>ion in the routing table.$<strong>ns</strong>_ dump-routelogic-distanceThis dumps the distance inform<strong>at</strong>ion in the routing table.$node add-route This is a method used to add routing entries (nexthop inform<strong>at</strong>ion) in the node’s routing table. <strong>The</strong> nexthop to fromthis node is the object <strong>and</strong> this info is added to the node’s classifier.$routelogic lookup Retur<strong>ns</strong> the id of the node th<strong>at</strong> is the next hop from the node with id srcid to the node with id destid.$routelogic dump Dump the routing tables of all nodes whose id is less than nodeid. Node ids are typically assigned to nodes in ascendingfashion starting from 0 by their order of cre<strong>at</strong>ion.rtobject dump-routes Dump the routing table to the output channel specified by fileID. fileID must be a file h<strong>and</strong>le returned by the Tcl opencomm<strong>and</strong> <strong>and</strong> it must have been opened for writing.$rtobject rtProto?Retur<strong>ns</strong> a h<strong>and</strong>le to the routing protocol agent specified by proto if it exists <strong>at</strong> th<strong>at</strong> node. Retur<strong>ns</strong> an empty string otherwise.$rtobject nextHop?Retur<strong>ns</strong> the id of the node th<strong>at</strong> is the next hop to the destin<strong>at</strong>ion specified by the node id, .$rtobject rtpref?destIDRetur<strong>ns</strong> the preference for the route to destin<strong>at</strong>ion node given by destid.$rtobject metric?destIDRetur<strong>ns</strong> metric for the route to destid.260


Chapter 30Multicast RoutingThis section describes the usage <strong>and</strong> the internals of multicast routing implement<strong>at</strong>ion in <strong>ns</strong>. We first describe the userinterface to enable multicast routing (Section 30.1), specify the multicast routing protocol to be used <strong>and</strong> the various methods<strong>and</strong> configur<strong>at</strong>ion parameters specific to the protocols currently supported in <strong>ns</strong>. We then describe in detail the internals <strong>and</strong>the architecture of the multicast routing implement<strong>at</strong>ion in <strong>ns</strong> (Section 30.2).<strong>The</strong> procedures <strong>and</strong> functio<strong>ns</strong> described in this chapter can be found in various files in the directories ~<strong>ns</strong>/tcl/mcast, ~<strong>ns</strong>/tcl/ctrmcast;additional support routines are in ~<strong>ns</strong>/mcast_ctrl.{cc,h}, ~<strong>ns</strong>/tcl/lib/<strong>ns</strong>-lib.tcl, <strong>and</strong> ~<strong>ns</strong>/tcl/lib/<strong>ns</strong>-node.tcl.30.1 Multicast APIMulticast forwarding requires enhancements to the nodes <strong>and</strong> links in the topology. <strong>The</strong>refore, the user must specify multicastrequirements to the Simul<strong>at</strong>or class before cre<strong>at</strong>ing the topology. This is done in one of two ways:orset <strong>ns</strong> [new Simul<strong>at</strong>or -multicast on]set <strong>ns</strong> [new Simul<strong>at</strong>or]$<strong>ns</strong> multicastWhen multicast exte<strong>ns</strong>io<strong>ns</strong> are thus enabled, nodes will be cre<strong>at</strong>ed with additional classifiers <strong>and</strong> replic<strong>at</strong>ors for multicastforwarding, <strong>and</strong> links will contain elements to assign incoming interface labels to all packets entering a node.A multicast routing str<strong>at</strong>egy is the mechanism by which the multicast distribution tree is computed in the simul<strong>at</strong>ion. <strong>ns</strong>supports three multiast route comput<strong>at</strong>ion str<strong>at</strong>egies: centralised, de<strong>ns</strong>e mode(DM) or shared tree mode(ST).<strong>The</strong> method mrtproto{} in the Class Simul<strong>at</strong>or specifies either the route comput<strong>at</strong>ion str<strong>at</strong>egy, for centralised multicastrouting, or the specific detailed multicast routing protocol th<strong>at</strong> should be used.<strong>The</strong> following are examples of valid invoc<strong>at</strong>io<strong>ns</strong> of multicast routing in <strong>ns</strong>:set cmc [$<strong>ns</strong> mrtproto CtrMcast]$<strong>ns</strong> mrtproto DM;# specify centralized multicast for all nodes;# cmc is the h<strong>and</strong>le for multicast protocol object;# specify de<strong>ns</strong>e mode multicast for all nodes261


$<strong>ns</strong> mrtproto ST;# specify shared tree mode to run on all nodesNotice in the above examples th<strong>at</strong> CtrMcast retur<strong>ns</strong> a h<strong>and</strong>le th<strong>at</strong> can be used for additional configur<strong>at</strong>ion of centralisedmulticast routing. <strong>The</strong> other routing protocols will return a null string. All the nodes in the topology will run i<strong>ns</strong>tances of thesame protocol.Multiple multicast routing protocols can be run <strong>at</strong> a node, but in this case the user must specify which protocol ow<strong>ns</strong> whichincoming interface. For this finer control mrtproto-iifs{} is used.New/unused multicast address are alloc<strong>at</strong>ed using the procedure allocaddr{}.<strong>The</strong> agents use the i<strong>ns</strong>tance procedures join-group{} <strong>and</strong> leave-group{}, in the class Node to join <strong>and</strong> leave multicastgroups. <strong>The</strong>se procedures take two m<strong>and</strong><strong>at</strong>ory arguments. <strong>The</strong> first argument identifies the corresponding agent <strong>and</strong> secondargument specifies the group address.An example of a rel<strong>at</strong>ively simple multicast configur<strong>at</strong>ion is:set <strong>ns</strong> [new Simul<strong>at</strong>or -multicast on]set group [Node allocaddr]set node0 [$<strong>ns</strong> node]set node1 [$<strong>ns</strong> node]$<strong>ns</strong> duplex-link $node0 $node1 1.5Mb 10ms DropTail;# enable multicast routing;# alloc<strong>at</strong>e a multicast address;# cre<strong>at</strong>e multicast capable nodesset mproto DM;# configure multicast protocolset mrth<strong>and</strong>le [$<strong>ns</strong> mrtproto $mproto] ;# all nodes will contain multicast protocol agentsset udp [new Agent/UDP] ;# cre<strong>at</strong>e a source agent <strong>at</strong> node 0$<strong>ns</strong> <strong>at</strong>tach-agent $node0 $udpset src [new Applic<strong>at</strong>ion/Traffic/CBR]$src <strong>at</strong>tach-agent $udp$udp set dst_addr_ $group$udp set dst_port_ 0set rcvr [new Agent/LossMonitor] ;# cre<strong>at</strong>e a receiver agent <strong>at</strong> node 1$<strong>ns</strong> <strong>at</strong>tach-agent $node1 $rcvr$<strong>ns</strong> <strong>at</strong> 0.3 "$node1 join-group $rcvr $group" ;# join the group <strong>at</strong> simul<strong>at</strong>ion time 0.3 (sec)30.1.1 Multicast Behavior Monitor Configur<strong>at</strong>ion<strong>ns</strong> supports a multicast monitor module th<strong>at</strong> can trace user-defined packet activity. <strong>The</strong> module counts the number of packetsin tra<strong>ns</strong>it periodically <strong>and</strong> prints the results to specified files. <strong>at</strong>tach{} enables a monitor module to print output to a file.trace-topo{} i<strong>ns</strong>ets monitor modules into all links. filter{} allows accounting on specified packet header, field inthe header), <strong>and</strong> value for the field). Calling filter{} repe<strong>at</strong>edly will result in an AND effect on the filtering condition.print-trace{} notifies the monitor module to begin dumping d<strong>at</strong>a. ptype() is a global arrary th<strong>at</strong> takes a packet typename (as seen in trace-all{} output) <strong>and</strong> maps it into the corresponding value. A simple configur<strong>at</strong>ion to filter cbr packetson a particular group is:set mcastmonitor [new McastMonitor]set chan [open cbr.tr w]$mmonitor <strong>at</strong>tach $chan1$mcastmonitor set period_ 0.02;# open trace file;# <strong>at</strong>tach trace file to McastMoniotor object;# default 0.03 (sec)262


$mmonitor trace-topo;# trace entire topology$mmonitor filter Common ptype_ $ptype(cbr) ;# filter on ptype_ in Common header$mmonitor filter IP dst_ $group;# AND filter on dst_ address in IP header$mmonitor print-trace;# begin dumping periodic traces to specified files<strong>The</strong> following sample output illustr<strong>at</strong>es the output file form<strong>at</strong> (time, count):0.16 00.17999999999999999 00.19999999999999998 00.21999999999999997 60.23999999999999996 110.25999999999999995 120.27999999999999997 1230.1.2 Protocol Specific configur<strong>at</strong>ionIn this section, we briefly illustr<strong>at</strong>e the protocol specific configur<strong>at</strong>ion mechanisms for all the protocols implemented in <strong>ns</strong>.Centralized Multicast <strong>The</strong> centralized multicast is a sparse mode implement<strong>at</strong>ion of multicast similar to PIM-SM [9]. ARendezvous Point (RP) rooted shared tree is built for a multicast group. <strong>The</strong> actual sending of prune, join messages etc. toset up st<strong>at</strong>e <strong>at</strong> the nodes is not simul<strong>at</strong>ed. A centralized comput<strong>at</strong>ion agent is used to compute the forwarding trees <strong>and</strong> setup multicast forwarding st<strong>at</strong>e, 〈S, G〉 <strong>at</strong> the relevant nodes as new receivers join a group. D<strong>at</strong>a packets from the senders to agroup are unicast to the RP. Note th<strong>at</strong> d<strong>at</strong>a packets from the senders are unicast to the RP even if there are no receivers for thegroup.<strong>The</strong> method of enabling centralised multicast routing in a simul<strong>at</strong>ion is:set mproto CtrMcastset mrth<strong>and</strong>le [$<strong>ns</strong> mrtproto $mproto];# set multicast protocol<strong>The</strong> comm<strong>and</strong> procedure mrtproto{} retur<strong>ns</strong> a h<strong>and</strong>le to the multicast protocol object. This h<strong>and</strong>le can be used to controlthe RP <strong>and</strong> the boot-strap-router (BSR), switch tree-types for a particular group, from shared trees to source specific trees,<strong>and</strong> recompute multicast routes.$mrth<strong>and</strong>le set_c_rp $node0 $node1$mrth<strong>and</strong>le set_c_bsr $node0:0 $node1:1;# set the RPs;# set the BSR, specified as list of node:priority$mrth<strong>and</strong>le get_c_rp $node0 $group ;# get the current RP ???$mrth<strong>and</strong>le get_c_bsr $node0;# get the current BSR$mrth<strong>and</strong>le switch-treetype $group$mrth<strong>and</strong>le compute-mroutes;# to source specific or shared tree;# recompute routes. usually invoked autom<strong>at</strong>ically as neededNote th<strong>at</strong> whenever network dynamics occur or unicast routing changes, compute-mroutes{} could be invoked to recomputethe multicast routes. <strong>The</strong> i<strong>ns</strong>tantaneous re-comput<strong>at</strong>ion fe<strong>at</strong>ure of centralised algorithms may result in causalityviol<strong>at</strong>io<strong>ns</strong> during the tra<strong>ns</strong>ient periods.263


De<strong>ns</strong>e Mode <strong>The</strong> De<strong>ns</strong>e Mode protocol (DM.tcl) is an implement<strong>at</strong>ion of a de<strong>ns</strong>e–mode–like protocol. Depending onthe value of DM class variable CacheMissMode it can run in one of two modes. If CacheMissMode is set to pimdm(default), PIM-DM-like forwarding rules will be used. Altern<strong>at</strong>ively, CacheMissMode can be set to dvmrp (loosely basedon DVMRP [30]). <strong>The</strong> main difference between these two modes is th<strong>at</strong> DVMRP maintai<strong>ns</strong> parent–child rel<strong>at</strong>io<strong>ns</strong>hips amongnodes to reduce the number of links over which d<strong>at</strong>a packets are broadcast. <strong>The</strong> implement<strong>at</strong>ion works on point-to-point linksas well as LANs <strong>and</strong> adapts to the network dynamics (links going up <strong>and</strong> down).Any node th<strong>at</strong> receives d<strong>at</strong>a for a particular group for which it has no dow<strong>ns</strong>tream receivers, send a prune upstream. A prunemessage causes the upstream node to initi<strong>at</strong>e prune st<strong>at</strong>e <strong>at</strong> th<strong>at</strong> node. <strong>The</strong> prune st<strong>at</strong>e prevents th<strong>at</strong> node from sending d<strong>at</strong>afor th<strong>at</strong> group dow<strong>ns</strong>tream to the node th<strong>at</strong> sent the original prune message while the st<strong>at</strong>e is active. <strong>The</strong> time dur<strong>at</strong>ion forwhich a prune st<strong>at</strong>e is active is configured through the DM class variable, PruneTimeout. A typical DM configur<strong>at</strong>ion isshown below:DM set PruneTimeout 0.3DM set CacheMissMode dvmrp$<strong>ns</strong> mrtproto DM;# default 0.5 (sec);# default pimdmShared Tree Mode Simplified sparse mode ST.tcl is a version of a shared–tree multicast protocol. Class variable arrayRP_ indexed by group determines which node is the RP for a particular group. For example:ST set RP_($group) $node0$<strong>ns</strong> mrtproto STAt the time the multicast simul<strong>at</strong>ion is started, the protocol will cre<strong>at</strong>e <strong>and</strong> i<strong>ns</strong>tall encapsul<strong>at</strong>or objects <strong>at</strong> nodes th<strong>at</strong> havemulticast senders, decapsul<strong>at</strong>or objects <strong>at</strong> RPs <strong>and</strong> connect them. To join a group, a node sends a graft message towards theRP of the group. To leave a group, it sends a prune message. <strong>The</strong> protocol currently does not support dynamic changes <strong>and</strong>LANs.Bi-directional Shared Tree Mode BST.tcl is an experimental version of a bi–directional shared tree protocol. As i<strong>ns</strong>hared tree mode, RPs must be configured manually by using the class array RP_. <strong>The</strong> protocol currently does not supportdynamic changes <strong>and</strong> LANs.30.2 Internals of Multicast RoutingWe describe the internals in three parts: first the classes to implement <strong>and</strong> support multicast routing; second, the specificprotocol implement<strong>at</strong>ion details; <strong>and</strong> finally, provide a list of the variables th<strong>at</strong> are used in the implement<strong>at</strong>io<strong>ns</strong>.30.2.1 <strong>The</strong> classes<strong>The</strong> main classes in the implement<strong>at</strong>ion are the class mrtObject <strong>and</strong> the class McastProtocol. <strong>The</strong>re are alsoexte<strong>ns</strong>io<strong>ns</strong> to the base classes: Simul<strong>at</strong>or, Node, Classifier, etc. We describe these classes <strong>and</strong> exte<strong>ns</strong>io<strong>ns</strong> in this subsection.<strong>The</strong> specific protocol implement<strong>at</strong>io<strong>ns</strong> also use adjunct d<strong>at</strong>a structures for specific tasks, such as timer mechanisms by detailedde<strong>ns</strong>e mode, encapsul<strong>at</strong>ion/decapsul<strong>at</strong>ion agents for centralised multicast etc.; we defer the description of these objects to thesection on the description of the particular protocol itself.264


mrtObject class <strong>The</strong>re is one mrtObject (aka Arbiter) object per multicast capable node. This object supports the abilityfor a node to run multiple multicast routing protocols by maintaining an array of multicast protocols indexed by the incominginterface. Thus, if there are several multicast protocols <strong>at</strong> a node, each interface is owned by just one protocol. <strong>The</strong>refore,this object supports the ability for a node to run multiple multicast routing protocols. <strong>The</strong> node uses the arbiter to performprotocol actio<strong>ns</strong>, either to a specific protocol i<strong>ns</strong>tance active <strong>at</strong> th<strong>at</strong> node, or to all protocol i<strong>ns</strong>tances <strong>at</strong> th<strong>at</strong> node.addproto{i<strong>ns</strong>tance, [iiflist]}getType{protocol}all-mprotos{op, args}start{}stop{}notify{dummy}dump-mroutes{file-h<strong>and</strong>le, [grp], [src]}join-group{G, S}leave-group{G, S}upcall{code, s, g, iif}drop{rep, s, g, iif}adds the h<strong>and</strong>le for a protocol i<strong>ns</strong>tance to its array of protocols. <strong>The</strong> secondoptional argument is the incoming interface list controlled by the protocol.If this argument is an empty list or not specified, the protocol is assumed torun on all interfaces (just one protocol).retur<strong>ns</strong> the h<strong>and</strong>le to the protocol i<strong>ns</strong>tance active <strong>at</strong> th<strong>at</strong> node th<strong>at</strong> m<strong>at</strong>chesthe specified type (first <strong>and</strong> only argument). This function is often used toloc<strong>at</strong>e a protocol’s peer <strong>at</strong> another node. An empty string is returned if theprotocol of the given type could not be found.internal routine to execute “op” with “args” on all protocol i<strong>ns</strong>tances active<strong>at</strong> th<strong>at</strong> node.start/stop execution of all protocols.is called when a topology change occurs. <strong>The</strong> dummy argument is currentlynot used.dump multicast routes to specified file-h<strong>and</strong>le.signals all protocol i<strong>ns</strong>tances to join 〈S, G〉.signals all protocol i<strong>ns</strong>tances to leave 〈S, G〉.signalled by node on forwarding errors in classifier; this routine in tur<strong>ns</strong>ignals the protocol i<strong>ns</strong>tance th<strong>at</strong> ow<strong>ns</strong> the incoming interface (iif) byinvoking the appropri<strong>at</strong>e h<strong>and</strong>le function for th<strong>at</strong> particular code.Called on packet drop, possibly to prune an interface.In addition, the mrtObject class supports the concept of well known groups, i.e., those groups th<strong>at</strong> do not require explicitprotocol support. Two well known groups, ALL_ROUTERS <strong>and</strong> ALL_PIM_ROUTERS are predefined in <strong>ns</strong>.<strong>The</strong> class mrtObject defines two class procedures to set <strong>and</strong> get inform<strong>at</strong>ion about these well known groups.registerWellKnownGroups{name}getWellKnownGroup{name}assig<strong>ns</strong> name a well known group address.retur<strong>ns</strong> the address alloc<strong>at</strong>ed to well known group, name. If name is not registeredas a well known group, then it retur<strong>ns</strong> the address for ALL_ROUTERS.McastProtocol classfunctio<strong>ns</strong>:start{}, stop{}getSt<strong>at</strong>us{}getType{}upcall{code args}This is the base class for the implement<strong>at</strong>ion of all the multicast protocols. It contai<strong>ns</strong> basic multicastSet the st<strong>at</strong>us_ of execution of this protocol i<strong>ns</strong>tance.return the st<strong>at</strong>us of execution of this protocol i<strong>ns</strong>tance.return the type of protocol executed by this i<strong>ns</strong>tance.invoked when the node classifier signals an error, either due to a cache-miss or a wrong-iif forincoming packet. This routine invokes the protocol specific h<strong>and</strong>le, h<strong>and</strong>le-〈code〉{} withspecified args to h<strong>and</strong>le the signal.A few words about interfaces. Multicast implement<strong>at</strong>ion in <strong>ns</strong> assumes duplex links i.e. if there is a simplex link from node 1to node 2, there must be a reverse simplex link from node 2 to node 1. To be able to tell from which link a packet was received,multicast simul<strong>at</strong>or configures links with an interface labeller <strong>at</strong> the end of each link, which labels packets with a particular265


<strong>and</strong> unique label (id). Thus, “incoming interface” is referred to this label <strong>and</strong> is a number gre<strong>at</strong>er or equal to zero. Incominginterface value can be neg<strong>at</strong>ive (-1) for a special case when the packet was sent by a local to the given node agent.In contrast, an “outgoing interface” refers to an object h<strong>and</strong>ler, usually a head of a link which can be i<strong>ns</strong>talled <strong>at</strong> a replic<strong>at</strong>or.This destinction is important: incoming interface is a numeric label to a packet, while outgoing interface is a h<strong>and</strong>ler to anobject th<strong>at</strong> is able to receive packets, e.g. head of a link.30.2.2 Exte<strong>ns</strong>io<strong>ns</strong> to other classes in <strong>ns</strong>In the earlier chapter describing nodes in <strong>ns</strong> (Chapter 5), we described the internal structure of the node in <strong>ns</strong>. To briefly recapth<strong>at</strong> description, the node entry for a multicast node is the switch_. It looks <strong>at</strong> the highest bit to decide if the destin<strong>at</strong>ion isa multicast or unicast packet. Multicast packets are forwarded to a multicast classifier which maintai<strong>ns</strong> a list of replic<strong>at</strong>ors;there is one replic<strong>at</strong>or per 〈source, group〉 tuple. Replic<strong>at</strong>ors copy the incoming packet <strong>and</strong> forward to all outgoing interfaces.Class Node Node support for multicast is realized in two primary ways: it serves as a focal point for access to the multicastprotocols, in the areas of address alloc<strong>at</strong>ion, control <strong>and</strong> management, <strong>and</strong> group membership dynamics; <strong>and</strong> secondly, itprovides primitives to access <strong>and</strong> control interfaces on links incident on th<strong>at</strong> node.266


exp<strong>and</strong>addr{},allocaddr{} Class procedures for address management. exp<strong>and</strong>addr{} is now obsoleted.allocaddr{} alloc<strong>at</strong>es the next available multicast address.start-mcast{},stop-mcast{}notify-mcast{}getArbiter{}dump-routes{file-h<strong>and</strong>le}new-group{s g iif code}join-group{a g}leave-group{a g}add-mfc{s g iif oiflist}To start <strong>and</strong> stop multicast routing <strong>at</strong> th<strong>at</strong> node.notify-mcast{} signals the mrtObject <strong>at</strong> th<strong>at</strong> node to recompute multicastroutes followinga topology change or unicast route upd<strong>at</strong>e from a neighbour.retur<strong>ns</strong> a h<strong>and</strong>le to mrtObject oper<strong>at</strong>ing <strong>at</strong> th<strong>at</strong> node.to dump the multicast forwarding tables <strong>at</strong> th<strong>at</strong> node.When a multicast d<strong>at</strong>a packet is received, <strong>and</strong> the multicast classifier cannot find the slotcorresponding to th<strong>at</strong> d<strong>at</strong>a packet, it invokes Node <strong>ns</strong>tproc new-group{} to establishthe appropri<strong>at</strong>e entry. <strong>The</strong> code indic<strong>at</strong>es the reason for not finding the slot. Currentlythere are two possibilities, cache-miss <strong>and</strong> wrong-iif. This procedure notifies the arbiteri<strong>ns</strong>tance to establish the new group.An agent <strong>at</strong> a node th<strong>at</strong> joi<strong>ns</strong> a particular group invokes “node join-group ”. <strong>The</strong> node signals the mrtObject to join the particular group,<strong>and</strong> adds agent to its list of agents <strong>at</strong> th<strong>at</strong> group. It then adds agent to all replic<strong>at</strong>orsassoci<strong>at</strong>ed with group.Node i<strong>ns</strong>tproc leave-group reverses the process described earlier. It disablesthe outgoing interfaces to the receiver agents for all the replic<strong>at</strong>ors of the group, deletesthe receiver agents from the local Agents_ list; it then invokes the arbiter i<strong>ns</strong>tance’sleave-group{}.Node i<strong>ns</strong>tproc add-mfc adds a multicast forwarding cache entry for a particular〈source, group, iif〉. <strong>The</strong> mechanism is:• cre<strong>at</strong>e a new replic<strong>at</strong>or (if one does not already exist),• upd<strong>at</strong>e the replic<strong>at</strong>or_ i<strong>ns</strong>tance variable array <strong>at</strong> the node,• add all outgoing interfaces <strong>and</strong> local agents to the appropri<strong>at</strong>e replic<strong>at</strong>or,• invoke the multicast classifier’s add-rep{} to cre<strong>at</strong>e a slot for the replic<strong>at</strong>or in themulticast classifier.del-mfc{s g oiflist}disables each oif in oiflist from the replic<strong>at</strong>or for 〈s, g〉.<strong>The</strong> list of primitives accessible <strong>at</strong> the node to control its interfaces are listed below.267


add-iif{ifid link},add-oif{link if}get-all-oifs{}get-all-iifs{}iif2link{ifid}link2iif{link}oif2link{oif}link2oif{link}rpf-nbr{src}Invoked during link cre<strong>at</strong>ion to prep the node about its incoming interface label <strong>and</strong> outgoinginterface object.Retur<strong>ns</strong> all oifs for this node.Retur<strong>ns</strong> all iifs for this node.Retur<strong>ns</strong> the link object labelled with given interface label.Retur<strong>ns</strong> the incoming interface label for the given link.Retur<strong>ns</strong> the link object corresponding to the given outgoing interface.Retur<strong>ns</strong> the outgoing interface for the link (<strong>ns</strong> object th<strong>at</strong> is incident to the node).Retur<strong>ns</strong> a h<strong>and</strong>le to the neighbour node th<strong>at</strong> is its next hop to the specified src.getReps{s g} Retur<strong>ns</strong> a h<strong>and</strong>le to the replic<strong>at</strong>or th<strong>at</strong> m<strong>at</strong>ches 〈s, g〉. Either argument can be a wildcard (*).getReps-raw{s g} As above, but retur<strong>ns</strong> a list of 〈key, h<strong>and</strong>le〉 pairs.clearReps{s g} Removes all replic<strong>at</strong>ors associ<strong>at</strong>ed with 〈s, g〉.Class Link <strong>and</strong> SimpleLink This class provides methods to check the type of link, <strong>and</strong> the label it affixes on individualpackets th<strong>at</strong> traverse it. <strong>The</strong>re is one additional method to actually place the interface objects on this link. <strong>The</strong>se methods are:if-label?{}retur<strong>ns</strong> the interface label affixed by this link to packets th<strong>at</strong> traverse it.Class NetworkInterface This is a simple connector th<strong>at</strong> is placed on each link. It affixes its label id to each packet th<strong>at</strong>traverses it. <strong>The</strong> packet id is used by the destin<strong>at</strong>ion node incident on th<strong>at</strong> link to identify the link by which the packet reachedit. <strong>The</strong> label id is configured by the Link co<strong>ns</strong>tructor. This object is an internal object, <strong>and</strong> is not designed to be manipul<strong>at</strong>edby user level simul<strong>at</strong>ion scripts. <strong>The</strong> object only supports two methods:label{ifid}label{}assig<strong>ns</strong> ifid th<strong>at</strong> this object will affix to each packet.retur<strong>ns</strong> the label th<strong>at</strong> this object affixes to each packet.<strong>The</strong> global class variable, ifacenum_, specifies the next available ifid number.Class Multicast Classifier Classifier/Multicast maintai<strong>ns</strong> a multicast forwarding cache. <strong>The</strong>re is one multicastclassifier per node. <strong>The</strong> node stores a reference to this classifier in its i<strong>ns</strong>tance variable multiclassifier_. When thisclassifier receives a packet, it looks <strong>at</strong> the 〈source, group〉 inform<strong>at</strong>ion in the packet headers, <strong>and</strong> the interface th<strong>at</strong> the packetarrived from (the incoming interface or iif); does a lookup in the MFC <strong>and</strong> identifies the slot th<strong>at</strong> should be used to forwardth<strong>at</strong> packet. <strong>The</strong> slot will point to the appropri<strong>at</strong>e replic<strong>at</strong>or.However, if the classifier does not have an entry for this 〈source, group〉, or the iif for this entry is different, it will invoke anupcall new-group{} for the classifier, with one of two codes to identify the problem:• cache-miss indic<strong>at</strong>es th<strong>at</strong> the classifier did not find any 〈source, group〉 entries;• wrong-iif indic<strong>at</strong>es th<strong>at</strong> the classifier found 〈source, group〉 entries, but none m<strong>at</strong>ching the interface th<strong>at</strong> this packetarrived on.<strong>The</strong>se upcalls to TCL give it a chance to correct the situ<strong>at</strong>ion: i<strong>ns</strong>tall an appropri<strong>at</strong>e MFC–entry (for cache-miss) orchange the incoming interface for the existing MFC–entry (for wrong-iif). <strong>The</strong> return value of the upcall determines wh<strong>at</strong>classifier will do with the packet. If the return value is “1”, it will assume th<strong>at</strong> TCL upcall has appropri<strong>at</strong>ely modified MFC268


will try to classify packet (lookup MFC) for the second time. If the return value is “0”, no further lookups will be done, <strong>and</strong>the packet will be thus dropped.add-rep{} cre<strong>at</strong>es a slot in the classifier <strong>and</strong> adds a replic<strong>at</strong>or for 〈source, group, iif〉 to th<strong>at</strong> slot.Class Replic<strong>at</strong>or When a replic<strong>at</strong>or receives a packet, it copies the packet to all of its slots. Each slot points to an outgoinginterface for a particular 〈source, group〉.If no slot is found, the C++ replic<strong>at</strong>or invokes the class i<strong>ns</strong>tance procedure drop{} to trigger protocol specific actio<strong>ns</strong>. Wewill describe the protocol specific actio<strong>ns</strong> in the next section, when we describe the internal procedures of each of the multicastrouting protocols.<strong>The</strong>re are i<strong>ns</strong>tance procedures to control the elements in each slot:i<strong>ns</strong>ert{oif}disable{oif}enable{oif}is-active{}exists{oif}change-iface{source, group, oldiif, newiif}i<strong>ns</strong>erting a new outgoing interface to the next available slot.disable the slot pointing to the specified oif.enable the slot pointing to the specified oif.retur<strong>ns</strong> true if the replic<strong>at</strong>or has <strong>at</strong> least one active slot.retur<strong>ns</strong> true if the slot pointing to the specified oif is active.modified the iif entry for the particular replic<strong>at</strong>or.30.2.3 Protocol InternalsWe now describe the implement<strong>at</strong>ion of the different multicast routing protocol agents.Centralized MulticastCtrMcast is inherits from McastProtocol. One CtrMcast agent needs to be cre<strong>at</strong>ed for each node. <strong>The</strong>re is a centralCtrMcastComp agent to compute <strong>and</strong> i<strong>ns</strong>tall multicast routes for the entire topology. Each CtrMcast agent processesmembership dynamic comm<strong>and</strong>s, <strong>and</strong> redirects the CtrMcastComp agent to recompute the appropri<strong>at</strong>e routes.join-group{}leave-group{}h<strong>and</strong>le-cache-miss{}registers the new member with the CtrMCastComp agent, <strong>and</strong> invokes th<strong>at</strong> agent to recomputeroutes for th<strong>at</strong> member.is the inverse of join-group{}.called when no proper forwarding entry is found for a particular packet source. In case ofcentralized multicast, it mea<strong>ns</strong> a new source has started sending d<strong>at</strong>a packets. Thus, theCtrMcast agent registers this new source with the CtrMcastComp agent. If there are anymembers in th<strong>at</strong> group, compute the new multicast tree. If the group is in RPT (shared tree)mode, then1. cre<strong>at</strong>e an encapsul<strong>at</strong>ion agent <strong>at</strong> the source;2. a corresponding decapsul<strong>at</strong>ion agent is cre<strong>at</strong>ed <strong>at</strong> the RP;3. the two agents are connected by unicast; <strong>and</strong>4. the 〈S,G〉 entry points its outgoing interface to the encapsul<strong>at</strong>ion agent.269


CtrMcastComp is the centralised multicast route comput<strong>at</strong>ion agent.reset-mroutes{}compute-mroutes{}compute-tree{source, group}compute-branch{source, group, member}prune-branch{source, group, member}resets all multicast forwarding entries.(re)computes all multicast forwarding entries.computes a multicast tree for one source to reach all the receivers in aspecific group.is executed when a receiver joi<strong>ns</strong> a multicast group. It could also beinvoked by compute-tree{} when it itself is recomputing the multicasttree, <strong>and</strong> has to reparent all receivers. <strong>The</strong> algorithm starts <strong>at</strong> thereceiver, recursively finding successive next hops, until it either reachesthe source or RP, or it reaches a node th<strong>at</strong> is already a part of the relevantmulticast tree. During the process, several new replic<strong>at</strong>ors <strong>and</strong> anoutgoing interface will be i<strong>ns</strong>talled.is similar to compute-branch{} except the outgoing interface is disabled;if the outgoing interface list is empty <strong>at</strong> th<strong>at</strong> node, it will walkup the multicast tree, pruning <strong>at</strong> each of the intermedi<strong>at</strong>e nodes, until itreaches a node th<strong>at</strong> has a non-empty outgoing interface list for the particularmulticast tree.De<strong>ns</strong>e Modejoin-group{group} sends graft messages upstream if 〈S,G〉 does not contain any activeoutgoing slots (i.e., no dow<strong>ns</strong>tream receivers). If the nexthop towards the source is a LAN, icrements a counter of receiversfor a particular group for the LANleave-group{group} decrements LAN counters.h<strong>and</strong>le-cache-miss{srcID group iface} depending on the value of CacheMissModecalls either h<strong>and</strong>le-cache-miss-pimdm orh<strong>and</strong>le-cache-miss-dvmrp.h<strong>and</strong>le-cache-miss-pimdm{srcID group iface} if the packet was received on the correct iif (from the node th<strong>at</strong>is the next hop towards the source), fan out the packet on all oifsexcept the oif th<strong>at</strong> leads back to the next–hop–neighbor <strong>and</strong> oifsth<strong>at</strong> are LANs for which this node is not a forwarder. Otherwise,if the interface was incorrect, send a prune back.h<strong>and</strong>le-cache-miss-dvmrp{srcID group iface} fa<strong>ns</strong> out the packet only to nodes for which this node is a nexthop towards the source (parent).drop{replic<strong>at</strong>or source group iface} sends a prune message back to the previous hop.recv-prune{from source group iface} resets the prune timer if the interface had been pruned previously;otherwise, it starts the prune timer <strong>and</strong> disables the interface; furthermore,if the outgoing interface list becomes empty, it propag<strong>at</strong>esthe prune message upstream.recv-graft{from source group iface} cancels any existing prune timer, <strong>and</strong>re-enables the pruned interface.If the outgoing interface list was previously empty, itforwards the graft upstream.h<strong>and</strong>le-wrong-iif{srcID group iface} This is invoked when the multicast classifier drops apacket because it arrived on the wrong interface, <strong>and</strong>invoked new-group{}. This routine is invoked bymrtObject i<strong>ns</strong>tproc new-group{}. When invoked, itsends a prune message back to the source.270


30.2.4 <strong>The</strong> internal variablesClass mrtObjectprotocols_mask-wkgroupswkgroupsAn array of h<strong>and</strong>les of protocol i<strong>ns</strong>tances active <strong>at</strong> the node <strong>at</strong> which this protocol oper<strong>at</strong>esindexed by incoming interface.Class variable—defines the mask used to identify well known groups.Class array variable—array of alloc<strong>at</strong>ed well known groups addresses, indexed by the groupname. wkgroups(Allocd) is a special variable indic<strong>at</strong>ing the highest currently alloc<strong>at</strong>ed wellknown group.McastProtocolst<strong>at</strong>us_type_Simul<strong>at</strong>ormultiSim_MrtH<strong>and</strong>le_takes values “up” or “down”, to indic<strong>at</strong>e the st<strong>at</strong>us of execution of the protocol i<strong>ns</strong>tance.contai<strong>ns</strong> the type (class name) of protocol executed by this i<strong>ns</strong>tance, e.g., DM, or ST.1 if multicast simul<strong>at</strong>ion is enabled, 0 otherwise.h<strong>and</strong>le to the centralised multicast simul<strong>at</strong>ion object.Nodeswitch_multiclassifier_replic<strong>at</strong>or_Agents_outLink_inLink_Link <strong>and</strong> SimpleLinkiif_head_NetworkInterfaceifacenum_h<strong>and</strong>le for classifier th<strong>at</strong> looks <strong>at</strong> the high bit of the destin<strong>at</strong>ion address in each packet to determinewhether it is a multicast packet (bit = 1) or a unicast packet (bit = 0).h<strong>and</strong>le to classifier th<strong>at</strong> performs the 〈s, g, iif〉 m<strong>at</strong>ch.array indexed by 〈s, g〉 of h<strong>and</strong>les th<strong>at</strong> replic<strong>at</strong>e a multicast packet on to the required links.array indexed by multicast group of the list of agents <strong>at</strong> the local node th<strong>at</strong> listen to the specificgroup.Cached list of outgoing interfaces <strong>at</strong> this node.Cached list of incoming interfaces <strong>at</strong> this node.h<strong>and</strong>le for the NetworkInterface object placed on this link.first object on the link, a no-op connector. However, this object contai<strong>ns</strong> the i<strong>ns</strong>tance variable,link_, th<strong>at</strong> points to the container Link object.Class variable—holds the next available interface number.30.3 Comm<strong>and</strong>s <strong>at</strong> a glanceFollowing is a list of comm<strong>and</strong>s used for multicast simul<strong>at</strong>io<strong>ns</strong>:set <strong>ns</strong> [new Simul<strong>at</strong>or -mcast on]This tur<strong>ns</strong> the multicast flag on for the the given simul<strong>at</strong>ion, <strong>at</strong> the time of cre<strong>at</strong>ion of the simul<strong>at</strong>or object.<strong>ns</strong>_ multicastThis like the comm<strong>and</strong> above tur<strong>ns</strong> the multicast flag on.<strong>ns</strong>_ multicast?This retur<strong>ns</strong> true if multicast flag has been turned on for the simul<strong>at</strong>ion <strong>and</strong> retur<strong>ns</strong> false if multicast is not turned on.271


$<strong>ns</strong>_ mrtproto This comm<strong>and</strong> specifies the type of multicast protocol to be used like DM, CtrMcast etc. As an additionalargument, the list of nodes th<strong>at</strong> will run an i<strong>ns</strong>tance of detailed routing protocol (other than centralised mcast) canalso be passed.$<strong>ns</strong>_ mrtproto-iifs This comm<strong>and</strong> allows a finer control than mrtproto. Since multiple mcast protocols can be run <strong>at</strong> a node, this comm<strong>and</strong>specifies which mcast protocol to run <strong>at</strong> which of the incoming interfaces given by in the .Node allocaddrThis retur<strong>ns</strong> a new/unused multicast address th<strong>at</strong> may be used to assign a multicast address to a group.Node exp<strong>and</strong>addrTHIS COMMAND IS OBSOLETE NOW This comm<strong>and</strong> exp<strong>and</strong>s the address space from 16 bits to 30 bits. However thiscomm<strong>and</strong> has been replaced by "<strong>ns</strong>_ set-address-form<strong>at</strong>-exp<strong>and</strong>ed".$node_ join-group This comm<strong>and</strong> is used when the <strong>at</strong> the node joi<strong>ns</strong> a particular group .$node_ leave-group This is used when the <strong>at</strong> the nodes decides to leave the group .Internal methods:$<strong>ns</strong>_ run-mcastThis comm<strong>and</strong> starts multicast routing <strong>at</strong> all nodes.$<strong>ns</strong>_ clear-mcastThis stopd mcast routing <strong>at</strong> all nodes.$node_ enable-mcast This allows special mcast supporting mechanisms (like a mcast classifier) to be added to the mcast-enabled node. isthe a h<strong>and</strong>le to the simul<strong>at</strong>or object.In addition to the internal methods listed here there are other methods specific to protocols like centralized mcast (CtrMcast),de<strong>ns</strong>e mode (DM), shared tree mode (ST) or bi-directional shared tree mode (BST), Node <strong>and</strong> Link class methods <strong>and</strong>NetworkInterface <strong>and</strong> Multicast classifier methods specific to multicast routing. All mcast rel<strong>at</strong>ed files may be found under<strong>ns</strong>/tcl/mcast directory.Centralised Multicast A h<strong>and</strong>le to the CtrMcastComp object is returned when the protocol is specified as ‘CtrMcast’ inmrtproto. Ctrmcast methods are:$ctrmcastcomp switch-treetype group-addrSwitch from the Rendezvous Point rooted shared tree to source-specific trees for the group specified by group-addr.Note th<strong>at</strong> this method cannot be used to switch from source-specific trees back to a shared tree for a multicast group.$ctrmcastcomp set_c_rp This sets the RPs.$ctrmcastcomp set_c_bsr This sets the BSR, specified as list of node:priority.$ctrmcastcomp get_c_rp Retur<strong>ns</strong> the RP for the group as seen by the node node for the multicast group with address group-addr. Note th<strong>at</strong>different nodes may see different RPs for the group if the network is partitioned as the nodes might be in differentpartitio<strong>ns</strong>.$ctrmcastcomp get_c_bsr 272


Retur<strong>ns</strong> the current BSR for the group.$ctrmcastcomp compute-mroutesThis recomputes multicast routes in the event of network dynamics or a change in unicast routes.De<strong>ns</strong>e Mode <strong>The</strong> de<strong>ns</strong>e mode (DM) protocol can be run as PIM-DM (default) or DVMRP depending on the class variableCacheMissMode. <strong>The</strong>re are no methods specific to this mcast protocol object. Class variables are:PruneTimeout Timeout value for prune st<strong>at</strong>e <strong>at</strong> nodes. defaults to 0.5sec.CacheMissMode Used to set PIM-DM or DVMRP type forwarding rules.Shared Tree <strong>The</strong>re are no methods for this class. Variables are:RP_ RP_ indexed by group determines which node is the RP for a particular group.Bidirectional Shared Tree <strong>The</strong>re are no methods for this class. Variable is same as th<strong>at</strong> of Shared Tree described above.273


Chapter 31Network DynamicsThis chapter describes the capabilities in <strong>ns</strong> to make the simul<strong>at</strong>ion topologies dynamic. We start with the i<strong>ns</strong>tance proceduresto the class Simul<strong>at</strong>or th<strong>at</strong> are useful to a simul<strong>at</strong>ion script (Section 31.1). <strong>The</strong> next section describes the internal architecture(Section 31.2), including the different classes <strong>and</strong> i<strong>ns</strong>tance variables <strong>and</strong> procedures; the following section describes theinteraction with unicast routing (Section 31.3). This aspect of network dynamics is still somewh<strong>at</strong> experimental in <strong>ns</strong>. <strong>The</strong>last section of this chapter outlines some of the deficiencies in the current realiz<strong>at</strong>ion (Section 31.4) of network dynamics,some one or which may be fixed in the future.<strong>The</strong> procedures <strong>and</strong> functio<strong>ns</strong> described in this chapter can be found in ~<strong>ns</strong>/tcl/rtglib/dynamics.tcl <strong>and</strong> ~<strong>ns</strong>/tcl/lib/routeproto.tcl.31.1 <strong>The</strong> user level API<strong>The</strong> user level interface to network dynamics is a collection of i<strong>ns</strong>tance procedures in the class Simul<strong>at</strong>or, <strong>and</strong> one procedureto trace <strong>and</strong> log the dynamics activity. Reflecting a r<strong>at</strong>her poor choice of names, these procedures are rtmodel,rtmodel-delete, <strong>and</strong> rtmodel-<strong>at</strong>. <strong>The</strong>re is one other procedure, rtmodel-configure, th<strong>at</strong> is used internally bythe class Simul<strong>at</strong>or to configure the rtmodels just prior to simul<strong>at</strong>ion start. We describe this method l<strong>at</strong>er (Section 31.2).— <strong>The</strong> i<strong>ns</strong>tance procedure rtmodel{} defines a model to be applied to the nodes <strong>and</strong> links in the topology. Someexamples of this comm<strong>and</strong> as it would be used in a simul<strong>at</strong>ion script are:$<strong>ns</strong> rtmodel Exponential 0.8 1.0 1.0 $n1$<strong>ns</strong> rtmodel Trace dynamics.trc $n2 $n3$<strong>ns</strong> rtmodel Deterministic 20.0 20.0 $node(1) $node(5)<strong>The</strong> procedure requires <strong>at</strong> least three arguments:• <strong>The</strong> first two arguments define the model th<strong>at</strong> will be used, <strong>and</strong> the parameters to configure the model.<strong>The</strong> currently implemented models in <strong>ns</strong> are Exponential (On/Off), Deterministic (On/Off), Trace (driven), or<strong>Manual</strong> (one-shot) models.• <strong>The</strong> number, form<strong>at</strong>, <strong>and</strong> interpret<strong>at</strong>ion of the configur<strong>at</strong>ion parameters is specific to the particular model.1. <strong>The</strong> exponential on/off model takes four parameters: 〈[start time], up interval, down interval, [finish time]〉.〈start time〉 defaults to 0.5s. from the start of the simul<strong>at</strong>ion, 〈finish time〉 defaults to the end of the simul<strong>at</strong>ion.〈up interval〉 <strong>and</strong> 〈down interval〉 specify the mean of the exponential distribution defining the time th<strong>at</strong> the274


node or link will be up <strong>and</strong> down respectively. <strong>The</strong> default up <strong>and</strong> down interval values are 10s. <strong>and</strong> 1s.respectively. Any of these values can be specified as “−” to default to the original value.<strong>The</strong> following are example specific<strong>at</strong>io<strong>ns</strong> of parameters to this model:0.8 1.0 1.0 ;# start <strong>at</strong> 0.8s., up/down = 1.0s., finish is default5.0 0.5 ;# start is default, up/down = 5.0s, 0.5s., finish is default- 0.7 ;# start, up interval are default, down = 0.7s., finish is default- - - 10 ;# start, up, down are default, finish <strong>at</strong> 10s.2. <strong>The</strong> deterministic on/off model is similar to the exponential model above, <strong>and</strong> takes four parameters: 〈[starttime], up interval, down interval, [finish time]〉. 〈start time〉 defaults to the start of the simul<strong>at</strong>ion, 〈finish time〉defaults to the end of the simul<strong>at</strong>ion. Only the interpret<strong>at</strong>ion of the up <strong>and</strong> down interval is different; 〈upinterval〉 <strong>and</strong> 〈down interval〉 specify the exact dur<strong>at</strong>ion th<strong>at</strong> the node or link will be up <strong>and</strong> down respectively.<strong>The</strong> default values for these parameters are: 〈start time〉 is 0.5s. from start of simul<strong>at</strong>ion, 〈up interval〉 is 2.0s.,〈down interval〉 is 1.0s., <strong>and</strong> 〈finish time〉 is the dur<strong>at</strong>ion of the simul<strong>at</strong>ion.3. <strong>The</strong> trace driven model takes one parameter: the name of the trace file. <strong>The</strong> form<strong>at</strong> of the input trace file isidentical to th<strong>at</strong> output by the dynamics trace modules, viz., v 〈time〉 link-〈oper<strong>at</strong>ion〉 〈node1〉〈node2〉. Lines th<strong>at</strong> do not correspond to the node or link specified are ignored.v 0.8123 link-up 3 5v 3.5124 link-down 3 54. <strong>The</strong> manual one-shot model takes two parameters: the oper<strong>at</strong>ion to be performed, <strong>and</strong> the time th<strong>at</strong> it is to beperformed.• <strong>The</strong> rest of the arguments to the rtmodel{} procedure define the node or link th<strong>at</strong> the model will be applied to.If only one node is specified, it is assumed th<strong>at</strong> the node will fail. This is modeled by making the links incidenton the node fail. If two nodes are specified, then the comm<strong>and</strong> assumes th<strong>at</strong> the two are adjacent to each other,<strong>and</strong> the model is applied to the link incident on the two nodes. If more than two nodes are specified, only the firstis co<strong>ns</strong>idered, the subsequent arguments are ignored.• i<strong>ns</strong>tance variable, traceAllFile_ is set.<strong>The</strong> comm<strong>and</strong> retur<strong>ns</strong> the h<strong>and</strong>le to the model th<strong>at</strong> was cre<strong>at</strong>ed in this call.Internally, rtmodel{} stores the list of route models cre<strong>at</strong>ed in the class Simul<strong>at</strong>or i<strong>ns</strong>tance variable, rtModel_.— <strong>The</strong> i<strong>ns</strong>tance procedure rtmodel-delete{} takes the h<strong>and</strong>le of a route model as argument, removes it from thertModel_ list, <strong>and</strong> deletes the route model.— <strong>The</strong> i<strong>ns</strong>tance procedure rtmodel-<strong>at</strong>{} is a special interface to the <strong>Manual</strong> model of network dynamics.<strong>The</strong> comm<strong>and</strong> takes the time, oper<strong>at</strong>ion, <strong>and</strong> node or link as arguments, <strong>and</strong> applies the oper<strong>at</strong>ion to the node or link <strong>at</strong>the specified time. Example uses of this comm<strong>and</strong> are:$<strong>ns</strong> rtmodel-<strong>at</strong> 3.5 up $n0$<strong>ns</strong> rtmodel-<strong>at</strong> 3.9 up $n(3) $n(5)$<strong>ns</strong> rtmodel-<strong>at</strong> 40 down $n4Finally, the i<strong>ns</strong>tance procedure trace-dynamics{} of the class rtModel enables tracing of the dynamics effected by thismodel. It is used as:set fh [open "dyn.tr" w]$rtmodel1 trace-dynamics $fh$rtmodel2 trace-dynamics $fh$rtmodel1 trace-dynamics stdoutIn this example, $rtmodel1 writes out trace entries to both dyn.tr <strong>and</strong> stdout; $rtmodel2 only writes out trace entries todyn.tr. A typical sequence of trace entries written out by either model might be:275


v 0.8123 link-up 3 5v 0.8123 link-up 5 3v 3.5124 link-down 3 5v 3.5124 link-down 5 3<strong>The</strong>se lines above indic<strong>at</strong>e th<strong>at</strong> Link 〈3, 5〉 failed <strong>at</strong> 0.8123s., <strong>and</strong> recovered <strong>at</strong> time 3.5124s.31.2 <strong>The</strong> Internal ArchitectureEach model of network dynamics is implemented as a separ<strong>at</strong>e class, derived from the base class rtModel. We beginby describing the base class rtModel <strong>and</strong> the derived classes (Section 31.2.1). <strong>The</strong> network dynamics models use an internalqueuing structure to e<strong>ns</strong>ure th<strong>at</strong> simultaneous events are correctly h<strong>and</strong>led, the class rtQueue. <strong>The</strong> next subsection (Section31.2.2) describes the internals of this structure. Finally, we describe the exte<strong>ns</strong>io<strong>ns</strong> to the existing classes (Section 31.3.1):the Node, Link, <strong>and</strong> others.31.2.1 <strong>The</strong> class rtModelTo use a new route model, the routine rtmodel{} cre<strong>at</strong>es an i<strong>ns</strong>tance of the appropri<strong>at</strong>e type, defines the node or link th<strong>at</strong>the model will oper<strong>at</strong>e upon, configures the model, <strong>and</strong> possibly enables tracing; <strong>The</strong> individual i<strong>ns</strong>tance procedures th<strong>at</strong>accomplish this in pieces are:<strong>The</strong> co<strong>ns</strong>tructor for the base class stores a reference to the Simul<strong>at</strong>or in its i<strong>ns</strong>tance variable, <strong>ns</strong>_. It also initializes thestartTime_ <strong>and</strong> finishTime_ from the class variables of the same name.<strong>The</strong> i<strong>ns</strong>tance procedure set-elements identifies the node or link th<strong>at</strong> the model will oper<strong>at</strong>e upon. <strong>The</strong> comm<strong>and</strong> storestwo arrays: links_, of the links th<strong>at</strong> the model will act upon; nodes_, of the incident nodes th<strong>at</strong> will be affected bythe link failure or recovery caused by the model.<strong>The</strong> default procedure in the base class to set the model configur<strong>at</strong>ion parameters is set-parms. It assumes a well definedstart time, up interval, down interval, <strong>and</strong> a finish time, <strong>and</strong> sets up configur<strong>at</strong>ion parameters for some class of models.It stores these values in the i<strong>ns</strong>tance variables: startTime_, upInterval_, downInterval_, finishTime_.<strong>The</strong> exponential <strong>and</strong> deterministic models use this default routine, the trace based <strong>and</strong> manual models define their ownprocedures.<strong>The</strong> i<strong>ns</strong>tance procedure trace{} enables trace-dynamics{} on each of the links th<strong>at</strong> it affects. Additional detailson trace-dynamics{} is discussed in the section on exte<strong>ns</strong>io<strong>ns</strong> to the class Link (Section 31.3.1).<strong>The</strong> next sequence of configur<strong>at</strong>ion steps are taken just prior to the start of the simul<strong>at</strong>or. <strong>ns</strong> invokes rtmodel-configure{}just before starting the simul<strong>at</strong>ion. This i<strong>ns</strong>tance procedure first acquires an i<strong>ns</strong>tance of the class rtQueue, <strong>and</strong> then invokesconfigure{} for each route model in its list, rtModel_.<strong>The</strong> i<strong>ns</strong>tance procedure configure{} makes each link th<strong>at</strong> is is applied to dynamic; this is the set of links stored inits i<strong>ns</strong>tance variable array, links_. <strong>The</strong>n the procedure schedules its first event.<strong>The</strong> default i<strong>ns</strong>tance procedure set-first-event{} schedules the first event to take all the links “down” <strong>at</strong>$startTime_ + upInterval_. Individual types of route models derived from this base class should redefine tihsfunction.276


Two i<strong>ns</strong>tance procedures in the base class , set-event{} <strong>and</strong> set-event-exact{}, can be used to scheduleevents in the route queue.set-event{interval, oper<strong>at</strong>ion} schedules oper<strong>at</strong>ion after interval seconds from the current time; it uses theprocedure set-event-exact{} below.set-event-exact{fireTime, oper<strong>at</strong>ion} schedules oper<strong>at</strong>ion to execute <strong>at</strong> fireTime.If the time for execution is gre<strong>at</strong>er than the finishTime_, then the only possible action is to take a failed link “up”.Finally, the base class provides the methods to take the links up{} or down{}. Each method invokes the appropri<strong>at</strong>eprocedure on each of the links in the i<strong>ns</strong>tance variable, links_.Exponential<strong>The</strong> model schedules its first event to take the links down <strong>at</strong> startTime_ + E(upInterval_);It also defines the procedures, up{} <strong>and</strong> down{}; each procedure invokes the base class procedure to perform the actualoper<strong>at</strong>ion. This routine then reschedules the next event <strong>at</strong> E(upInterval) or E(downInterval_) respectively.Deterministic <strong>The</strong> model defines the procedures, up{} <strong>and</strong> down{}; each procedure invokes the base class procedure toperform the actual oper<strong>at</strong>ion. This routine then reschedules the next event <strong>at</strong> upInterval or downInterval_ respectively.Trace<strong>The</strong> model redefines the i<strong>ns</strong>tance procedure set-parms{} to operan a trace file, <strong>and</strong> set events based on th<strong>at</strong> input.<strong>The</strong> i<strong>ns</strong>tance procedure get-next-event{} retur<strong>ns</strong> the next valid event from the trace file. A valid event is an event th<strong>at</strong>is applicable to one of the links in this object’s links_ variable.<strong>The</strong> i<strong>ns</strong>tance procedure set-trace-events{} uses get-next-event{} to schedule the next valid event.<strong>The</strong> model redefines set-first-event{}, up{}, <strong>and</strong> down{} to use set-trace-events{}.<strong>Manual</strong> <strong>The</strong> model is designed to fire exactly once. <strong>The</strong> i<strong>ns</strong>tance procedure set-parms{} takes an oper<strong>at</strong>ion <strong>and</strong> thetime to execute th<strong>at</strong> oper<strong>at</strong>ion as arguments. set-first-event{} will schedule the event <strong>at</strong> the appropri<strong>at</strong>e moment.This routine also redefines notify{} to delete the object i<strong>ns</strong>tance when the oper<strong>at</strong>ion is completed. This notion of the objectdeleting itself is fragile code.Since the object only fires once <strong>and</strong> does nto have to be rescheduled, it does not overload the procedures up{} or down{}.31.2.2 class rtQueue<strong>The</strong> simul<strong>at</strong>or needs to co-ordin<strong>at</strong>e multiple simultaneous network dynamics events, especially to e<strong>ns</strong>ure the right coherentbehaviour. Hence, the network dynamics models use their own internal route queue to schedule dynamics events. <strong>The</strong>re isone i<strong>ns</strong>tance of this object in the simul<strong>at</strong>or, in the class Simul<strong>at</strong>or i<strong>ns</strong>tance variable rtq_.<strong>The</strong> queue object stores an array of queued oper<strong>at</strong>io<strong>ns</strong> in its i<strong>ns</strong>tance variable, rtq_. <strong>The</strong> index is the time <strong>at</strong> which the eventwill execute. Each element is the list of oper<strong>at</strong>io<strong>ns</strong> th<strong>at</strong> will execute <strong>at</strong> th<strong>at</strong> time.<strong>The</strong> i<strong>ns</strong>tance procedures i<strong>ns</strong>q{} <strong>and</strong> i<strong>ns</strong>q-i{} can i<strong>ns</strong>ert an element into the queue.277


<strong>The</strong> first argument is the time <strong>at</strong> which this oper<strong>at</strong>ion will execute. i<strong>ns</strong>q{} takes the exact time as argument;i<strong>ns</strong>q-i{} takes the interval as argument, <strong>and</strong> schedules the oper<strong>at</strong>ion interval seconds after the current time.<strong>The</strong> following arguments specify the object, $obj, the i<strong>ns</strong>tance procedure of th<strong>at</strong> object, $iproc, <strong>and</strong> the argumentsto th<strong>at</strong> procedure, $args.<strong>The</strong>se arguments are placed into the route queue for execution <strong>at</strong> the appropri<strong>at</strong>e time.<strong>The</strong> i<strong>ns</strong>tance procedure runq{} executes eval $obj $iproc $args <strong>at</strong> the appropri<strong>at</strong>e i<strong>ns</strong>tant. After all the events forth<strong>at</strong> i<strong>ns</strong>tance are executed, runq{} will notify{} each object about the execution.Finally, the i<strong>ns</strong>tance procedure delq{} can remove a queued action with the time <strong>and</strong> the name of the object.31.3 Interaction with Unicast RoutingIn an earlier section, we had described how unicast routing reacts (Section 29.4.2) to changes to the topology. This sectiondetails the steps by which the network dynamics code will notify the nodes <strong>and</strong> routing about the changes to the topology.1. rtQueue::runq{} will invoke the procedures specified by each of the route model i<strong>ns</strong>tances. After all of the actio<strong>ns</strong>are completed, runq{} will notify each of the models.2. notify{} will then invoke i<strong>ns</strong>tance procedures <strong>at</strong> all of the nodes th<strong>at</strong> were incident to the affected links. Each routemodel stores the list of nodes in its i<strong>ns</strong>tance variable array, nodes_.It will then notify the RouteLogic i<strong>ns</strong>tance of topology changes.3. <strong>The</strong> rtModel object invokes the class Node i<strong>ns</strong>tance procedure intf-changed{} for each of the affected nodes.4. Node::intf-changed{} will notify any rtObject <strong>at</strong> the node of the possible changes to the topology.Recall th<strong>at</strong> these route objects are cre<strong>at</strong>ed when the simul<strong>at</strong>ion uses detailed dynamic unicast routing.31.3.1 Exte<strong>ns</strong>io<strong>ns</strong> to Other Classes<strong>The</strong> existing classes assume th<strong>at</strong> the topology is st<strong>at</strong>ic by default. In this section, we document the necessary changes to theseclasses to support dynamic topologies.We have already described the i<strong>ns</strong>tance procedures in the class Simul<strong>at</strong>or to cre<strong>at</strong>e or manipul<strong>at</strong>e route models, i.e.,rtmodel{}, rtmodel-<strong>at</strong>{}, rtmodel-delete{}, <strong>and</strong> rtmodel-configure{} in earlier sectio<strong>ns</strong> (Section 31.2.1).Similarly, the class Node contai<strong>ns</strong> the i<strong>ns</strong>tance procedure intf-changed{} th<strong>at</strong> we described in the previous section(Section 31.3).<strong>The</strong> network dynamics code oper<strong>at</strong>es on individual links. Each model currently tra<strong>ns</strong>l<strong>at</strong>es its specific<strong>at</strong>ion into oper<strong>at</strong>io<strong>ns</strong> onthe appropri<strong>at</strong>e links. <strong>The</strong> following paragraphs describe the class Link <strong>and</strong> rel<strong>at</strong>ed classes.class DynamicLink This class is the only TclObject in the network dynamics code. <strong>The</strong> shadow class is called classDynaLink. <strong>The</strong> class supports one bound variable, st<strong>at</strong>us_. st<strong>at</strong>us_ is 1 when the link is up, <strong>and</strong> 0 when the link isdown. <strong>The</strong> shadow object’s recv() method checks the st<strong>at</strong>us_ variable, to decide whether or not a packet should beforwarded.278


class Link This class supports the primitives: up <strong>and</strong> down, <strong>and</strong> up? to set <strong>and</strong> query st<strong>at</strong>us_. <strong>The</strong>se primitives arei<strong>ns</strong>tance procedures of the class.<strong>The</strong> i<strong>ns</strong>tance procedures up{} <strong>and</strong> down{} set st<strong>at</strong>us_ to 1 <strong>and</strong> 0 respectively.In addition, when the link fails, down{} will reset all connectors th<strong>at</strong> make up the link. Each connector, including allqueues <strong>and</strong> the delay object will flush <strong>and</strong> drop any packets th<strong>at</strong> it currently stores. This emul<strong>at</strong>es the packet drop dueto link failure.Both procedures then write trace entries to each file h<strong>and</strong>le in the list, dynT_.<strong>The</strong> i<strong>ns</strong>tance procedure up?{} retur<strong>ns</strong> the current value of st<strong>at</strong>us_.In addition, the class contai<strong>ns</strong> the i<strong>ns</strong>tance procedure all-connectors{}. This procedure takes an oper<strong>at</strong>ion as argument,<strong>and</strong> applies the oper<strong>at</strong>ion uniformly to all of the class i<strong>ns</strong>tance variables th<strong>at</strong> are h<strong>and</strong>les for TclObjects.class SimpleLink <strong>The</strong> class supports two i<strong>ns</strong>tance procedures dynamic{} <strong>and</strong> trace-dynamics{}. We havealready described the l<strong>at</strong>ter procedure when describing the trace{} procedure in the class rtModel.<strong>The</strong> i<strong>ns</strong>tance procedure dynamic{} i<strong>ns</strong>erts a DynamicLink object (Section 6.2) <strong>at</strong> the head of the queue. It points the downtargetof the object to the drop target of the link, drpT_, if the object is defined, or to the nullAgent_ in the simul<strong>at</strong>or. Italso signals each connector in the link th<strong>at</strong> the link is now dynamic.Most connectors ignore this signal to be become dynamic; the exception is DelayLink object. This object will normallyschedule each packet it receives for reception by the destin<strong>at</strong>ion node <strong>at</strong> the appropri<strong>at</strong>e time. When the link is dynamic,the object will queue each packet internally; it schedules only one event for the next packet th<strong>at</strong> will be delivered, i<strong>ns</strong>tead ofone event per packet normally. If the link fails, the route model will signal a reset, <strong>at</strong> which point, the shadow object willexecute its reset i<strong>ns</strong>tproc-like, <strong>and</strong> flush all packets in its internal queue. Additional details about the DelayLink can be foundin another chapter (Chapter 8).31.4 Deficencies in the Current Network Dynamics API<strong>The</strong>re are a number of deficencies in the current API th<strong>at</strong> should be changed in the next iter<strong>at</strong>ion:1. <strong>The</strong>re is no way to specify a cluster of nodes or links th<strong>at</strong> behave in lock-step dynamic synchrony.2. Node failure should be dealt with as its own mechanism, r<strong>at</strong>her than a second grade citizen of link failure. This showsup in a number of situ<strong>at</strong>io<strong>ns</strong>, such as:(a) <strong>The</strong> method of emul<strong>at</strong>ing node failure as the failure of the incident links is broken. Ideally, node failure shouldcause all agents incident on the node to be reset.(b) <strong>The</strong>re is no tracing associ<strong>at</strong>ed with node failure.3. If two distinct route models are applied to two separ<strong>at</strong>e links incident on a common node, <strong>and</strong> the two links experiencea topology change <strong>at</strong> the same i<strong>ns</strong>tant, then the node will be notified more than once.31.5 Comm<strong>and</strong>s <strong>at</strong> a glanceFollowing is a list of comm<strong>and</strong>s used to simul<strong>at</strong>e dynamic scenarios in <strong>ns</strong>:279


$<strong>ns</strong>_ rtmodel This comm<strong>and</strong> defines the dynamic model (currently implemented models are: Deterministic, Exponential, <strong>Manual</strong> orTrace) to be applied to nodes <strong>and</strong> links in the topology. <strong>The</strong> first two arguments co<strong>ns</strong>ists of the rtmodel <strong>and</strong> the parameter toconfigure the model. st<strong>and</strong>s for different type of arguments expected with different dynamic model types. Thisretur<strong>ns</strong> a h<strong>and</strong>le to a model object corresponding to the specified model.• In the Deterministic model is , , , . Startingfrom start-time the link is made up for up-interval <strong>and</strong> down for down-interval till finish-time is reached. <strong>The</strong> defaultvalues for start-time, up-interval, downinterval are 0.5s, 2.0s, 1.0s respectively. finishtime defaults to the end of thesimul<strong>at</strong>ion. <strong>The</strong> start-time defaults to 0.5s in order to let the routing protocol comput<strong>at</strong>ion quiesce.• If the Exponential model is used model-params is of the form , where the link up-timeis an exponential distribution around the mean upinterval <strong>and</strong> the link down-time is an exponential distribution aroundthe mean down-interval. Default values for up-interval <strong>and</strong> down-interval are 10s <strong>and</strong> 1s respectively.• If the <strong>Manual</strong> distribution is used model-params is where <strong>at</strong> specifies the time <strong>at</strong> which the oper<strong>at</strong>ion opshould occur. op is one of up, down. <strong>The</strong> <strong>Manual</strong> distribution could be specified altern<strong>at</strong>ely using the rtmodel-<strong>at</strong>method described l<strong>at</strong>er in the section.• If Trace is specified as the model the link/node dynamics is read from a Tracefile. <strong>The</strong> model-params argument wouldin this case be the file-h<strong>and</strong>le of the Tracefile th<strong>at</strong> has the dynamics inform<strong>at</strong>ion. <strong>The</strong> tracefile form<strong>at</strong> is identical to thetrace output gener<strong>at</strong>ed by the trace-dynamics link method (see TRACE AND MONITORING METHODS SECTION).$<strong>ns</strong>_ rtmodel-delete This comm<strong>and</strong> takes the h<strong>and</strong>le of the routemodel as an argument, removes it from the list of rtmodels maintainedby simul<strong>at</strong>or <strong>and</strong> deletes the model.$<strong>ns</strong>_ rtmodel-<strong>at</strong> This comm<strong>and</strong> is a special interface to the <strong>Manual</strong> model of network dynamics. It takes the time , type of oper<strong>at</strong>ion <strong>and</strong> node or link on which to apply the oper<strong>at</strong>ion as the arguments. At time , the oper<strong>at</strong>ion whichmaybe up or down is applied to a node or link.$rtmodel trace This enables tracing of dynamics effected by this model in the links. is an i<strong>ns</strong>tance of the simul<strong>at</strong>or, the output fileto write the traces to <strong>and</strong> is an optional argument th<strong>at</strong> may be used to define a type of oper<strong>at</strong>ion (like nam). This is awrapper for the class Link procedure trace-dynamics.$link trace-dynamics This is a class link i<strong>ns</strong>tance procedure th<strong>at</strong> is used to setup tracing of dynamics in th<strong>at</strong> particular link. <strong>The</strong> arguments aresame as th<strong>at</strong> of class rtModel’s procedure trace described above.$link dynamicThis comm<strong>and</strong> i<strong>ns</strong>erts a DynamicLink object <strong>at</strong> the head of the queue <strong>and</strong> signals to all connectors in the link th<strong>at</strong> the link isnow dynamic.Internal procedures:$<strong>ns</strong>_ rtmodel-configureThis is an internal procedure th<strong>at</strong> configures all dynamic models th<strong>at</strong> are present in the list of models maintained by thesimul<strong>at</strong>or.280


Chapter 32Hierarchical RoutingThis chapter describes the internals of hierarchical routing implemented in <strong>ns</strong>. This chapter co<strong>ns</strong>ists of two sectio<strong>ns</strong>. In thefirst section we give an overview of hierarchical routing. In the second section we walk through the API’s used for settinghierarchical routing <strong>and</strong> describe the architecture, internals <strong>and</strong> code p<strong>at</strong>h for hier rtg in the process.<strong>The</strong> functio<strong>ns</strong> <strong>and</strong> procedures described in this chapter can be found in ~<strong>ns</strong>/tcl/lib/<strong>ns</strong>-hiernode.tcl, tcl/lib/<strong>ns</strong>-address.tcl,tcl/lib/<strong>ns</strong>-route.tcl <strong>and</strong> route.cc.32.1 Overview of Hierarchical RoutingHierarchical routing was mainly devised, among other things, to reduce memory requirements of simul<strong>at</strong>io<strong>ns</strong> over very largetopologies. A topology is broken down into several layers of hierarchy, thus dow<strong>ns</strong>izing the routing table. <strong>The</strong> table size isreduced from n 2 , for fl<strong>at</strong> routing, to about log n for hierarchical routing. However some overhead costs results as numberof hierarchy levels are increased. Optimum results were found for 3 levels of hierarchy <strong>and</strong> the current <strong>ns</strong> implement<strong>at</strong>io<strong>ns</strong>upports upto a maximum of 3 levels of hierarchical routing.To be able to use hierarchical routing for the simul<strong>at</strong>io<strong>ns</strong>, we need to define the hierarchy of the topology as well as providethe nodes with hierarchical addressing. In fl<strong>at</strong> routing, every node knows about every other node in the topology, thus resultingin routing table size to the order of n 2 . For hierarchical routing, each node knows only about those nodes in its level. Forall other destin<strong>at</strong>io<strong>ns</strong> outside its level it forwards the packets to the border router of its level. Thus the routing table size getsdow<strong>ns</strong>ized to the order of about log n.32.2 Usage of Hierarchical routingHierarchical routing requires some additional fe<strong>at</strong>ures <strong>and</strong> mechanisms for the simualtion. For example, a new node objectcalled HierNode is been defined for hier rtg. <strong>The</strong>refore the user must specify hierarchical routing requirements before cre<strong>at</strong>ingtopology. This is done as shown below:First, the address form<strong>at</strong> ( ) or the address space used for node <strong>and</strong> port address, needs to be set in the hierarchical mode. Itmay be done in one of the two ways:set <strong>ns</strong> [new Simul<strong>at</strong>or]281


$<strong>ns</strong> set-address-form<strong>at</strong> hierarchicalThis sets the node address space to a 3 level hierarchy assigning 8 bits in each level.or,$<strong>ns</strong> set-address-form<strong>at</strong> hierarchical ...which cre<strong>at</strong>es a node address space for n levels of hierarchy assigning bits as specified for every level.This other than cre<strong>at</strong>ing a hierarchical address space also sets a flag called EnableHierRt_ <strong>and</strong> sets the Simul<strong>at</strong>or class variablenode_factory_ to HierNode. <strong>The</strong>refore when nodes are cre<strong>at</strong>ed by calling Simul<strong>at</strong>or method “node” as in :$<strong>ns</strong> node 0.0.1, a HierNode is cre<strong>at</strong>ed with an address of 0.0.1;Class AddrParams is used to store the topology hierarchy like number of levels of hierarchy, number of areas in each levellike number of domai<strong>ns</strong>, number of clusters <strong>and</strong> number of nodes in each cluster.<strong>The</strong> API for supplying these inform<strong>at</strong>ion to AddrParams is shown below:AddrParams set domain_num_ 2lappend cluster_num 2 2AddrParams set cluster_num_ $cluster_numlappend eilastlevel 2 3 2 3AddrParams set nodes_num_ $eilastlevelThis defines a topology with 2 domai<strong>ns</strong>, say D1 <strong>and</strong> D2 with 2 clusters each (C11 & C12 in D1 <strong>and</strong> C21 & C22 in D2). <strong>The</strong>nnumber of nodes in each of these 4 clusters is specified as 2,3,2 <strong>and</strong> 3 respectively.<strong>The</strong> default values used by AddrParams provide a topology with a single domain with 4 clusters, with each cluster co<strong>ns</strong>istingof 5 nodes.Appropri<strong>at</strong>e mask <strong>and</strong> shift values are gener<strong>at</strong>ed by AddrParams for the hierarchical node address space.Each HierNode <strong>at</strong> the time of its cre<strong>at</strong>ion calls the method ‘mk-default-classifier ” to setup n numbers of address classifiersfor n levels of hierarchy defined in the topology.HierNode i<strong>ns</strong>tproc mk-default-classifier$self i<strong>ns</strong>tvar np_ id_ classifiers_ agents_ dmux_ neighbor_ address_# puts "id=$id_"set levels [AddrParams set hlevel_]for set n 1 $n


HierNodeEntry0123401234Level 201234Level 3To HierNodePort DemuxLevel 13-Level classifiers for HierNode (hier-addr:0.2.1)Figure 32.1: Hierarchical classifiersNode i<strong>ns</strong>tproc add-route dst target$self i<strong>ns</strong>tvar rtnotif_# Notify every module th<strong>at</strong> is interested about this# route i<strong>ns</strong>tall<strong>at</strong>ionif $rtnotif_ != ""$rtnotif_ add-route $dst $target$self incr-rtgtable-sizeFor an example of 3 level of hierarchy, the level 1 classifier demuxes for domai<strong>ns</strong>, level 2 for all clusters i<strong>ns</strong>ide the node’sdomain <strong>and</strong> finally classifier 3 demuxes for all nodes in the particular cluster th<strong>at</strong> the node itself resides. For such a topology,a HierNode with address of 0.1.2 looks like the figure below:Thus the size of the routing tables are co<strong>ns</strong>iderably reduced from n 2 as seen for fl<strong>at</strong> routing where each node had to storethe next_hop info of all other nodes in the topology. I<strong>ns</strong>tead, for hierarchical routing, a given node needs to know aboutits neighbours in its own cluster, about the all clusters in its domain <strong>and</strong> about all the domai<strong>ns</strong>. This saves on memoryco<strong>ns</strong>umption as well as run-time for the simul<strong>at</strong>io<strong>ns</strong> using several thous<strong>and</strong>s of nodes in their topology.32.3 Cre<strong>at</strong>ing large Hierarchical topologies<strong>The</strong> previous section describes methods to cre<strong>at</strong>e hierarchical topologies by h<strong>and</strong>. However, there is a script availablein <strong>ns</strong> th<strong>at</strong> converts Georgia-tech’s SGB-graphs into <strong>ns</strong> comp<strong>at</strong>ible hierarchical topologies. Please refer to http://wwwmash.CS.Berkeley.EDU/<strong>ns</strong>/<strong>ns</strong>-topogen.htmlfor downloading as well as i<strong>ns</strong>tructio<strong>ns</strong> on using the hierarchical converter package.See hier-rtg-10.tcl <strong>and</strong> hier-rtg-100.tcl in ~<strong>ns</strong>/tcl/ex for example scripts of hier routing on small <strong>and</strong> large topologies respectively.283


32.4 Hierarchical Routing with SessionSimHierarchical routing may be used in conjunction with Session simul<strong>at</strong>io<strong>ns</strong> (see Chapter 42). Session-level simul<strong>at</strong>io<strong>ns</strong> whichare used for running multicast simul<strong>at</strong>io<strong>ns</strong> over very large topologies, gai<strong>ns</strong> additionally in terms of memory savings if usedwith hierarchical routing. See simul<strong>at</strong>ion script ~<strong>ns</strong>/tcl/ex/newmcast/session-hier.tcl for an example of sessio<strong>ns</strong>im over hierrtg.32.5 Comm<strong>and</strong>s <strong>at</strong> a glanceFollowing is a list of hierarchical routing/addressing rel<strong>at</strong>ed comm<strong>and</strong>s used in simul<strong>at</strong>ion scripts:$<strong>ns</strong>_ set-address-form<strong>at</strong> hierarchicalThis comm<strong>and</strong> was used to setup hierarchical addressing in <strong>ns</strong>. However with the recent changes in node APIs, thiscomm<strong>and</strong> has been replaced by<strong>ns</strong>_ node-config -addressType hierarchicalThis cre<strong>at</strong>es a default topology of 3 levels of hierarchy, assigning 8 bits to each level.$<strong>ns</strong>_ set-address-form<strong>at</strong> hierarchical ....This comm<strong>and</strong> cre<strong>at</strong>es a hierarchy of <strong>and</strong> assig<strong>ns</strong> the bits in each level as specified in the arguments.AddrParams set domain_num_ AddrParams set cluster_num_ AddrParams set nodes_num_ <strong>The</strong> above APIs are used to specify the hierarchical topology, i.e the number of domai<strong>ns</strong>, clusters <strong>and</strong> nodes present in thetopology. Default values used by AddrParams (i.e if nothing is specified) provide a topology with a single domain with 4clusters, with each cluster co<strong>ns</strong>isting of 5 nodes.Internal procedures:$Node add-route This procedure is used to add next-hop entries of a destin<strong>at</strong>ion for a given .$hiernode_ split-addrstr This splits up a hierarchical adrress string (say a.b.c) into a list of the addresses <strong>at</strong> each level (i.e, a,b <strong>and</strong> c).284


Part VTra<strong>ns</strong>port285


Chapter 33UDP Agents33.1 UDP AgentsUDP agents are implemented in udp.{cc, h}. A UDP agent accepts d<strong>at</strong>a in variable size chunks from an applic<strong>at</strong>ion,<strong>and</strong> segments the d<strong>at</strong>a if needed. UDP packets also contain a monotonically increasing sequence number <strong>and</strong> an RTP timestamp.Although real UDP packets do not contain sequence numbers or timestamps, this sequence number does not incur anysimul<strong>at</strong>ed overhead, <strong>and</strong> can be useful for tracefile analysis or for simul<strong>at</strong>ing UDP-based applic<strong>at</strong>io<strong>ns</strong>.<strong>The</strong> default maximum segment size (MSS) for UDP agents is 1000 byte:Agent/UDP set packetSize_ 1000 ;# max segment sizeThis OTcl i<strong>ns</strong>tvar is bound to the C++ agent variable size_.Applic<strong>at</strong>io<strong>ns</strong> can access UDP agents via the sendmsg() function in C++, or via the send or sendmsg methods in OTcl, asdescribed in section 38.2.3.<strong>The</strong> following is a simple example of how a UDP agent may be used in a program. In the example, the CBR traffic gener<strong>at</strong>oris started <strong>at</strong> time 1.0, <strong>at</strong> which time the gener<strong>at</strong>or begi<strong>ns</strong> to periodically call the UDP agent sendmsg() function.set <strong>ns</strong> [new Simul<strong>at</strong>or]set n0 [$<strong>ns</strong> node]set n1 [$<strong>ns</strong> node]$<strong>ns</strong> duplex-link $n0 $n1 5Mb 2ms DropTailset udp0 [new Agent/UDP]$<strong>ns</strong> <strong>at</strong>tach-agent $n0 $udp0set cbr0 [new Applic<strong>at</strong>ion/Traffic/CBR]$cbr0 <strong>at</strong>tach-agent $udp0$udp0 set packetSize_ 536;# set MSS to 536 bytesset null0 [new Agent/Null]$<strong>ns</strong> <strong>at</strong>tach-agent $n1 $null0$<strong>ns</strong> connect $udp0 $null0$<strong>ns</strong> <strong>at</strong> 1.0 "$cbr0 start"286


33.2 Comm<strong>and</strong>s <strong>at</strong> a glance<strong>The</strong> following comm<strong>and</strong>s are used to setup UDP agents in simul<strong>at</strong>ion scripts:set udp0 [new Agent/UDP]This cre<strong>at</strong>es an i<strong>ns</strong>tance of the UDP agent.$<strong>ns</strong>_ <strong>at</strong>tach-agent This is a common comm<strong>and</strong> used to <strong>at</strong>tach any to a given .$traffic-gen <strong>at</strong>tach-agent This a class Applic<strong>at</strong>ion/Traffic/ method which connects the traffic gener<strong>at</strong>or to the given . Forexample, if we want to setup a CBR traffic flow for the udp agent, udp1, we given the following comm<strong>and</strong>sset cbr1 [new Applic<strong>at</strong>ion/Traffic/CBR]$cbr1 <strong>at</strong>tach-agent $udp1$<strong>ns</strong>_ connect This comm<strong>and</strong> sets up an end-to-end connection between two agents (<strong>at</strong> the tra<strong>ns</strong>port layer).$udp set packetSize_ $udp set dst_addr_ $udp set dst_port_ $udp set class_ $udp set ttl_ ..... etc<strong>The</strong> above are different parameter values th<strong>at</strong> may be set as shown above for udp agents. <strong>The</strong> default values can be found in<strong>ns</strong>/tcl/lib/<strong>ns</strong>-default.tcl.For a typical example of setting up an UDP agent used in a simul<strong>at</strong>ion, see the above section 33.1.287


Chapter 34TCP AgentsThis section describes the oper<strong>at</strong>ion of the TCP agents in <strong>ns</strong>. <strong>The</strong>re are two major types of TCP agents: one-way agents <strong>and</strong> <strong>at</strong>wo-way agent. One-way agents are further subdivided into a set of TCP senders (which obey different congestion <strong>and</strong> errorcontrol techniques) <strong>and</strong> receivers (“sinks”). <strong>The</strong> two-way agent is symmetric in the se<strong>ns</strong>e th<strong>at</strong> it represents both a sender <strong>and</strong>receiver. It is still under development.<strong>The</strong> files described in this section are too numerous to enumer<strong>at</strong>e here. Basically it covers most files m<strong>at</strong>ching the regularexpression ~<strong>ns</strong>/tcp*.{cc, h}.<strong>The</strong> one-way TCP sending agents currently supported are:• Agent/TCP - a “tahoe” TCP sender• Agent/TCP/Reno - a “Reno” TCP sender• Agent/TCP/Newreno - Reno with a modific<strong>at</strong>ion• Agent/TCP/Sack1 - TCP with selective repe<strong>at</strong> (follows RFC2018)• Agent/TCP/Vegas - TCP Vegas• Agent/TCP/Fack - Reno TCP with “forward acknowledgment”<strong>The</strong> one-way TCP receiving agents currently supported are:• Agent/TCPSink - TCP sink with one ACK per packet• Agent/TCPSink/DelAck - TCP sink with configurable delay per ACK• Agent/TCPSink/Sack1 - selective ACK sink (follows RFC2018)• Agent/TCPSink/Sack1/DelAck - Sack1 with DelAck<strong>The</strong> two-way experimental sender currently supports only a Reno form of TCP:• Agent/TCP/FullTcp<strong>The</strong> section comprises three parts: the first part is a simple overview <strong>and</strong> example of configuring the base TCP send/sinkagents (the sink requires no configur<strong>at</strong>ion). <strong>The</strong> second part describes the internals of the base send agent, <strong>and</strong> last part is adescription of the exte<strong>ns</strong>io<strong>ns</strong> for the other types of agents th<strong>at</strong> have been included in the simul<strong>at</strong>or.288


34.1 One-Way TCP Senders<strong>The</strong> simul<strong>at</strong>or supports several versio<strong>ns</strong> of an abstracted TCP sender. <strong>The</strong>se objects <strong>at</strong>tempt to capture the essence of the TCPcongestion <strong>and</strong> error control behaviors, but are not intended to be faithful replicas of real-world TCP implement<strong>at</strong>io<strong>ns</strong>. <strong>The</strong>ydo not contain a dynamic window advertisement, they do segment number <strong>and</strong> ACK number comput<strong>at</strong>io<strong>ns</strong> entirely in packetunits, there is no SYN/FIN connection establishment/teardown, <strong>and</strong> no d<strong>at</strong>a is ever tra<strong>ns</strong>ferred (e.g. no checksums or urgentd<strong>at</strong>a).34.1.1 <strong>The</strong> Base TCP Sender (Tahoe TCP)<strong>The</strong> “Tahoe” TCP agent Agent/TCP performs congestion control <strong>and</strong> round-trip-time estim<strong>at</strong>ion in a way similar to theversion of TCP released with the 4.3BSD “Tahoe” UN’X system release from UC Berkeley. <strong>The</strong> congestion window is1increased by one packet per new ACK received during slow-start (when cwnd_ < ssthresh_) <strong>and</strong> is increased bycwnd_ foreach new ACK received during congestion avoidance (when cwnd_ ≥ ssthresh_).Respo<strong>ns</strong>es to Congestion Tahoe TCP assumes a packet has been lost (due to congestion) when it observes NUMDUPACKS(defined in tcp.h, currently 3) duplic<strong>at</strong>e ACKs, or when a retra<strong>ns</strong>mission timer expires. In either case, Tahoe TCP reacts bysetting ssthresh_ to half of the current window size (the minimum of cwnd_ <strong>and</strong> window_) or 2, whichever is larger. Itthen initializes cwnd_ back to the value of windowInit_. This will typically cause the TCP to enter slow-start.Round-Trip Time Estim<strong>at</strong>ion <strong>and</strong> RTO Timeout Selection Four variables are used to estim<strong>at</strong>e the round-trip time<strong>and</strong> set the retra<strong>ns</strong>mission timer: rtt_, srtt_, rttvar_, tcpTick_, <strong>and</strong> backoff_. TCP initializes rttvarto 3/tcpTick_ <strong>and</strong> backoff to 1. When any future retra<strong>ns</strong>mission timer is set, it’s timeout is set to the current time plusmax(bt(a + 4v + 1), 64) seconds, where b is the current backoff value, t is the value of tcpTick, a is the value of srtt, <strong>and</strong> vis the value of rttvar.Round-trip time samples arrive with new ACKs. <strong>The</strong> RTT sample is computed as the difference between the current time <strong>and</strong>a “time echo” field in the ACK packet. When the first sample is taken, its value is used as the initial value for srtt_. Halfthe first sample is used as the initial value for rttvar_. For subsequent samples, the values are upd<strong>at</strong>ed as follows:srtt = 7 8 × srtt + 1 8 × samplerttvar = 3 4 × rttvar + 1 × |sample − srtt|434.1.2 Configur<strong>at</strong>ionRunning an TCP simul<strong>at</strong>ion requires cre<strong>at</strong>ing <strong>and</strong> configuring the agent, <strong>at</strong>taching an applic<strong>at</strong>ion-level d<strong>at</strong>a source (a trafficgener<strong>at</strong>or), <strong>and</strong> starting the agent <strong>and</strong> the traffic gener<strong>at</strong>or.34.1.3 Simple Configur<strong>at</strong>ionCre<strong>at</strong>ing the Agent289


set <strong>ns</strong> [new Simul<strong>at</strong>or]set node1 [$<strong>ns</strong> node]set node2 [$<strong>ns</strong> node];# preamble initializ<strong>at</strong>ion;# agent to reside on this node;# agent to reside on this nodeset tcp1 [$<strong>ns</strong> cre<strong>at</strong>e-connection TCP $node1 TCPSink $node22]4$tcp set window_ 50 ;# configure the TCP agentset ftp1 [new Applic<strong>at</strong>ion/FTP]$ftp1 <strong>at</strong>tach-agent $tcp1$<strong>ns</strong> <strong>at</strong> 0.0 "$ftp start"This example illustr<strong>at</strong>es the use of the simul<strong>at</strong>or built-in function cre<strong>at</strong>e-connection. <strong>The</strong> arguments to this functionare: the source agent to cre<strong>at</strong>e, the source node, the target agent to cre<strong>at</strong>e, the target node, <strong>and</strong> the flow ID to be used on theconnection. <strong>The</strong> function oper<strong>at</strong>es by cre<strong>at</strong>ing the two agents, setting the flow ID fields in the agents, <strong>at</strong>taching the source<strong>and</strong> target agents to their respective nodes, <strong>and</strong> finally connecting the agents (i.e. setting appropri<strong>at</strong>e source <strong>and</strong> destin<strong>at</strong>ionaddresses <strong>and</strong> ports). <strong>The</strong> return value of the function is the name of the source agent cre<strong>at</strong>ed.TCP D<strong>at</strong>a Source <strong>The</strong> TCP agent does not gener<strong>at</strong>e any applic<strong>at</strong>ion d<strong>at</strong>a on its own; i<strong>ns</strong>tead, the simul<strong>at</strong>ion user canconnect any traffic gener<strong>at</strong>ion module to the TCP agent to gener<strong>at</strong>e d<strong>at</strong>a. Two applic<strong>at</strong>io<strong>ns</strong> are commonly used for TCP: FTP<strong>and</strong> Telnet. FTP represents a bulk d<strong>at</strong>a tra<strong>ns</strong>fer of large size, <strong>and</strong> telnet chooses its tra<strong>ns</strong>fer sizes r<strong>and</strong>omly from tcplib (seethe file tcplib-telnet.cc. Details on configuring these applic<strong>at</strong>ion source objects are in Section 38.4.34.1.4 Other Configur<strong>at</strong>ion ParametersIn addition to the window_ parameter listed above, the TCP agent supports additional configur<strong>at</strong>ion variables. Each of thevariables described in this subsection is both a class variable <strong>and</strong> an i<strong>ns</strong>tance variable. Changing the class variable changesthe default value for all agents th<strong>at</strong> are cre<strong>at</strong>ed subsequently. Changing the i<strong>ns</strong>tance variable of a particular agent only affectsthe values used by th<strong>at</strong> agent. For example,Agent/TCP set window_ 100$tcp set window_ 2.0;# Changes the class variable;# Changes window_ for the $tcp object only<strong>The</strong> default parameters for each TCP agent are:Agent/TCP set window_ 20 ;# max bound on window sizeAgent/TCP set windowInit_ 1;# initial/reset value of cwndAgent/TCP set windowOption_ 1;# cong avoid algorithm (1: st<strong>and</strong>ard)Agent/TCP set windowCo<strong>ns</strong>tant_ 4 ;# used only when windowOption != 1Agent/TCP set windowThresh_ 0.002;# used in computing averaged windowAgent/TCP set overhead_ 0;# !=0 adds r<strong>and</strong>om time between sendsAgent/TCP set ecn_ 0;# TCP should react to ecn bitAgent/TCP set packetSize_ 1000;# packet size used by sender (bytes)Agent/TCP set bugFix_ true;# see explan<strong>at</strong>ionAgent/TCP set slow_start_restart_ true;# see explan<strong>at</strong>ionAgent/TCP set tcpTick_ 0.1;# timer granul<strong>at</strong>iry in sec (.1 is NONSTANDARD)Agent/TCP set maxrto_ 64;# bound on RTO (seconds)Agent/TCP set dupacks_ 0;# duplic<strong>at</strong>e ACK counterAgent/TCP set ack_ 0;# highest ACK received290


Agent/TCP set cwnd_ 0Agent/TCP set awnd_ 0Agent/TCP set ssthresh_ 0Agent/TCP set rtt_ 0Agent/TCP set srtt_ 0Agent/TCP set rttvar_ 0Agent/TCP set backoff_ 0Agent/TCP set maxseq_ 0;# congestion window (packets);# averaged cwnd (experimental);# slow-st<strong>at</strong> threshold (packets);# rtt sample;# smoothed (averaged) rtt;# mean devi<strong>at</strong>ion of rtt samples;# current RTO backoff factor;# max (packet) seq number sentFor many simul<strong>at</strong>io<strong>ns</strong>, few of the configur<strong>at</strong>ion parameters are likely to require modific<strong>at</strong>ion. <strong>The</strong> more commonly modifiedparameters include: window_ <strong>and</strong> packetSize_. <strong>The</strong> first of these bounds the window TCP uses, <strong>and</strong> is co<strong>ns</strong>idered toplay the role of the receiver’s advertised window in real-world TCP (although it remai<strong>ns</strong> co<strong>ns</strong>tant). <strong>The</strong> packet size essentiallyfunctio<strong>ns</strong> like the MSS size in real-world TCP. Changes to these parameters can have a profound effect on the behavior ofTCP. Generally, those TCPs with larger packet sizes, bigger windows, <strong>and</strong> smaller round trip times (a result of the topology<strong>and</strong> congestion) are more agressive in acquiring network b<strong>and</strong>width.34.1.5 Other One-Way TCP SendersReno TCP <strong>The</strong> Reno TCP agent is very similar to the Tahoe TCP agent, except it also includes fast recovery, where thecurrent congestion window is “infl<strong>at</strong>ed” by the number of duplic<strong>at</strong>e ACKs the TCP sender has received before receiving anew ACK. A “new ACK” refers to any ACK with a value higher than the higest seen so far. In addition, the Reno TCP agentdoes not return to slow-start during a fast retra<strong>ns</strong>mit. R<strong>at</strong>her, it reduces sets the congestion window to half the current window<strong>and</strong> resets ssthresh_ to m<strong>at</strong>ch this value.Newreno TCP This agent is based on the Reno TCP agent, but which modifies the action taken when receiving new ACKS.In order to exit fast recovery, the sender must receive an ACK for the highest sequence number sent. Thus, new “partialACKs” (those which represent new ACKs but do not represent an ACK for all outst<strong>and</strong>ing d<strong>at</strong>a) do not defl<strong>at</strong>e the window(<strong>and</strong> possibly lead to a stall, characteristic of Reno).Vegas TCPThis agent implements “Vegas” TCP ([4, 5]). It was contributed by Ted Kuo.Sack TCP This agent implements selective repe<strong>at</strong>, based on selective ACKs provided by the receiver. It follows the ACKscheme described in [23], <strong>and</strong> was developed with M<strong>at</strong>t M<strong>at</strong>his <strong>and</strong> Jamshid Mahdavi.Fack TCP This agent implements “forward ACK” TCP, a modific<strong>at</strong>ion of Sack TCP described in [22].34.2 TCP Receivers (sinks)<strong>The</strong> TCP senders described above represent one-way d<strong>at</strong>a senders. <strong>The</strong>y must peer with a “TCP sink” object.291


34.2.1 <strong>The</strong> Base TCP Sink<strong>The</strong> base TCP sink object (Agent/TCPSink) is respo<strong>ns</strong>ible for returning ACKs to a peer TCP source object. It gener<strong>at</strong>esone ACK per packet received. <strong>The</strong> size of the ACKs may be configured. <strong>The</strong> cre<strong>at</strong>ion <strong>and</strong> configur<strong>at</strong>ion of the TCP sinkobject is generally performed autom<strong>at</strong>ically by a library call (see cre<strong>at</strong>e-connection above).configur<strong>at</strong>ion parametersAgent/TCPSink set packetSize_ 4034.2.2 Delayed-ACK TCP SinkA delayed-ACK sink object (Agent/Agent/TCPSink/DelAck) is available for simul<strong>at</strong>ing a TCP receiver th<strong>at</strong> ACKsless than once per packet received. This object contai<strong>ns</strong> a bound variable interval_ which gives the number of seconds towait between ACKs. <strong>The</strong> delayed ACK sink implements an agressive ACK policy whereby only ACKs for in-order packetsare delayed. Out-of-order packets cause immedi<strong>at</strong>e ACK gener<strong>at</strong>ion.configur<strong>at</strong>ion parametersAgent/TCPSink/DelAck set interval_ 100ms34.2.3 Sack TCP Sink<strong>The</strong> selective-acknowledgment TCP sink (Agent/TCPSink/Sack1) implements SACK gener<strong>at</strong>ion modeled after the descriptionof SACK in RFC 2018. This object includes a bound variable maxSackBlocks_ which gives the maximumnumber of blocks of inform<strong>at</strong>ion in an ACK available for holding SACK inform<strong>at</strong>ion. <strong>The</strong> default value for this variable is 3,in accordance with the expected use of SACK with RTTM (see RFC 2018, section 3). Delayed <strong>and</strong> selective ACKs togetherare implemented by an object of type Agent/TCPSink/Sack1/DelAck.configur<strong>at</strong>ion parametersAgent/TCPSink set maxSackBlocks_ 334.3 Two-Way TCP Agents (FullTcp)<strong>The</strong> Agent/TCP/FullTcp object is a new addition to the suite of TCP agents supported in the simul<strong>at</strong>or <strong>and</strong> is still underdevelopment. It is different from (<strong>and</strong> incomp<strong>at</strong>ible with) the other agents, but does use some of the same architecture. Itdiffers from these agents in the following ways: following ways:• connectio<strong>ns</strong> may be establised <strong>and</strong> town down (SYN/FIN packets are exchanged)• bidirectional d<strong>at</strong>a tra<strong>ns</strong>fer is supported292


• sequence numbers are in bytes r<strong>at</strong>her than packets<strong>The</strong> gener<strong>at</strong>ion of SYN packets (<strong>and</strong> their ACKs) can be of critical importance in trying to model real-world behavior whenusing many very short d<strong>at</strong>a tra<strong>ns</strong>fers. This version of TCP currently defaults to sending d<strong>at</strong>a on the 3rd segment of an initial 3-way h<strong>and</strong>shake, a behavior somewh<strong>at</strong> different than common real-world TCP implement<strong>at</strong>io<strong>ns</strong>. A “typical” TCP connectionproceeds with an active opener sending a SYN, the passive opener responding with a SYN+ACK, the active opener respondingwith an ACK, <strong>and</strong> then some time l<strong>at</strong>er sending the first segment with d<strong>at</strong>a (corresponding to the first applic<strong>at</strong>ion write). Thus,this version of TCP sends d<strong>at</strong>a <strong>at</strong> a time somewh<strong>at</strong> earlier than typical implement<strong>at</strong>io<strong>ns</strong>. This TCP can also be configured tosend d<strong>at</strong>a on the initial SYN segment. Future changes to FullTCP may include a modific<strong>at</strong>ion to send the first d<strong>at</strong>a segmentl<strong>at</strong>er, <strong>and</strong> possibly to implement T/TCP functionality.Currently FullTCP is only implemented with Reno congestion control, but ultim<strong>at</strong>ely it should be available with the full rangeof congestion control algorithms (e.g., Tahoe, SACK, Vegas, etc.).34.3.1 Simple Configur<strong>at</strong>ionRunning an Full TCP simul<strong>at</strong>ion requires cre<strong>at</strong>ing <strong>and</strong> configuring the agent, <strong>at</strong>taching an applic<strong>at</strong>ion-level d<strong>at</strong>a source (<strong>at</strong>raffic gener<strong>at</strong>or), <strong>and</strong> starting the agent <strong>and</strong> the traffic gener<strong>at</strong>or.Cre<strong>at</strong>ing the Agent# set up connection (do not use "cre<strong>at</strong>e-connection" method because# we need a h<strong>and</strong>le on the sink object)set src [new Agent/TCP/FullTcp]set sink [new Agent/TCP/FullTcp]$<strong>ns</strong>_ <strong>at</strong>tach-agent $node_(s1) $src$<strong>ns</strong>_ <strong>at</strong>tach-agent $node_(k1) $sink$src set fid_ 0$sink set fid_ 0$<strong>ns</strong>_ connect $src $sink# set up TCP-level connectio<strong>ns</strong>$sink listen$src set window_ 100;;# cre<strong>at</strong>e agent;# cre<strong>at</strong>e agent;# bind src to node;# bind sink to node;# set flow ID field;# set flow ID field;# active connection src to sink;# will figure out who its peer is<strong>The</strong> cre<strong>at</strong>ion of the FullTcp agent is similar to the other agents, but the sink is placed in a listening st<strong>at</strong>e by the listenmethod. Because a h<strong>and</strong>le to the receiving side is required in order to make this call, the cre<strong>at</strong>e-connection call usedabove cannot be used.Configur<strong>at</strong>ion Parameters<strong>The</strong> following configur<strong>at</strong>ion parameters are available through Tcl for the FullTcp agent:Agent/TCP/FullTcp set segsperack_ 1Agent/TCP/FullTcp set segsize_ 536Agent/TCP/FullTcp set tcprexmtthresh_ 3Agent/TCP/FullTcp set iss_ 0Agent/TCP/FullTcp set nodelay_ falseAgent/TCP/FullTcp set d<strong>at</strong>a_on_syn_ false;# segs received before gener<strong>at</strong>ing ACK;# segment size (MSS size for bulk xfers);# dupACKs thresh to trigger fast rexmt;# initial send sequence number;# disable sender-side Nagle algorithm;# send d<strong>at</strong>a on initial SYN?293


Agent/TCP/FullTcp set dupseg_fix_ true;# avoid fast rxt due to dup segs+acksAgent/TCP/FullTcp set dupack_reset_ false ;# reset dupACK ctr on !0 len d<strong>at</strong>a segs containing dup ACKsAgent/TCP/FullTcp set interval_ 0.1;# as in TCP above, (100ms is non-std)34.3.2 BayFullTcpA different implement<strong>at</strong>ion of two-way TCP has been ported into <strong>ns</strong> from K<strong>at</strong>hy Nicholes/Van Jacobson’s group. It is calledBayFullTcp. <strong>The</strong> basic difference between BayFullTcp <strong>and</strong> FullTcp (the two-way tcp version already present in <strong>ns</strong>) are asfollows:• BayTcp supports a client-server applic<strong>at</strong>ion model while FullTcp makes no assumption about its applic<strong>at</strong>ion layer.• <strong>The</strong> tcp-applic<strong>at</strong>ion interface is different for both;• FullTcp supports partial ack (BayTcp doesn’t).• FullTcp supports different flavors of tcp (tahoe, reno etc) which is not the case for baytcp.• Both implement<strong>at</strong>io<strong>ns</strong> have different set of API’s .<strong>The</strong>re might be other finer differences between the two as well. One of our future pla<strong>ns</strong> is to redefine the APIs to allow fulltcpto use baytcp’s client-server model.34.4 Architecture <strong>and</strong> Internals<strong>The</strong> base TCP agent (class Agent/TCP) is co<strong>ns</strong>tructed as a collection of routines for sending packets, processing ACKs,managing the send window, <strong>and</strong> h<strong>and</strong>ling timeouts. Generally, each of these routines may be over-ridden by a function withthe same name in a derived class (this is how many of the TCP sender variants are implemented).<strong>The</strong> TCP header <strong>The</strong> TCP header is defined by the hdr_tcp structure in the file ~<strong>ns</strong>/tcp.h. <strong>The</strong> base agent only makesuse of the following subset of the fields:ts_ /* current time packet was sent from source */ts_echo_ /* for ACKs: timestamp field from packet associ<strong>at</strong>ed with this ACK */seqno_ /* sequence number for this d<strong>at</strong>a segment or ACK (Note: overloading!) */reason_ /* set by sender when (re)tra<strong>ns</strong>mitting to trace reason for send */Functio<strong>ns</strong> for Sending D<strong>at</strong>aNote th<strong>at</strong> generally the sending TCP never actually sends d<strong>at</strong>a (it only sets the packet size).send_much(force, reason, maxburst) - this function <strong>at</strong>tempts to send as many packets as the current sent window allows. Italso keeps track of how many packets it has sent, <strong>and</strong> limits to the total to maxburst.<strong>The</strong> function output(seqno, reason) sends one packet with the given sequence number <strong>and</strong> upd<strong>at</strong>es the maximumsent sequence number variable (maxseq_) to hold the given sequence number if it is the gre<strong>at</strong>est sent so far. This functionalso assig<strong>ns</strong> the various fields in the TCP header (sequence number, timestamp, reason for tra<strong>ns</strong>mission). This function alsosets a retra<strong>ns</strong>mission timer if one is not already pending.294


Functio<strong>ns</strong> for Window Management <strong>The</strong> usable send window <strong>at</strong> any time is given by the function window(). It retur<strong>ns</strong>the minimum of the congestion window <strong>and</strong> the variable wnd_, which represents the receiver’s advertised window.opencwnd() - this function ope<strong>ns</strong> the congestion window. It is invoked when a new ACK arrives. When in slow-start,the function merely increments cwnd_ by each ACK received. When in congestion avoidance, the st<strong>and</strong>ard configur<strong>at</strong>ionincrements cwnd_ by its reciprocal. Other window growth optio<strong>ns</strong> are supported during congestion avoidance, but they areexperimental (<strong>and</strong> not documented; contact Sally Floyd for details).closecwnd(int how) - this function reduces the congestion window. It may be invoked in several ways: when entering fastretra<strong>ns</strong>mit, due to a timer expir<strong>at</strong>ion, or due to a congestion notific<strong>at</strong>ion (ECN bit set). Its argument how indic<strong>at</strong>es how thecongestion window should be reduced. <strong>The</strong> value 0 is used for retra<strong>ns</strong>mission timeouts <strong>and</strong> fast retra<strong>ns</strong>mit in Tahoe TCP. Ittypically causes the TCP to enter slow-start <strong>and</strong> reduce ssthresh_ to half the current window. <strong>The</strong> value 1 is used by RenoTCP for implementing fast recovery (which avoids returning to slow-start). <strong>The</strong> value 2 is used for reducing the windowdue to an ECN indic<strong>at</strong>ion. It resets the congestion window to its initial value (usually causing slow-start), but does not alterssthresh_.Functio<strong>ns</strong> for Processing ACKs recv() - this function is the main reception p<strong>at</strong>h for ACKs. Note th<strong>at</strong> because only onedirection of d<strong>at</strong>a flow is in use, this function should only ever be invoked with a pure ACK packet (i.e. no d<strong>at</strong>a). <strong>The</strong> functio<strong>ns</strong>tores the timestamp from the ACK in ts_peer_, <strong>and</strong> checks for the presence of the ECN bit (reducing the send windowif appropri<strong>at</strong>e). If the ACK is a new ACK, it calls newack(), <strong>and</strong> otherwise checks to see if it is a duplic<strong>at</strong>e of the last ACKseen. If so, it enters fast retra<strong>ns</strong>mit by closing the window, resetting the retra<strong>ns</strong>mission timer, <strong>and</strong> sending a packet by callingsend_much.newack() - this function processes a “new” ACK (one th<strong>at</strong> contai<strong>ns</strong> an ACK number higher than any seen so far). <strong>The</strong> functio<strong>ns</strong>ets a new retra<strong>ns</strong>mission timer by calling newtimer(), upd<strong>at</strong>es the RTT estim<strong>at</strong>ion by calling rtt_upd<strong>at</strong>e, <strong>and</strong> upd<strong>at</strong>es thehighest <strong>and</strong> last ACK variables.Functio<strong>ns</strong> for Managing the Retra<strong>ns</strong>mission Timer <strong>The</strong>se functio<strong>ns</strong> serve two purposes: estim<strong>at</strong>ing the round-trip time<strong>and</strong> setting the actual retra<strong>ns</strong>mission timer. rtt_init - this function initializes srtt_ <strong>and</strong> rtt_ to zero, sets rttvar_ to3/tcp_tick_, <strong>and</strong> sets the backoff multiplier to one.rtt_timeout - this function gives the timeout value in seconds th<strong>at</strong> should be used to schedule the next retra<strong>ns</strong>mission timer.It computes this based on the current estim<strong>at</strong>es of the mean <strong>and</strong> devi<strong>at</strong>ion of the round-trip time. In addition, it implementsKarn’s exponential timer backoff for multiple co<strong>ns</strong>ecutive retra<strong>ns</strong>mission timeouts.rtt_upd<strong>at</strong>e - this function takes as argument the measured RTT <strong>and</strong> averages it in to the running mean <strong>and</strong> devi<strong>at</strong>ion estim<strong>at</strong>orsaccording to the description above. Note th<strong>at</strong> t_srtt_ <strong>and</strong> t_rttvar are both stored in fixed-point (integers). <strong>The</strong>y have3 <strong>and</strong> 2 bits, respectively, to the right of the binary point.reset_rtx_timer - This function is invoked during fast retra<strong>ns</strong>mit or during a timeout. It sets a retra<strong>ns</strong>mission timer by callingset_rtx_timer <strong>and</strong> if invoked by a timeout also calls rtt_backoff.rtt_backoff - this function backs off the retra<strong>ns</strong>mission timer (by doubling it).newtimer - this function called only when a new ACK arrives. If the sender’s left window edge is beyond the ACK, the<strong>ns</strong>et_rtx_timer is called, otherwise if a retra<strong>ns</strong>mission timer is pending it is cancelled.295


34.5 Tracing TCP Dynamics<strong>The</strong> behavior of TCP is often observed by co<strong>ns</strong>tructing a sequence number-vs-time plot. Typically, a trace is performed byenabling tracing on a link over which the TCP packets will pass. Two trace methods are supported: the default one (used fortracing TCP agents), <strong>and</strong> an exte<strong>ns</strong>ion used only for FullTcP.34.6 One-Way Trace TCP Trace DynamicsTCP packets gener<strong>at</strong>ed by one of the one-way TCP agents <strong>and</strong> destined for a TCP sink agent passing over a traced link (seesection 26) will gener<strong>at</strong>e a trace file lines of the form:+ 0.94176 2 3 tcp 1000 ------ 0 0.0 3.0 25 40+ 0.94276 2 3 tcp 1000 ------ 0 0.0 3.0 26 41d 0.94276 2 3 tcp 1000 ------ 0 0.0 3.0 26 41+ 0.95072 2 0 ack 40 ------ 0 3.0 0.0 14 29- 0.95072 2 0 ack 40 ------ 0 3.0 0.0 14 29- 0.95176 2 3 tcp 1000 ------ 0 0.0 3.0 21 36+ 0.95176 2 3 tcp 1000 ------ 0 0.0 3.0 27 42<strong>The</strong> exact form<strong>at</strong> of this trace file is given in section 26.4. When tracing TCP, packets of type tcp or ack are relevant. <strong>The</strong>irtype, size, sequence number (ack number for ack packets), <strong>and</strong> arrival/depart/drop time are given by field positio<strong>ns</strong> 5, 6, 11,<strong>and</strong> 2, respectively. <strong>The</strong> + indic<strong>at</strong>es a packet arrival, d a drop, <strong>and</strong> - a departure. A number of scripts process this file toproduce graphical output or st<strong>at</strong>istical summaries (see, for example, ~<strong>ns</strong>/test-suite.tcl, the finish procedure.34.7 One-Way Trace TCP Trace DynamicsTCP packets gener<strong>at</strong>ed by FullTcp <strong>and</strong> passing over a traced link contain additional inform<strong>at</strong>ion not displayed by defaultusing the regular trace object. By enabling the flag show_tcphdr_ on the trace object (see section refsec:traceform<strong>at</strong>), 3additional header fields are written to the trace file: ack number, tcp-specific flags, <strong>and</strong> header length.34.8 Comm<strong>and</strong>s <strong>at</strong> a glance<strong>The</strong> following is a list of comm<strong>and</strong>s used to setup/manipul<strong>at</strong>e TCP flows for simul<strong>at</strong>io<strong>ns</strong>:set tcp0 [new Agent/TCP]This cre<strong>at</strong>es an i<strong>ns</strong>tance of a TCP agent. <strong>The</strong>re are several flavors of TCP-sender <strong>and</strong> TCP-receiver (or sink) agent currentlyimplemented in <strong>ns</strong>. TCP-senders currently available are: Agent/TCP, Agent/TCP/Reno, Agent/TCP/Newreno,Agent/TCP/Sack1, Agent/TCP/Vegas, Agent/TCP/Fack.TCP-receivers currently available are: Agent/TCPSink, Agent/TCPSink/DelAck, Agent/TCPSink/Sack1,Agent/TCPSink/Sack1/DelAck.<strong>The</strong>re is also a two-way implement<strong>at</strong>ion of tcp called Agent/TCP/FullTcp. For details on the different TCP flavors see earliersectio<strong>ns</strong> of this chapter.Configur<strong>at</strong>ion parameters for TCP flows maybe set as follows:296


$tcp set window_ For all possible configur<strong>at</strong>ion parameters available for TCP see section 34.1.4. <strong>The</strong> default configur<strong>at</strong>ion values can also befound in <strong>ns</strong>/tcl/lib/<strong>ns</strong>-default.tcl.Following is an example of a simple TCP connection setup:set tcp [new Agent/TCP]$<strong>ns</strong>_ <strong>at</strong>tach-agent $node_(s1) $tcp$tcp set fid_ 0set ftp [new Applic<strong>at</strong>ion/FTP]$ftp <strong>at</strong>tach-agent $tcpset sink [new Agent/TCPSink]$<strong>ns</strong>_ <strong>at</strong>tach-agent $node_(k1) $sink$sink set fid_ 0$<strong>ns</strong>_ connect $ftp $sink$<strong>ns</strong>_ <strong>at</strong> $start-time "$ftp start";# cre<strong>at</strong>e tcp agent;# bind src to node;# set flow ID field;# cre<strong>at</strong>e ftp traffic;# bind ftp traffic to tcp agent;# cre<strong>at</strong>e tcpsink agent;# bind sink to node;# set flow ID field;# active connection src to sink;# start ftp flowFor an example of setting up a full-tcp connection see section 34.3.1.297


Chapter 35SCTP AgentsThis chapter describes the SCTP agents developed for <strong>ns</strong> by the Protocol Engineering <strong>Lab</strong> <strong>at</strong> the University of Delaware.<strong>The</strong> SCTP agents are all two-way agents, which mea<strong>ns</strong> they are symmetric in the se<strong>ns</strong>e th<strong>at</strong> they represent both a sender <strong>and</strong>receiver. However, bi-directional d<strong>at</strong>a has not yet been implemented. Each i<strong>ns</strong>tance of an SCTP agent is either a sender orreceiver.<strong>The</strong> SCTP agents are implemented in files m<strong>at</strong>ching the regular expression ~<strong>ns</strong>/sctp/sctp*.{cc, h}.<strong>The</strong> SCTP agents currently supported are:• Agent/SCTP - RFC2960 + draft-ietf-tsvwg-sctpimpguide-09.txt + draft-ietf-tsvwg-usctp-01.txt• Agent/SCTP/HbAfterRto - experimental exte<strong>ns</strong>ion (HEARTBEAT after RTO)• Agent/SCTP/MultipleFastRtx - experimental exte<strong>ns</strong>ion (UD PEL’s Multiple Fast Retra<strong>ns</strong>mit algorithm)• Agent/SCTP/Timestamp - experimental exte<strong>ns</strong>ion (TIMESTAMP chunk)• Agent/SCTP/MfrHbAfterRto - experimental exte<strong>ns</strong>ion th<strong>at</strong> combines MultipleFastRtx <strong>and</strong> HbAfterRto• Agent/SCTP/MfrTimestamp - experimental exte<strong>ns</strong>ion th<strong>at</strong> combines MultipleFastRtx <strong>and</strong> TimestampSection 35.1 provides a simple overview of the base SCTP agent with details of configur<strong>at</strong>ion parameters <strong>and</strong> comm<strong>and</strong>s.Section 35.2 describes the SCTP exte<strong>ns</strong>io<strong>ns</strong> available. <strong>The</strong> details of the SCTP trace form<strong>at</strong> used in packet trace files areexplained in Section 35.3. Section 35.4 explai<strong>ns</strong> how to use legacy applic<strong>at</strong>io<strong>ns</strong> with SCTP <strong>and</strong> how to write SCTP-aware applic<strong>at</strong>io<strong>ns</strong>which exploit all SCTP’s fe<strong>at</strong>ures. Section 35.5 provides examples scripts for both singled homed <strong>and</strong> multihomedendpoints.35.1 <strong>The</strong> Base SCTP Agent<strong>The</strong> base SCTP agent Agent/SCTP supports the fe<strong>at</strong>ures in the following sectio<strong>ns</strong> of RFC2960, including modific<strong>at</strong>io<strong>ns</strong> upto draft-ietf-tsvwg-sctpimpguide-13.txt.5.1 Normal Establishment of an Associ<strong>at</strong>ion (rudimentary h<strong>and</strong>shake)6.1 Tra<strong>ns</strong>mission of DATA Chunks298


6.2 Acknowledgment on Reception of DATA Chunks6.3 Management Retra<strong>ns</strong>mission Timer6.4 Multihomed SCTP Endpoints6.5 Stream Identifier <strong>and</strong> Stream Sequence Number6.6 Ordered <strong>and</strong> Unordered Delivery6.7 Report Gaps in Received DATA TSNs7.2 SCTP Slow-Start <strong>and</strong> Congestion Avoidance8.1 Endpoint Failure Detection8.2 P<strong>at</strong>h Failure Detection8.3 P<strong>at</strong>h Heartbe<strong>at</strong> (without upper layer control)This agent also supports the Partial Reliability exte<strong>ns</strong>ion as of draft-ietf-tsvwg-usctp-01.txt.Associ<strong>at</strong>ion Establishment <strong>The</strong> SCTP agent establishes an associ<strong>at</strong>ion using a four-way h<strong>and</strong>shake, but the h<strong>and</strong>shake iskept simple <strong>and</strong> does not strictly conform to RFC2960. <strong>The</strong> h<strong>and</strong>shake does not exchange tags, <strong>and</strong> the INIT <strong>and</strong> COOKIE-ECHO chunks are not used to upd<strong>at</strong>e the RTT. I<strong>ns</strong>tead, RTT estim<strong>at</strong>ion begin with the first DATA chunk.Associ<strong>at</strong>ion Shutdown Currently, the SCTP agent does not perform a proper shutdown. <strong>The</strong> associ<strong>at</strong>ion is abruptly termin<strong>at</strong>edwhen the simul<strong>at</strong>ed connection ends. A shutdown procedure may be added in a future release.Multihoming <strong>The</strong> underlying infrastructure of <strong>ns</strong>-2 does not support multiple interfaces for a single node. To get aroundthis limit<strong>at</strong>ion, our approach allows the general support for logically multihoming nodes th<strong>at</strong> have a multihomed tra<strong>ns</strong>portlayer, such as SCTP. Each multihomed node is actually made up of more than one node. As shown in Figure 35.1, a logicallymultihomed node is made up of a single "core node" <strong>and</strong> multiple "interface nodes", one for each simul<strong>at</strong>ed interface. <strong>The</strong>core node is connected to each interface node via a uni-directional link towards the interface node, but traffic never traversesthese links. <strong>The</strong>se links are only in place for the core node to make routing decisio<strong>ns</strong>. An SCTP agent simultaneously resideson all these nodes (i.e., the core <strong>and</strong> interface nodes), but actual traffic only goes to/from the interface nodes. Whenever theSCTP agent needs to send d<strong>at</strong>a to a destin<strong>at</strong>ion <strong>and</strong> does not know which outgoing interface to use, the agent firsts co<strong>ns</strong>ultswith the core node for a route lookup. <strong>The</strong>n, the SCTP agent performs the send from the appropri<strong>at</strong>e interface node. Incomingd<strong>at</strong>a is received <strong>at</strong> one of the interface nodes directly <strong>and</strong> passed up to the SCTP agent. This solution is applicable to anytra<strong>ns</strong>port protocol th<strong>at</strong> requires multihoming functionality in <strong>ns</strong>-2. Note: the user must configure multihomed nodes usingcomm<strong>and</strong>s in Section 35.1.2 (an example is shown in Section 35.5.2).Packet Number vs TSN Numbering While <strong>ns</strong> starts numbering packets <strong>at</strong> 0, the SCTP module starts numbering DATAchunk TSNs <strong>at</strong> 1 <strong>and</strong> assig<strong>ns</strong> undefined TSN values (-1) to control chunks (ie, INIT, SACK, HEARTBEAT, etc). <strong>The</strong> fourpackets exchanged during the associ<strong>at</strong>ion establishment are counted in the packet enumer<strong>at</strong>ion, but do not show up in graphs.This inform<strong>at</strong>ion is important when doing things like specifying a drop list for the ErrorModel object. For example, packet2 actually refers to the first SCTP packet with DATA chunk(s).35.1.1 Configur<strong>at</strong>ion ParametersSCTP supports several configur<strong>at</strong>ion variables which are TCL bindable. Each of the variables described in this subsection isboth a class variable <strong>and</strong> an i<strong>ns</strong>tance variable. Changing the class variable changes the default value for all agents th<strong>at</strong> are299


Figure 35.1: Example of a Multihomed Nodecre<strong>at</strong>ed subsequently. Changing the i<strong>ns</strong>tance variable of a particular agent only affects the values used by th<strong>at</strong> agent. Forexample,Agent/SCTP set p<strong>at</strong>hMaxRetra<strong>ns</strong>_ 5$sctp set p<strong>at</strong>hMaxRetra<strong>ns</strong>_ 5;# Changes the class variable;# Changes p<strong>at</strong>hMaxRetra<strong>ns</strong>_ for the $sctp object only<strong>The</strong> default parameters for each SCTP agent are:Agent/SCTP set debugMask_ 0 ;# 32-bit mask for modular toggle debugging control (see explan<strong>at</strong>ion)Agent/SCTP set debugFileIndex_ -1;# specifies debugging output file (see explan<strong>at</strong>ion)Agent/SCTP set associ<strong>at</strong>ionMaxRetra<strong>ns</strong>_ 10;# RFC2960’s Associ<strong>at</strong>ion.Max.Retra<strong>ns</strong>Agent/SCTP set p<strong>at</strong>hMaxRetra<strong>ns</strong>_ 5;# RFC2960’s P<strong>at</strong>h.Max.Retra<strong>ns</strong>Agent/SCTP set changePrimaryThresh_ -1 ;# change primary if error count exeeds thresh (default infinite)Agent/SCTP set maxInitRetra<strong>ns</strong>mits_ 8;# RFC2960’s Max.Init.Retra<strong>ns</strong>mitsAgent/SCTP set oneHeartbe<strong>at</strong>Timer_ 1;# toggle HB timer for each dest vs one for all destsAgent/SCTP set heartbe<strong>at</strong>Interval_ 30;# RFC2960’s HB.interval in secondsAgent/SCTP set mtu_ 1500;# MTU in bytes including IP headerAgent/SCTP set initialRwnd_ 65536;# initial receiver window in bytes (set on receiver side)Agent/SCTP set initialSsthresh_ 65536;# initial ssthresh value in bytesAgent/SCTP set initialCwnd_ 2;# initial cwnd in multiple of (MTU - SCTP/IP headers)Agent/SCTP set initialRto_ 3.0;# default initial RTO = 3 secsAgent/SCTP set minRto_ 1.0;# default min RTO = 1 secAgent/SCTP set maxRto_ 60.0;# default max RTO = 60 secsAgent/SCTP set fastRtxTrigger_ 4;# 4 missing reports trigger fast rtxAgent/SCTP set numOutStreams_ 1;# number of outgoing streamsAgent/SCTP set numUnrelStreams_ 0 ;# number of partially reliable streams (all grouped starting <strong>at</strong> stream 0)Agent/SCTP set reliability_ 0;# k-rtx value of all partially reliable streamsAgent/SCTP set unordered_ 0;# toggle all chunks are ordered/unorderedAgent/SCTP set ipHeaderSize_ 20;# IP header sizeAgent/SCTP set d<strong>at</strong>aChunkSize_ 1468 ;# includes d<strong>at</strong>a chunk header <strong>and</strong> restricted to 4 byte boundaries300


Agent/SCTP set useDelayedSacks_ 1 ;# toggle on/off delayed sack algorithm (set on receiver side)Agent/SCTP set sackDelay_ 0.200;# rfc2960 recommends 200 msAgent/SCTP set useMaxBurst_ 1;# toggle on/off max burstAgent/SCTP set rtxToAlt_ 1 ;# rtxs to which dest? 0 = same, 1 = alt, 2 = fast rtx to same + timeouts to altAgent/SCTP set dormantAction_ 0 ;# 0 = change dest, 1 = use primary, 2 = use last dest before dormantAgent/SCTP set routeCalcDelay_ 0;# time to calcul<strong>at</strong>e a route (see explan<strong>at</strong>ion)Agent/SCTP set routeCacheLifetime_ 1.2 ;# how long a route remai<strong>ns</strong> cached (see explan<strong>at</strong>ion)Agent/SCTP set trace_all_ 0;# toggle on/off print all variables on a trace event<strong>The</strong> debugMask_ parameter is a 32-bit mask to turn on/off debugging for particular functio<strong>ns</strong>. See ~<strong>ns</strong>/sctp/sctpDebug.hfor the mappings of the bitmask. A -1 may be used to clear all bits, <strong>and</strong> 0 is used to turn off all debugging. If debug_ (thest<strong>and</strong>ard <strong>ns</strong> debug flag) is set to 1, then all the bits in debugMask_ are set. Note: <strong>ns</strong> must be compiled with -DDEBUG forthis option to work.<strong>The</strong> debugFileIndex_ parameter is an integer to specify the file used for debugging output by an SCTP agent. Eachi<strong>ns</strong>tance of an SCTP agent can independently output debugging info to a separ<strong>at</strong>e file. For example, the d<strong>at</strong>a sender can logdebugging output to one file, while the receiver logs to another file. If debugFileIndex_ is set to 0, the file used will benamed debug.SctpAgent.0. If -1 is used, the debug output is sent to stderr. To avoid confusion, two SCTP agents should notsend debug output to the same file. <strong>The</strong> default is -1. Note: <strong>ns</strong> must be compiled with -DDEBUG for this option to work.<strong>The</strong> configur<strong>at</strong>ion parameters th<strong>at</strong> deal with ordering <strong>and</strong> reliability optio<strong>ns</strong> may be overridden by an SCTP-aware applic<strong>at</strong>ion(see Section 35.4).<strong>The</strong> routeCalcDelay_ <strong>and</strong> routeCacheLifetime_ parameters are only used to optionally simul<strong>at</strong>e overheads ofreactive routing protocols in MANETs without actually simul<strong>at</strong>ing a MANET. (Do not use this fe<strong>at</strong>ure if you are actuallysimul<strong>at</strong>ing a MANET!) <strong>The</strong> default setting for routeCalcDelay_ is 0 seconds, which mea<strong>ns</strong> th<strong>at</strong> this fe<strong>at</strong>ure is turnedoff. <strong>The</strong> default setting for routeCacheLifetime_ is 1.2 seconds (ignored if this fe<strong>at</strong>ure is turned off), which is purposelyset slightly larger than the default min RTO to avoid a “cache miss” after a single timeout event.35.1.2 Comm<strong>and</strong>sSCTP provides certain comm<strong>and</strong>s th<strong>at</strong> can be used within TCL scripts:trace Tracks given variables. <strong>The</strong> variable (<strong>and</strong> associ<strong>at</strong>ed inform<strong>at</strong>ion) is printed every time the value changes. Takes 1argument:cwnd_ Used to trace the cwnds of all p<strong>at</strong>hs.rto_ Used to trace the RTOs of all p<strong>at</strong>hs.errorCount_ Used to trace the error counters of all p<strong>at</strong>hs.frCount_ Used to trace the number of times a fast retra<strong>ns</strong>mit is invoked.mfrCount_ Used to trace the number of times the multiple fast retra<strong>ns</strong>mit algorithm is invoked. This trace variablecan only be used with the MultipleFastRtx exte<strong>ns</strong>ion agent. (See Section 35.2.2)timeoutCount_ Used to trace the total number of times a timeout has occurred on all p<strong>at</strong>hs.rcdCount_ Used to trace the total number of times a route calcul<strong>at</strong>ion delay (see Section 35.1.1) has occurred on allp<strong>at</strong>hs.301


Note: the actual value of these trace variables have no meaning. <strong>The</strong>y are simply used to trace corresponding variables forpotentially multihomed endpoints. For example, if a sender’s peer endpoint has two destin<strong>at</strong>io<strong>ns</strong>, the sender will maintaintwo cwnds. <strong>The</strong> cwnd_ trace variable will trace both of these cwnds together.print Provides the sampling method of tracing. This comm<strong>and</strong> simply prints a given variable (<strong>and</strong> associ<strong>at</strong>ed inform<strong>at</strong>ion)per call. Takes 1 argument: one of the trace variables presented above.set-multihome-core Sets the core node for multihomed endpoints. Takes 1 argument of type node. M<strong>and</strong><strong>at</strong>ory for multihomedendpoints <strong>and</strong> must not be set more than once per endpoint.multihome-add-interface Adds an interface to a multihomed endpoint. Takes 2 arguments of type node. Argument 1 is thecore node of the multihomed endpoint. Argument 2 is the interface node to be added. M<strong>and</strong><strong>at</strong>ory for multihomed endpoints.All interfaces must be added after set-multihome-core is called <strong>and</strong> before multihome-<strong>at</strong>tach-agent is called.multihome-<strong>at</strong>tach-agent Attaches an SCTP agent to a multihomed endpoint. Takes 2 arguments. Argument 1 is the corenode. Argument 2 is the SCTP agent. M<strong>and</strong><strong>at</strong>ory for multihomed endpoints.set-primary-destin<strong>at</strong>ion Sets the interface node of the peer endpoint as the primary destin<strong>at</strong>ion. Takes 1 argument of typenode. Optional <strong>and</strong> may be set more than once per endpoint. If not used, a primary destin<strong>at</strong>ion is chosen autom<strong>at</strong>ically.force-source Sets the interface node th<strong>at</strong> packets will be sent from. Takes 1 argument of type node. Optional <strong>and</strong> may beset more than once per endpoint. If not used, routing will autom<strong>at</strong>ically choose the source on a per packet basis.35.2 Exte<strong>ns</strong>io<strong>ns</strong>35.2.1 HbAfterRto SCTP<strong>The</strong> HbAfterRto SCTP agent extends the current retra<strong>ns</strong>mission policy. In addition to SCTP’s current policy of retra<strong>ns</strong>mittingto an altern<strong>at</strong>e destin<strong>at</strong>ion on a timeout, a heartbe<strong>at</strong> is sent immedi<strong>at</strong>ely to the destin<strong>at</strong>ion on which a timeout occurred. Extraheartbe<strong>at</strong>s provide a mechanism for a sender to upd<strong>at</strong>e an altern<strong>at</strong>e destin<strong>at</strong>ion’s RTT estim<strong>at</strong>e more frequently, thus resultingin a better RTT estim<strong>at</strong>e on which to base the RTO value.For example, suppose a packet is lost in tra<strong>ns</strong>it to the primary destin<strong>at</strong>ion, <strong>and</strong> l<strong>at</strong>er gets retra<strong>ns</strong>mitted to an altern<strong>at</strong>e destin<strong>at</strong>ion.Also suppose th<strong>at</strong> the retra<strong>ns</strong>mission times out. <strong>The</strong> lost packet is retra<strong>ns</strong>mitted again to yet another altern<strong>at</strong>e destin<strong>at</strong>ion(if one exists; otherwise, the primary). More importantly, a heartbe<strong>at</strong> is also sent to the altern<strong>at</strong>e destin<strong>at</strong>ion which timed out.If the heartbe<strong>at</strong> is successfully acked, th<strong>at</strong> destin<strong>at</strong>ion acquires an additional RTT measurement to help reduce its recentlydoubled RTO [?].35.2.2 MultipleFastRtx SCTP<strong>The</strong> MultipleFastRtx SCTP agent <strong>at</strong>tempts to minimize the number of timeouts which occur. Without the Multiple Fast Retra<strong>ns</strong>mitalgorithm, SCTP may only Fast Retra<strong>ns</strong>mit a TSN once. If a Fast Retra<strong>ns</strong>mitted TSN is lost, a timeout is necessary302


to retra<strong>ns</strong>mit the TSN again. <strong>The</strong> Multiple Fast Retra<strong>ns</strong>mit algorithm allows the same TSN to be Fast Retra<strong>ns</strong>mitted severaltimes if needed. Without the Multiple Fast Retra<strong>ns</strong>mit algorithm, a large window of outst<strong>and</strong>ing d<strong>at</strong>a may gener<strong>at</strong>e enoughSACKs to incorrectly trigger more than one Fast Retra<strong>ns</strong>mit of the same TSN in a single RTT. To avoid these spurious FastRetra<strong>ns</strong>mits, the Multiple Fast Retra<strong>ns</strong>mit algorithm introduces a fastRtxRecover st<strong>at</strong>e variable for each TSN Fast Retra<strong>ns</strong>mitted.This variable stores the highest outst<strong>and</strong>ing TSN <strong>at</strong> the time a TSN is Fast Retra<strong>ns</strong>mitted. <strong>The</strong>n, only SACKs whichnewly ack TSNs beyond fastRtxRecover can increment the missing report for the Fast Retra<strong>ns</strong>mitted TSN. If the missingreport threshold for the Fast Retra<strong>ns</strong>mitted TSN is reached again, the sender has enough evidence th<strong>at</strong> this TSN was lost <strong>and</strong>can be Fast Retra<strong>ns</strong>mitted again [?].35.2.3 Timestamp SCTP<strong>The</strong> Timestamp SCTP agent introduces timestamps into each packet, thus allowing a sender to disambigu<strong>at</strong>e original tra<strong>ns</strong>missio<strong>ns</strong>from retra<strong>ns</strong>missio<strong>ns</strong>. By removing retra<strong>ns</strong>mission ambiguity, Karn’s algorithm can be elimin<strong>at</strong>ed, <strong>and</strong> successfulretra<strong>ns</strong>missio<strong>ns</strong> on the altern<strong>at</strong>e p<strong>at</strong>h can be used to upd<strong>at</strong>e the RTT estim<strong>at</strong>e <strong>and</strong> keep the RTO value more accur<strong>at</strong>e. Withtimestamps, the sender has more samples for upd<strong>at</strong>ing the RTT estim<strong>at</strong>e of altern<strong>at</strong>e destin<strong>at</strong>ion(s) [?].35.2.4 MfrHbAfterRto SCTP<strong>The</strong> MfrHbAfterRto SCTP agent combines the functionality of the HbAfterRto <strong>and</strong> MultipleFastRtx SCTP agents.35.2.5 MfrHbAfterRto SCTP<strong>The</strong> MfrTimestamp SCTP agent combines the functionality of the Timestamp <strong>and</strong> MultipleFastRtx SCTP agents.35.3 Tracing SCTP DynamicsSCTP packets gener<strong>at</strong>ed by one of the SCTP agents <strong>and</strong> destined for a peer SCTP agent over a traced link (see section 26)will gener<strong>at</strong>e a trace file with lines of the form:+ 0.5 1 4 sctp 56 -------I 0 1.0 4.0 1 -1 4 65535 65535- 0.5 1 4 sctp 56 -------I 0 1.0 4.0 1 -1 4 65535 65535r 0.700896 1 4 sctp 56 -------I 0 1.0 4.0 1 -1 4 65535 65535+ 0.700896 4 1 sctp 56 -------I 0 4.0 1.0 1 -1 5 65535 65535- 0.700896 4 1 sctp 56 -------I 0 4.0 1.0 1 -1 5 65535 65535r 0.901792 4 1 sctp 56 -------I 0 4.0 1.0 1 -1 5 65535 65535+ 0.901792 1 4 sctp 36 -------I 0 1.0 4.0 1 -1 6 65535 65535- 0.901792 1 4 sctp 36 -------I 0 1.0 4.0 1 -1 6 65535 65535r 1.102368 1 4 sctp 36 -------I 0 1.0 4.0 1 -1 6 65535 65535+ 1.102368 4 1 sctp 36 -------I 0 4.0 1.0 1 -1 7 65535 65535- 1.102368 4 1 sctp 36 -------I 0 4.0 1.0 1 -1 7 65535 65535r 1.302944 4 1 sctp 36 -------I 0 4.0 1.0 1 -1 7 65535 65535+ 1.302944 1 4 sctp 1500 -------D 0 1.0 4.0 1 1 8 0 0- 1.302944 1 4 sctp 1500 -------D 0 1.0 4.0 1 1 8 0 0+ 1.302944 1 4 sctp 1500 -------D 0 1.0 4.0 1 2 9 0 1- 1.326624 1 4 sctp 1500 -------D 0 1.0 4.0 1 2 9 0 1303


1.526624 1 4 sctp 1500 -------D 0 1.0 4.0 1 1 8 0 0r 1.550304 1 4 sctp 1500 -------D 0 1.0 4.0 1 2 9 0 1+ 1.550304 4 1 sctp 48 -------S 0 4.0 1.0 1 2 11 65535 65535- 1.550304 4 1 sctp 48 -------S 0 4.0 1.0 1 2 11 65535 65535r 1.751072 4 1 sctp 48 -------S 0 4.0 1.0 1 2 11 65535 65535...+ 19.302944 4 1 sctp 56 -------H 0 2.0 5.0 1 -1 336 65535 65535- 19.302944 4 1 sctp 56 -------H 0 2.0 5.0 1 -1 336 65535 65535r 19.303264 4 1 sctp 56 -------H 0 4.0 1.0 1 -1 322 65535 65535+ 19.303264 1 4 sctp 56 -------B 0 1.0 4.0 1 -1 337 65535 65535- 19.327584 1 4 sctp 56 -------B 0 1.0 4.0 1 -1 337 65535 65535r 19.52848 1 4 sctp 56 -------B 0 1.0 4.0 1 -1 337 65535 65535When tracing SCTP, packets of type sctp are relevant. <strong>The</strong>ir packet type, chunk type, packet size, TSN (CumAck point forSACK chunks), stream ID, SSN, <strong>and</strong> arrival/depart/drop time are given by field positio<strong>ns</strong> 5, 7 (flag position 8), 6, 12, 14, 15,<strong>and</strong> 2, respectively. If a packet has more than one chunk, a line is printed for each chunk. A future release should include afield to indic<strong>at</strong>e which chunk of the packet a line refers to (e.g., 2:3 could identify the 2nd chunk of a packet which contai<strong>ns</strong> 3chunks). Since control chunks do not use TSNs, stream IDs, or SSNs, the trace lines for these chunks use undefined numbers(-1 or 65535) for these fields. <strong>The</strong> + indic<strong>at</strong>es a packet arrival, d a drop, <strong>and</strong> - a departure.Flag position 8 of field 7 indic<strong>at</strong>e the chunk type as follows. <strong>The</strong> I flag indic<strong>at</strong>es an associ<strong>at</strong>ion initi<strong>at</strong>ion control chunk (INIT,INIT-ACK, COOKIE-ECHO, COOKIE-ACK). A future release should use I for the INIT <strong>and</strong> INIT-ACK chunks, <strong>and</strong> C forthe COOKIE-ECHO <strong>and</strong> COOKIE-ACK chunks. <strong>The</strong> D, S, H, <strong>and</strong> B flags indic<strong>at</strong>e a DATA chunk, a SACK, a HEARTBEATchunk, <strong>and</strong> a HEARTBEAT-ACK chunk.A number of scripts process this file to produce graphical output or st<strong>at</strong>istical summaries (for example, see the finishprocedure in ~<strong>ns</strong>/tcl/test/test-suite-sctp.tcl).35.4 SCTP Applic<strong>at</strong>io<strong>ns</strong>SCTP supports legacy <strong>ns</strong> applic<strong>at</strong>io<strong>ns</strong>, but they obviously cannot completely exploit all SCTP’s fe<strong>at</strong>ures. For these applic<strong>at</strong>io<strong>ns</strong>,the TCL-bound SCTP configur<strong>at</strong>ion parameters can be used to set reliability <strong>and</strong> ordering optio<strong>ns</strong>. However, theseoptio<strong>ns</strong> cannot be controlled per message using these parameters. Only SCTP-aware applic<strong>at</strong>ion can be written to do so.<strong>ns</strong> applic<strong>at</strong>io<strong>ns</strong> wishing to become SCTP-aware can use the sendmsg API as follows (see ~<strong>ns</strong>/apps/sctp_app1.{cc, h} as anexample).1. Cre<strong>at</strong>e <strong>and</strong> fill an i<strong>ns</strong>tance of the AppD<strong>at</strong>a_S structure (see ~<strong>ns</strong>/sctp/sctp.h). <strong>The</strong> AppD<strong>at</strong>a_S structure has thefollowing fields:usNumStreams is the number of outgoing streams to setup during negoti<strong>at</strong>ion. Although this field is passedwith every sendmsg call, it is only used during associ<strong>at</strong>ion setup. Once the associ<strong>at</strong>ion is established, this field isignored.usNumUnreliable is the number of outgoing streams which are unreliable (now called partially reliable). <strong>The</strong>sender simply sets the lowest outgoing stream to unreliable/partially-reliable; the remaining ones are reliable.This field is also only used during associ<strong>at</strong>ion establishment.usStreamId is the stream ID of a message.usReliability is the reliability level (k-rtx value) of a message. This field is ignored if the message is senton a reliable stream.304


eUnordered is the unordered boolean flag for a message.uiNumBytes is the number of bytes in a message.2. Pass this object as the second parameter in SCTP’s sendmsg:sctpAgent->sendmsg(numBytes, (char *)appD<strong>at</strong>a);35.5 Example Scripts35.5.1 Singled Homed ExampleTrace set show_sctphdr_ 1;# this needs to be set for tracing SCTP packetsset <strong>ns</strong> [new Simul<strong>at</strong>or]set allchan [open all.tr w]$<strong>ns</strong> trace-all $allchanproc finish {exit 0}set n0 [$<strong>ns</strong> node]set n1 [$<strong>ns</strong> node]$<strong>ns</strong> duplex-link $n0 $n1 .5Mb 200ms DropTail# NOTE: <strong>The</strong> debug files (in this example, they would be debug.SctpAgent.0# <strong>and</strong> debug.SctpAgent.1) contain a lot of useful info. <strong>The</strong>y can be# used to trace every packet sent, received, <strong>and</strong> processed.#set sctp0 [new Agent/SCTP]$<strong>ns</strong> <strong>at</strong>tach-agent $n0 $sctp0$sctp0 set debugMask_ 0x00303000;# refer to sctpDebug.h for mask mappings$sctp0 set debugFileIndex_ 0set trace_ch [open trace.sctp w]$sctp0 set trace_all_ 0$sctp0 trace cwnd_$sctp0 <strong>at</strong>tach $trace_chset sctp1 [new Agent/SCTP]$<strong>ns</strong> <strong>at</strong>tach-agent $n1 $sctp1$sctp1 set debugMask_ -1$sctp1 set debugFileIndex_ 1;# do not trace all variables on one line;# trace cwnd for all destin<strong>at</strong>io<strong>ns</strong>;# use -1 to turn on all debugging$<strong>ns</strong> connect $sctp0 $sctp1set ftp0 [new Applic<strong>at</strong>ion/FTP]$ftp0 <strong>at</strong>tach-agent $sctp0$<strong>ns</strong> <strong>at</strong> 0.5 "$ftp0 start"$<strong>ns</strong> <strong>at</strong> 4.5 "$ftp0 stop"305


$<strong>ns</strong> <strong>at</strong> 5.0 "finish"$<strong>ns</strong> run35.5.2 Multihomed Example# This example demo<strong>ns</strong>tr<strong>at</strong>es multihoming. Two SCTP endpoints, each# with 2 interfaces, are directly connected between each pair of# interfaces. In the middle of the associ<strong>at</strong>ion, a change primary# is done. Running nam helps to visualize the multihomed# architecture.## host0_if0 O===========O host1_if0# / \# host0_core O O host1_core# \ /# host0_if1 O===========O host1_if1Trace set show_sctphdr_ 1set <strong>ns</strong> [new Simul<strong>at</strong>or]set nf [open sctp.nam w]$<strong>ns</strong> namtrace-all $nfset allchan [open all.tr w]$<strong>ns</strong> trace-all $allchanproc finish {exec nam sctp.nam &exit 0}set host0_core [$<strong>ns</strong> node]set host0_if0 [$<strong>ns</strong> node]set host0_if1 [$<strong>ns</strong> node]$host0_core color Red$host0_if0 color Red$host0_if1 color Red$<strong>ns</strong> multihome-add-interface $host0_core $host0_if0$<strong>ns</strong> multihome-add-interface $host0_core $host0_if1set host1_core [$<strong>ns</strong> node]set host1_if0 [$<strong>ns</strong> node]set host1_if1 [$<strong>ns</strong> node]$host1_core color Blue$host1_if0 color Blue$host1_if1 color Blue$<strong>ns</strong> multihome-add-interface $host1_core $host1_if0$<strong>ns</strong> multihome-add-interface $host1_core $host1_if1$<strong>ns</strong> duplex-link $host0_if0 $host1_if0 .5Mb 200ms DropTail306


$<strong>ns</strong> duplex-link $host0_if1 $host1_if1 .5Mb 200ms DropTailset sctp0 [new Agent/SCTP]$<strong>ns</strong> multihome-<strong>at</strong>tach-agent $host0_core $sctp0set trace_ch [open trace.sctp w]$sctp0 set trace_all_ 1$sctp0 trace rto_$sctp0 trace errorCount_$sctp0 <strong>at</strong>tach $trace_ch;# print all on a single trace eventset sctp1 [new Agent/SCTP]$<strong>ns</strong> multihome-<strong>at</strong>tach-agent $host1_core $sctp1$<strong>ns</strong> connect $sctp0 $sctp1set ftp0 [new Applic<strong>at</strong>ion/FTP]$ftp0 <strong>at</strong>tach-agent $sctp0$sctp0 set-primary-destin<strong>at</strong>ion $host1_if0;# set primary before associ<strong>at</strong>ion starts$<strong>ns</strong> <strong>at</strong> 7.5 "$sctp0 set-primary-destin<strong>at</strong>ion $host1_if1";# change primary$<strong>ns</strong> <strong>at</strong> 7.5 "$sctp0 print cwnd_" ;# print all dests’ cwnds <strong>at</strong> time 7.5$<strong>ns</strong> <strong>at</strong> 0.5 "$ftp0 start"$<strong>ns</strong> <strong>at</strong> 9.5 "$ftp0 stop"$<strong>ns</strong> <strong>at</strong> 10.0 "finish"$<strong>ns</strong> run307


Chapter 36Agent/SRMThis chapter describes the internals of the SRM implement<strong>at</strong>ion in <strong>ns</strong>. <strong>The</strong> chapter is in three parts: the first part is an overviewof a minimal SRM configur<strong>at</strong>ion, <strong>and</strong> a “complete” description of the configur<strong>at</strong>ion parameters of the base SRM agent. <strong>The</strong>second part describes the architecture, internals, <strong>and</strong> the code p<strong>at</strong>h of the base SRM agent. <strong>The</strong> last part of the chapter is adescription of the exte<strong>ns</strong>io<strong>ns</strong> for other types of SRM agents th<strong>at</strong> have been <strong>at</strong>tempted to d<strong>at</strong>e.<strong>The</strong> procedures <strong>and</strong> functio<strong>ns</strong> described in this chapter can be found in ~<strong>ns</strong>/tcl/mcast/srm.tcl, ~<strong>ns</strong>/tcl/mcast/srm-adaptive.tcl,~<strong>ns</strong>/tcl/mcast/srm-nam.tcl, ~<strong>ns</strong>/tcl/mcast/srm-debug.tcl, <strong>and</strong> ~<strong>ns</strong>/srm.{cc, h}.36.1 Configur<strong>at</strong>ionRunning an SRM simul<strong>at</strong>ion requires cre<strong>at</strong>ing <strong>and</strong> configuring the agent, <strong>at</strong>taching an applic<strong>at</strong>ion-level d<strong>at</strong>a source (a trafficgener<strong>at</strong>or), <strong>and</strong> starting the agent <strong>and</strong> the traffic gener<strong>at</strong>or.36.1.1 Trivial Configur<strong>at</strong>ionCre<strong>at</strong>ing the Agentset <strong>ns</strong> [new Simul<strong>at</strong>or]$<strong>ns</strong> enableMcastset node [$<strong>ns</strong> node]set group [$<strong>ns</strong> allocaddr];# preamble initializ<strong>at</strong>ion;# agent to reside on this node;# multicast group for this agentset srm [new Agent/SRM]$srm set dst_ $group ;# configure the SRM agent$<strong>ns</strong> <strong>at</strong>tach-agent $node $srm$srm set fid_ 1$srm log [open srmSt<strong>at</strong>s.tr w]$srm trace [open srmEvents.tr w];# optional configur<strong>at</strong>ion;# log st<strong>at</strong>istics in this file;# trace events for this agent<strong>The</strong> key steps in configuring a virgin SRM agent are to assign its multicast group, <strong>and</strong> <strong>at</strong>tach it to a node.308


Other useful configur<strong>at</strong>ion parameters are to assign a separ<strong>at</strong>e flow id to traffic origin<strong>at</strong>ing from this agent, to open a log filefor st<strong>at</strong>istics, <strong>and</strong> a trace file for trace d<strong>at</strong>a 1 .<strong>The</strong> file tcl/mcast/srm-nam.tcl contai<strong>ns</strong> definitio<strong>ns</strong> th<strong>at</strong> overload the agent’s send methods; this separ<strong>at</strong>es controltraffic origin<strong>at</strong>ing from the agent by type. Each type is alloc<strong>at</strong>ed a separ<strong>at</strong>e flowID. <strong>The</strong> traffic is separ<strong>at</strong>ed into sessionmessages (flowid = 40), requests (flowid = 41), <strong>and</strong> repair messages (flowid = 42). <strong>The</strong> base flowid can be changed by settingglobal variable ctrlFid to one less than the desired flowid before sourcing srm-nam.tcl. To do this, the simul<strong>at</strong>ion scriptmust source srm-nam.tcl before cre<strong>at</strong>ing any SRM agents. This is useful for analysis of traffic traces, or for visualiz<strong>at</strong>ionin nam.Applic<strong>at</strong>ion D<strong>at</strong>a H<strong>and</strong>ling <strong>The</strong> agent does not gener<strong>at</strong>e any applic<strong>at</strong>ion d<strong>at</strong>a on its own; i<strong>ns</strong>tead, the simul<strong>at</strong>ion user canconnect any traffic gener<strong>at</strong>ion module to any SRM agent to gener<strong>at</strong>e d<strong>at</strong>a. <strong>The</strong> following code demo<strong>ns</strong>tr<strong>at</strong>es how a trafficgener<strong>at</strong>ion agent can be <strong>at</strong>tached to an SRM agent:set packetSize 210set exp0 [new Applic<strong>at</strong>ion/Traffic/Exponential]$exp0 set packetSize_ $packetSize$exp0 set burst_time_ 500ms$exp0 set idle_time_ 500ms$exp0 set r<strong>at</strong>e_ 100k;# configure traffic gener<strong>at</strong>or$exp0 <strong>at</strong>tach-agent $srm0$srm0 set packetSize_ $packetSize$srm0 set tg_ $exp0$srm0 set app_fid_ 0;# <strong>at</strong>tach applic<strong>at</strong>ion to SRM agent;# to gener<strong>at</strong>e repair packets of appropri<strong>at</strong>e size;# pointer to traffic gener<strong>at</strong>or object;# fid value for packets gener<strong>at</strong>ed by traffic gener<strong>at</strong>or<strong>The</strong> user can <strong>at</strong>tach any traffic gener<strong>at</strong>or to an SRM agent. <strong>The</strong> SRM agent will add the SRM headers, set the destin<strong>at</strong>ionaddress to the multicast group, <strong>and</strong> deliver the packet to its target. <strong>The</strong> SRM header contai<strong>ns</strong> the type of the message, theidentity of the sender, the sequence number of the message, <strong>and</strong> (for control messages), the round for which this message isbeing sent. Each d<strong>at</strong>a unit in SRM is identified as 〈sender’s id, message sequence number〉.<strong>The</strong> SRM agent does not gener<strong>at</strong>e its own d<strong>at</strong>a; it does not also keep track of the d<strong>at</strong>a sent, except to record the sequencenumbers of messages received in the event th<strong>at</strong> it has to do error recovery. Since the agent has no actual record of past d<strong>at</strong>a,it needs to know wh<strong>at</strong> packet size to use for each repair message. Hence, the i<strong>ns</strong>tance variable packetSize_ specifies thesize of repair messages gener<strong>at</strong>ed by the agent.Starting the Agent <strong>and</strong> Traffic Gener<strong>at</strong>or<strong>The</strong> agent <strong>and</strong> the traffic gener<strong>at</strong>or must be started separ<strong>at</strong>ely.$srm start$exp0 startAltern<strong>at</strong>ively, the traffic gener<strong>at</strong>or can be started from the SRM Agent:$srm0 start-sourceAt start, the agent joi<strong>ns</strong> the multicast group, <strong>and</strong> starts gener<strong>at</strong>ing session messages. <strong>The</strong> start-source triggers thetraffic gener<strong>at</strong>or to start sending d<strong>at</strong>a.1 Note th<strong>at</strong> the trace d<strong>at</strong>a can also be used to g<strong>at</strong>her certain kinds of trace d<strong>at</strong>a. We will illustr<strong>at</strong>e this l<strong>at</strong>er.309


36.1.2 Other Configur<strong>at</strong>ion ParametersIn addition to the above parameters, the SRM agent supports additional configur<strong>at</strong>ion variables. Each of the variables describedin this section is both an OTcl class variable <strong>and</strong> an OTcl object’s i<strong>ns</strong>tance variable. Changing the class variablechanges the default value for all agents th<strong>at</strong> are cre<strong>at</strong>ed subsequently. Changing the i<strong>ns</strong>tance variable of a particular agentonly affects the values used by th<strong>at</strong> agent. For example,Agent/SRM set D1_ 2.0$srm set D1_ 2.0;# Changes the class variable;# Changes D1_ for the particular $srm object only<strong>The</strong> default request <strong>and</strong> repair timer parameters [11] for each SRM agent are:Agent/SRM set C1_ 2.0 ;# request parametersAgent/SRM set C2_ 2.0Agent/SRM set D1_ 1.0 ;# repair parametersAgent/SRM set D2_ 1.0It is thus possible to trivially obtain two flavors of SRM agents based on whether the agents use probabilistic or deterministicsuppression by using the following definitio<strong>ns</strong>:Class Agent/SRM/Deterministic -superclass Agent/SRMAgent/SRM/Deterministic set C2_ 0.0Agent/SRM/Deterministic set D2_ 0.0Class Agent/SRM/Probabilistic -superclass Agent/SRMAgent/SRM/Probabilistic set C1_ 0.0Agent/SRM/Probabilistic set D1_ 0.0In a l<strong>at</strong>er section (Section 36.7), we will discuss other ways of extending the SRM agent.Timer rel<strong>at</strong>ed functio<strong>ns</strong> are h<strong>and</strong>led by separ<strong>at</strong>e objects belonging to the class SRM. Timers are required for loss recovery <strong>and</strong>sending periodic session messages. <strong>The</strong>re are loss recovery objects to send request <strong>and</strong> repair messages. <strong>The</strong> agent cre<strong>at</strong>es asepar<strong>at</strong>e request or repair object to h<strong>and</strong>le each loss. In contrast, the agent only cre<strong>at</strong>es one session object to send periodicsession messages. <strong>The</strong> default classes the express each of these functio<strong>ns</strong> are:Agent/SRM set requestFunction_Agent/SRM set repairFunction_Agent/SRM set sessionFunction_"SRM/request""SRM/repair""SRM/session"Agent/SRM set requestBackoffLimit_ 5 ;# parameter to requestFunction_Agent/SRM set sessionDelay_ 1.0 ;# parameter to sessionFunction_<strong>The</strong> i<strong>ns</strong>tance procedures requestFunction{}, repairFunction{}, <strong>and</strong> sessionFunction{} can be used tochange the default function for individual agents. <strong>The</strong> last two lines are specific parameters used by the request <strong>and</strong> sessionobjects. <strong>The</strong> following section (Section 36.2) describes the implement<strong>at</strong>ion of theses objects in gre<strong>at</strong>er detail.310


36.1.3 St<strong>at</strong>isticsEach agent tracks two sets of st<strong>at</strong>istics: st<strong>at</strong>istics to measure the respo<strong>ns</strong>e to d<strong>at</strong>a loss, <strong>and</strong> overall st<strong>at</strong>istics for each request/repair.In addition, there are methods to access other inform<strong>at</strong>ion from the agent.D<strong>at</strong>a Loss <strong>The</strong> st<strong>at</strong>istics to measure the respo<strong>ns</strong>e to d<strong>at</strong>a losses tracks the duplic<strong>at</strong>e requests (<strong>and</strong> repairs), <strong>and</strong> the averagerequest (<strong>and</strong> repair) delay. <strong>The</strong> algorithm used is documented in Floyd et al[11]. In this algorithm, each new request (orrepair) starts a new request (or repair) period. During the request (or repair) period, the agent measures the number of firstround duplic<strong>at</strong>e requests (or repairs) until the round termin<strong>at</strong>es either due to receiving a request (or repair), or due to the agentsending one. <strong>The</strong> following code illustr<strong>at</strong>es how the user can simple retrieve the current values in an agent:set st<strong>at</strong>sList [$srm array get st<strong>at</strong>istics_]array set st<strong>at</strong>sArray [$srm array get st<strong>at</strong>istics_]<strong>The</strong> first form retur<strong>ns</strong> a list of key-value pairs. <strong>The</strong> second form loads the list into the st<strong>at</strong>sArray for further manipul<strong>at</strong>ion.<strong>The</strong> keys of the array are dup-req, ave-dup-req, req-delay, ave-req-delay, dup-rep, ave-dup-rep,rep-delay, <strong>and</strong> ave-rep-delay.Overall St<strong>at</strong>istics In addition, each loss recovery <strong>and</strong> session object keeps track of times <strong>and</strong> st<strong>at</strong>istics. In particular, eachobject records its startTime, serviceTime, distance, as are relevant to th<strong>at</strong> object; startTime is the time th<strong>at</strong> thisobject was cre<strong>at</strong>ed, serviceTime is the time for this object to complete its task, <strong>and</strong> the distance is the one-way time to reachthe remote peer.For request objects, startTime is the time a packet loss is detected, serviceTime is the time to finally receive th<strong>at</strong> packet,<strong>and</strong> distance is the distance to the original sender of the packet. For repair objects, startTime is the time th<strong>at</strong> a request forretra<strong>ns</strong>mission is received, serviceTime is the time send a repair, <strong>and</strong> the distance is the distance to the original requester. Forboth types of objects, the serviceTime is normalized by the distance. For the session object, startTime is the time th<strong>at</strong> theagent joi<strong>ns</strong> the multicast group. serviceTime <strong>and</strong> distance are not relevant.Each object also maintai<strong>ns</strong> st<strong>at</strong>istics particular to th<strong>at</strong> type of object. Request objects track the number of duplic<strong>at</strong>e requests<strong>and</strong> repairs received, the number of requests sent, <strong>and</strong> the number of times this object had to backoff before finally receivingthe d<strong>at</strong>a. Repair objects track the number of duplic<strong>at</strong>e requests <strong>and</strong> repairs, as well as whether or not this object for this agentsent the repair. Session objects simply record the number of session messages sent.<strong>The</strong> values of the timers <strong>and</strong> the st<strong>at</strong>istics for each object are written to the log file every time an object completes the errorrecovery function it was tasked to do. <strong>The</strong> form<strong>at</strong> of this trace file is:where〈prefix〉 is〈id〉 is〈times〉 is〈st<strong>at</strong>s〉 is〈prefix〉 〈id〉 〈times〉 〈st<strong>at</strong>s〉〈time〉 n 〈node id〉 m 〈msg id〉 r 〈round〉〈msg id〉 is expressed as 〈source id:sequence number〉type 〈of object〉list of key-value pairs of startTime, serviceTime, distancelist of key-value pairs of per object st<strong>at</strong>isticsdupRQST, dupREPR, #sent, backofffor request objectsdupRQST, dupREPR, #sentfor repair objects#sentfor session objects<strong>The</strong> following sample output illustr<strong>at</strong>es the output file form<strong>at</strong> (the lines have been folded to fit on the page):311


3.6274 n 0 m r 1 type repair serviceTime 0.500222 \startTime 3.5853553333333332 distance 0.0105 #sent 1 dupREPR 0 dupRQST 03.6417 n 1 m r 2 type request serviceTime 2.66406 \startTime 3.5542666666666665 distance 0.0105 backoff 1 #sent 1 dupREPR 0 dupRQST 03.6876 n 2 m r 2 type request serviceTime 1.33406 \startTime 3.5685333333333333 distance 0.021 backoff 1 #sent 0 dupREPR 0 dupRQST 03.7349 n 3 m r 2 type request serviceTime 0.876812 \startTime 3.5828000000000002 distance 0.032 backoff 1 #sent 0 dupREPR 0 dupRQST 03.7793 n 5 m r 2 type request serviceTime 0.669063 \startTime 3.5970666666666671 distance 0.042 backoff 1 #sent 0 dupREPR 0 dupRQST 03.7808 n 4 m r 2 type request serviceTime 0.661192 \startTime 3.5970666666666671 distance 0.0425 backoff 1 #sent 0 dupREPR 0 dupRQST 0Miscellaneous Inform<strong>at</strong>ionagent:Finally, the user can use the following methods to g<strong>at</strong>her additional inform<strong>at</strong>ion about the• groupSize?{} retur<strong>ns</strong> the agent’s current estim<strong>at</strong>e of the multicast group size.• distances?{} retur<strong>ns</strong> a list of key-value pairs of distances; the key is the address of the agent, the value is theestim<strong>at</strong>e of the distance to th<strong>at</strong> agent. <strong>The</strong> first element is the address of this agent, <strong>and</strong> the distance of 0.• distance?{} retur<strong>ns</strong> the distance to the particular agent specified as argument.<strong>The</strong> default distance <strong>at</strong> the start of any simul<strong>at</strong>ion is 1.$srm(i) groupSize?;# retur<strong>ns</strong> $srm(i)’s estim<strong>at</strong>e of the group size$srm(i) distances?;# retur<strong>ns</strong> list of 〈address, distance〉 tuples$srm(i) distance? 257 ;# retur<strong>ns</strong> the distance to agent <strong>at</strong> address 25736.1.4 TracingEach object writes out trace inform<strong>at</strong>ion th<strong>at</strong> can be used to track the progress of the object in its error recovery. Each traceentry is of the form:〈prefix〉 〈tag〉 〈type of entry〉 〈values〉<strong>The</strong> prefix is as describe in the previous section for st<strong>at</strong>istics. <strong>The</strong> tag is Q for request objects, P for repair objects, <strong>and</strong> S forsession objects. <strong>The</strong> following types of trace entries <strong>and</strong> parameters are written by each object:312


Type ofTag Object Other values CommentsQDETECTQ INTERVALS C1 〈C1_〉 C2 〈C2_〉 dist 〈distance〉 i 〈backoff_〉Q NTIMER <strong>at</strong> 〈time〉 Time the request timer will fireQSENDNACKQ NACK IGNORE-BACKOFF 〈time〉 Receive NACK, ignore other NACKsuntil 〈time〉Q REPAIR IGNORES 〈time〉 Receive REPAIR, ignore NACKs until〈time〉Q DATA Agent receives d<strong>at</strong>a i<strong>ns</strong>tead of repair.Possibly indic<strong>at</strong>es out of order arrival ofd<strong>at</strong>a.P NACK from 〈requester〉 Receive NACK, initi<strong>at</strong>e repairP INTERVALS D1 〈D1_〉 D2 〈D2_〉 dist 〈distance〉P RTIMER <strong>at</strong> 〈time〉 Time the repair timer will firePSENDREPP REPAIR IGNORES 〈time〉 Receive REPAIR, ignore NACKs until〈time〉P DATA Agent receives d<strong>at</strong>a i<strong>ns</strong>tead of repair. Indic<strong>at</strong>esprem<strong>at</strong>ure request by an agent.S SESSION logs session message sent<strong>The</strong> following illustr<strong>at</strong>es a typical trace for a single loss <strong>and</strong> recovery.3.5543 n 1 m r 0 Q DETECT3.5543 n 1 m r 1 Q INTERVALS C1 2.0 C2 0.0 d 0.0105 i 13.5543 n 1 m r 1 Q NTIMER <strong>at</strong> 3.575273.5685 n 2 m r 0 Q DETECT3.5685 n 2 m r 1 Q INTERVALS C1 2.0 C2 0.0 d 0.021 i 13.5685 n 2 m r 1 Q NTIMER <strong>at</strong> 3.610533.5753 n 1 m r 1 Q SENDNACK3.5753 n 1 m r 2 Q INTERVALS C1 2.0 C2 0.0 d 0.0105 i 23.5753 n 1 m r 2 Q NTIMER <strong>at</strong> 3.617273.5753 n 1 m r 2 Q NACK IGNORE-BACKOFF 3.596273.5828 n 3 m r 0 Q DETECT3.5828 n 3 m r 1 Q INTERVALS C1 2.0 C2 0.0 d 0.032 i 13.5828 n 3 m r 1 Q NTIMER <strong>at</strong> 3.64683.5854 n 0 m r 0 P NACK from 2573.5854 n 0 m r 1 P INTERVALS D1 1.0 D2 0.0 d 0.01053.5854 n 0 m r 1 P RTIMER <strong>at</strong> 3.595863.5886 n 2 m r 2 Q INTERVALS C1 2.0 C2 0.0 d 0.021 i 23.5886 n 2 m r 2 Q NTIMER <strong>at</strong> 3.672623.5886 n 2 m r 2 Q NACK IGNORE-BACKOFF 3.630623.5959 n 0 m r 1 P SENDREP3.5959 n 0 m r 1 P REPAIR IGNORES 3.627363.5971 n 4 m r 0 Q DETECT3.5971 n 4 m r 1 Q INTERVALS C1 2.0 C2 0.0 d 0.0425 i 13.5971 n 4 m r 1 Q NTIMER <strong>at</strong> 3.682073.5971 n 5 m r 0 Q DETECT3.5971 n 5 m r 1 Q INTERVALS C1 2.0 C2 0.0 d 0.042 i 13.5971 n 5 m r 1 Q NTIMER <strong>at</strong> 3.681073.6029 n 3 m r 2 Q INTERVALS C1 2.0 C2 0.0 d 0.032 i 2313


3.6029 n 3 m r 2 Q NTIMER <strong>at</strong> 3.730893.6029 n 3 m r 2 Q NACK IGNORE-BACKOFF 3.666893.6102 n 1 m r 2 Q REPAIR IGNORES 3.641713.6172 n 4 m r 2 Q INTERVALS C1 2.0 C2 0.0 d 0.0425 i 23.6172 n 4 m r 2 Q NTIMER <strong>at</strong> 3.787153.6172 n 4 m r 2 Q NACK IGNORE-BACKOFF 3.702153.6172 n 5 m r 2 Q INTERVALS C1 2.0 C2 0.0 d 0.042 i 23.6172 n 5 m r 2 Q NTIMER <strong>at</strong> 3.785153.6172 n 5 m r 2 Q NACK IGNORE-BACKOFF 3.701153.6246 n 2 m r 2 Q REPAIR IGNORES 3.687563.6389 n 3 m r 2 Q REPAIR IGNORES 3.734923.6533 n 4 m r 2 Q REPAIR IGNORES 3.780773.6533 n 5 m r 2 Q REPAIR IGNORES 3.77927<strong>The</strong> logging of request <strong>and</strong> repair traces is done by SRM::evTrace{}. However, the routine SRM/Session::evTrace{},overrides the base class definition of srm::evTrace{}, <strong>and</strong> writes out nothing. Individual simul<strong>at</strong>ion scripts can overridethese methods for gre<strong>at</strong>er flexibility in logging optio<strong>ns</strong>. One possible reason to override these methods might to reduce theamount of d<strong>at</strong>a gener<strong>at</strong>ed; the new procedure could then gener<strong>at</strong>e compressed <strong>and</strong> processed output.Notice th<strong>at</strong> the trace filoe contai<strong>ns</strong> sufficient inform<strong>at</strong>ion <strong>and</strong> details to derive most of the st<strong>at</strong>istics written out in the log file,or is stored in the st<strong>at</strong>istics arrays.36.2 Architecture <strong>and</strong> Internals<strong>The</strong> SRM agent implement<strong>at</strong>ion splits the protocol functio<strong>ns</strong> into packet h<strong>and</strong>ling, loss recovery, <strong>and</strong> session message activity.Packet h<strong>and</strong>ling co<strong>ns</strong>ists of forwarding applic<strong>at</strong>ion d<strong>at</strong>a messages, sending <strong>and</strong> receipt of control messages. <strong>The</strong>seactivities are executed by C++ methods.Error detection is done in C++ due to receipt of messages. However, the loss recovery is entirely done through i<strong>ns</strong>tanceprocedures in OTcl.<strong>The</strong> sending <strong>and</strong> processing of messages is accomplished in C++; the policy about when these messages should be sentis decided by i<strong>ns</strong>tance procedures in OTcl.We first describe the C++ processing due to receipt of messages (Section 36.3). Loss recovery <strong>and</strong> the sending of sessionmessages involves timer based processing. <strong>The</strong> agent uses a separ<strong>at</strong>e class SRM to perform the timer based functio<strong>ns</strong>. Foreach loss, an agent may do either request or repair processing. Each agent will i<strong>ns</strong>tanti<strong>at</strong>e a separ<strong>at</strong>e loss recovery object forevery loss, as is appropri<strong>at</strong>e for the processing th<strong>at</strong> it has to do. In the following section we describe the basic timer basedfunctio<strong>ns</strong> <strong>and</strong> the loss recovery mechanisms (Section 36.5). Finally, each agent uses one timer based function for sendingperiodic session messages (Section 36.6).36.3 Packet H<strong>and</strong>ling: Processing received messages<strong>The</strong> recv() method can receive four type of messages: d<strong>at</strong>a, request, repair, <strong>and</strong> session messages.D<strong>at</strong>a Packets <strong>The</strong> agent does not gener<strong>at</strong>e any d<strong>at</strong>a messages. <strong>The</strong> user has to specify an external agent to gener<strong>at</strong>e traffic.<strong>The</strong> recv() method must distinguish between locally origin<strong>at</strong>ed d<strong>at</strong>a th<strong>at</strong> must be sent to the multicast group, <strong>and</strong> d<strong>at</strong>a314


eceived from multicast group th<strong>at</strong> must be processed. <strong>The</strong>refore, the applic<strong>at</strong>ion agent must set the packet’s destin<strong>at</strong>ionaddress to zero.For locally origin<strong>at</strong>ed d<strong>at</strong>a, the agent adds the appropri<strong>at</strong>e SRM headers, sets the destin<strong>at</strong>ion address to the multicast group,<strong>and</strong> forwards the packet to its target.On receiving a d<strong>at</strong>a message from the group, recv_d<strong>at</strong>a(sender, msgid) will upd<strong>at</strong>e its st<strong>at</strong>e marking message 〈sender,msgid〉 received, <strong>and</strong> possibly trigger requests if it detects losses. In addition, if the message was an older message receivedout of order, then there must be a pending request or repair th<strong>at</strong> must be cleared. In th<strong>at</strong> case, the compiled object invokes theOTcl i<strong>ns</strong>tance procedure, recv-d<strong>at</strong>a{sender, msgid} 2 .Currently, there is no provision for the receivers to actually receive any applic<strong>at</strong>ion d<strong>at</strong>a. <strong>The</strong> agent does not also store any ofthe user d<strong>at</strong>a. It only gener<strong>at</strong>es repair messages of the appropri<strong>at</strong>e size, defined by the i<strong>ns</strong>tance variable packetSize_. However,the agent assumes th<strong>at</strong> any applic<strong>at</strong>ion d<strong>at</strong>a is placed in the d<strong>at</strong>a portion of the packet, pointed to by packet->accessd<strong>at</strong>a().Request Packets On receiving a request, recv_rqst(sender, msgid) will check whether it needs to schedule requests forother missing d<strong>at</strong>a. If it has received this request before it was aware th<strong>at</strong> the source had gener<strong>at</strong>ed this d<strong>at</strong>a message (i.e.,the sequence number of the request is higher than the last known sequence number of d<strong>at</strong>a from this source), then the agentcan infer th<strong>at</strong> it is missing this, as well as d<strong>at</strong>a from the last known sequence number onwards; it schedules requests for all ofthe missing d<strong>at</strong>a <strong>and</strong> retur<strong>ns</strong>. On the other h<strong>and</strong>, if the sequence number of the request is less than the last known sequencenumber from the source, then the agent can be in one of three st<strong>at</strong>es: (1) it does not have this d<strong>at</strong>a, <strong>and</strong> has a request pendingfor it, (2) it has the d<strong>at</strong>a, <strong>and</strong> has seen an earlier request, upon which it has a repair pending for it, or (3) it has the d<strong>at</strong>a, <strong>and</strong>it should i<strong>ns</strong>tanti<strong>at</strong>e a repair. All of these error recovery mechanisms are done in OTcl; recv_rqst() invokes the i<strong>ns</strong>tanceprocedure recv-rqst{sender, msgid, requester} for further processing.Repair Packets On receiving a repair, recv_repr(sender, msgid) will check whether it needs to schedule requests forother missing d<strong>at</strong>a. If it has received this repair before it was aware th<strong>at</strong> the source had gener<strong>at</strong>ed this d<strong>at</strong>a message (i.e., thesequence number of the repair is higher than the last known sequence number of d<strong>at</strong>a from this source), then the agent caninfer th<strong>at</strong> it is missing all d<strong>at</strong>a between the last known sequence number <strong>and</strong> th<strong>at</strong> on the repair; it schedules requests for all ofthis d<strong>at</strong>a, marks this message as received, <strong>and</strong> retur<strong>ns</strong>. On the other h<strong>and</strong>, if the sequence number of the request is less thanthe last known sequence number from the source, then the agent can be in one of three st<strong>at</strong>es: (1) it does not have this d<strong>at</strong>a,<strong>and</strong> has a request pending for it, (2) it has the d<strong>at</strong>a, <strong>and</strong> has seen an earlier request, upon which it has a repair pending for it,or (3) it has the d<strong>at</strong>a, <strong>and</strong> probably scheduled a repair for it <strong>at</strong> some time; after error recovery, its hold down timer (equal tothree times its distance to some requester) expired, <strong>at</strong> which time the pending object was cleared. In this last situ<strong>at</strong>ion, theagent will simply ignore the repair, for lack of being able to do anything meaningful. All of these error recovery mechanismsare done in OTcl; recv_repr() invokes the i<strong>ns</strong>tance procedure recv-repr{sender, msgid} to complete the loss recoveryphase for the particular message.Session Packets On receiving a session message, the agent upd<strong>at</strong>es its sequence numbers for all active sources, <strong>and</strong> computesits i<strong>ns</strong>tantaneous distance to the sending agent if possible. <strong>The</strong> agent will ignore earlier session messages from a groupmember, if it has received a l<strong>at</strong>er one out of order.Session message processing is done in recv_sess(). <strong>The</strong> form<strong>at</strong> of the session message is: 〈count of tuples in this message,list of tuples〉, where each tuple indic<strong>at</strong>es the 〈sender id, last sequence number from the source, time the last session messagewas received from this sender, time th<strong>at</strong> th<strong>at</strong> message was sent〉. <strong>The</strong> first tuple is the inform<strong>at</strong>ion about the local agent 3 .2 Technically, recv_d<strong>at</strong>a() invokes the i<strong>ns</strong>tance procedure recv d<strong>at</strong>a 〈sender〉 〈msgid〉, th<strong>at</strong> then invokes recv-d<strong>at</strong>a{}. <strong>The</strong> indirectionallows individual simul<strong>at</strong>ion scripts to override the recv{} as needed.3 Note th<strong>at</strong> this implement<strong>at</strong>ion of session message h<strong>and</strong>ling is subtly different from th<strong>at</strong> used in wb or described in [11]. In principle, an agent dissemin<strong>at</strong>esa list of the d<strong>at</strong>a it has actually received. Our implement<strong>at</strong>ion, on the other h<strong>and</strong>, only dissemin<strong>at</strong>es a count of the last message sequence number per sourceth<strong>at</strong> the agent knows th<strong>at</strong> th<strong>at</strong> the source has sent. This is a co<strong>ns</strong>traint when studying aspects of loss recovery during partition <strong>and</strong> healing. It is reasonable toexpect th<strong>at</strong> the maintainer of this code will fix this problem during one of his numerous intervals of copious spare time.315


36.4 Loss Detection—<strong>The</strong> Class SRMinfoA very small encapsul<strong>at</strong>ing class, entirely in C++, tracks a number of assorted st<strong>at</strong>e inform<strong>at</strong>ion. Each member of the group,n i , uses one SRMinfo block for every other member of the group.An SRMinfo object about group member n j <strong>at</strong> n i , contai<strong>ns</strong> inform<strong>at</strong>ion about the session messages received by n i from n j .n i can use this inform<strong>at</strong>ion to compute its distance to n j .If n j sends is active in sending d<strong>at</strong>a traffic, then the SRMinfo object will also contain inform<strong>at</strong>ion about the received d<strong>at</strong>a,including a bit vector indic<strong>at</strong>ing all packets received from n j .<strong>The</strong> agent keeps a list of SRMinfo objects, one per group member, in its member variable, sip_. Its method, get_st<strong>at</strong>e(intsender) will return the object corresponding to th<strong>at</strong> sender, possibly cre<strong>at</strong>ing th<strong>at</strong> object, if it did not already exist. <strong>The</strong> classSRMinfo has two methods to access <strong>and</strong> set the bit vector, i.e.,ifReceived(int id)setReceived(int id)indic<strong>at</strong>es whether the particular message from the appropri<strong>at</strong>e sender, with id id was received<strong>at</strong> n i ,to set the bit to indic<strong>at</strong>e th<strong>at</strong> the particular message from the appropri<strong>at</strong>e sender, with id id wasreceived <strong>at</strong> n i .<strong>The</strong> session message variables to access timing inform<strong>at</strong>ion are public; no encapsul<strong>at</strong>ing methods are provided. <strong>The</strong>se are:int lsess_; /* # of last session msg received */int sendTime_; /* Time sess. msg. # sent */int recvTime_; /* Time sess. msg. # received */double distance_;/* D<strong>at</strong>a messages */int ld<strong>at</strong>a_; /* # of last d<strong>at</strong>a msg sent */36.5 Loss Recovery ObjectsIn the last section, we described the agent behavior when it receives a message. Timers are used to control when any particularcontrol message is to be sent. <strong>The</strong> SRM agent uses a separ<strong>at</strong>e class SRM to do the timer based processing. In this section,we describe the basics if the class SRM, <strong>and</strong> the loss recovery objects. <strong>The</strong> following section will describe how the classSRM is used for sending periodic session messages. An SRM agent will i<strong>ns</strong>tanti<strong>at</strong>e one object to recover from one lost d<strong>at</strong>apacket. Agents th<strong>at</strong> detect the loss will i<strong>ns</strong>tanti<strong>at</strong>e an object in the class SRM/request; agents th<strong>at</strong> receive a request <strong>and</strong>have the required d<strong>at</strong>a will i<strong>ns</strong>tanti<strong>at</strong>e an object in the class SRM/repair.Request Mechanisms SRM agents detect loss when they receive a message, <strong>and</strong> infer the loss based on the sequencenumber on the message received. Since packet reception is h<strong>and</strong>led entirely by the compiled object, loss detection occurs inthe C++ methods. Loss recovery, however, is h<strong>and</strong>led entirely by i<strong>ns</strong>tance procedures of the corresponding interpreted objectin OTcl.When any of the methods detects new losses, it invokes Agent/SRM::request{} with a list of the message sequencenumbers th<strong>at</strong> are missing. request{} will cre<strong>at</strong>e a new requestFunction_ object for each message th<strong>at</strong> is missing.<strong>The</strong> agent stores the object h<strong>and</strong>le in its array of pending_ objects. <strong>The</strong> key to the array is the message identifier〈sender〉:〈msgid〉.316


<strong>The</strong> default requestFunction_ is class SRM/request <strong>The</strong> co<strong>ns</strong>tructor for the class SRM/request calls thebase class co<strong>ns</strong>tructor to initialize the simul<strong>at</strong>or i<strong>ns</strong>tance (<strong>ns</strong>_), the SRM agent (agent_), trace file (trace_), <strong>and</strong>the times_ array. It then initializes its st<strong>at</strong>istics_ array with the pertinent elements.A separ<strong>at</strong>e call to set-params{} sets the sender_, msgid_, round_ i<strong>ns</strong>tance variables for the request object. <strong>The</strong>object determines C1_ <strong>and</strong> C2_ by querying its agent_. It sets its distance to the sender (times_(distance)) <strong>and</strong>fixes other scheduling parameters: the backoff co<strong>ns</strong>tant (backoff_), the current number of backoffs (backoffCtr_),<strong>and</strong> the limit (backoffLimit_) fixed by the agent. set-params{} writes the trace entry “Q DETECT”.<strong>The</strong> final step in request{} is to schedule the timer to send the actual request <strong>at</strong> the appropri<strong>at</strong>e moment. <strong>The</strong>i<strong>ns</strong>tance procedure SRM/request::schedule{} uses compute-delay{} <strong>and</strong> its current backoff co<strong>ns</strong>tant todetermine the delay. <strong>The</strong> object schedules send-request{} to be executed after delay_ seconds. <strong>The</strong> i<strong>ns</strong>tancevariable eventID_ stores a h<strong>and</strong>le to the scheduled event. <strong>The</strong> default compute-delay{} function retur<strong>ns</strong> avalue uniformly distributed in the interval [C 1 d s , (C 1 + C 2 )d s ], where d s is twice $times_(distance). <strong>The</strong>schedule{} schedules an event to send a request after the computed delay. <strong>The</strong> routine writes a trace entry “QNTIMER <strong>at</strong> 〈time〉”.When the scheduled timer fires, the routine send-request{} sends the appropri<strong>at</strong>e message. It invokes “$agent_ sendrequest 〈args〉” to send the request. Note th<strong>at</strong> send{} is an i<strong>ns</strong>tproc-like, executed by the comm<strong>and</strong>() method of the compiledobject. However, it is possible to overload the i<strong>ns</strong>tproc-like with a specific i<strong>ns</strong>tance procedure send{} for specific configur<strong>at</strong>io<strong>ns</strong>.As an example, recall th<strong>at</strong> the file tcl/mcast/srm-nam.tcl overloads the send{} comm<strong>and</strong> to set the flowidbased on type of message th<strong>at</strong> is sent. send-request{} upd<strong>at</strong>es the st<strong>at</strong>istics, <strong>and</strong> writes the trace entry “Q SENDNACK”.When the agent receives a control message for a packet for which a pending object exists, the agent will h<strong>and</strong> the message offto the object for processing.When a request for a particular packet is received, the request object can be in one of two st<strong>at</strong>es: it is ignoring requests,co<strong>ns</strong>idering them to be duplic<strong>at</strong>es, or it will cancel its send event <strong>and</strong> re-schedule another one, after having backed offits timer. If ignoring requests it will upd<strong>at</strong>e its st<strong>at</strong>istics, <strong>and</strong> write the trace entry “Q NACK dup”. Otherwise, set <strong>at</strong>ime based on its current estim<strong>at</strong>e of the delay_, until which to ignore further requests. This interval is marked bythe i<strong>ns</strong>tance variable ignore_. If the object reschedules its timer, it will write the trace entry “ Q NACK IGNORE-BACKOFF 〈ignore〉”. Note th<strong>at</strong> this re-scheduling relies on the fact th<strong>at</strong> the agent has joined the multicast group, <strong>and</strong>will therefore receive a copy of every message it sends out.When the request object receives a repair for the particular packet, it can be in one of two st<strong>at</strong>es: either it is still waitingfor the repair, or it has already received an earlier repair. If it is the former, there will be an event pending to send arequest, <strong>and</strong> eventID_ will point to th<strong>at</strong> event. <strong>The</strong> object will compute its serviceTime, cancel th<strong>at</strong> event, <strong>and</strong> set ahold-down period during which it will ignore other requests. At the end of the hold-down period, the object will ask itsagent to clear it. It will write the trace entry “Q REPAIR IGNORES 〈ignore〉”. On the other h<strong>and</strong>, if this is a duplic<strong>at</strong>erepair, the object will upd<strong>at</strong>e its st<strong>at</strong>istics, <strong>and</strong> write the trace entry “Q REPAIR dup”.When the loss recovery phase is completed by the object, Agent/SRM::clear{} will remove the object from its arrayof pending_ objects, <strong>and</strong> place it in its list of done_ objects. Periodically, the agent will cleanup <strong>and</strong> delete the done_objects.Repair Mechanisms <strong>The</strong> agent will initi<strong>at</strong>e a repair if it receives a request for a packet, <strong>and</strong> it does not have a request objectpending_ for th<strong>at</strong> packet. <strong>The</strong> default repair object belongs to the class SRM/repair. Barring minor differences, thesequence of events <strong>and</strong> the i<strong>ns</strong>tance procedures in this class are identical to those for SRM/request. R<strong>at</strong>her than outline everysingle procedure, we only outline the differences from those described earlier for a request object.<strong>The</strong> repair object uses the repair parameters, D1_, D2_. A repair object does not repe<strong>at</strong>edly reschedule is timers; therefore, itdoes not use any of the backoff variables such as th<strong>at</strong> used by a request object. <strong>The</strong> repair object ignores all requests for the317


same packet. <strong>The</strong> repair objet does not use the ignore_ variable th<strong>at</strong> request objects use. <strong>The</strong> trace entries written by repairobjects are marginally different; they are “P NACK from 〈requester〉”, “P RTIMER <strong>at</strong> 〈fireTime〉”, “P SENDREP”, “P REPAIRIGNORES 〈holddown〉”.Apart from these differences, the calling sequence for events in a repair object is similar to th<strong>at</strong> of a request object.Mechanisms for St<strong>at</strong>istics <strong>The</strong> agent, in concert with the request <strong>and</strong> repair objects, collect st<strong>at</strong>istics about their respo<strong>ns</strong>eto d<strong>at</strong>a loss [11]. Each call to the agent request{} procedure marks a new period. At the start of a new period,mark-period{} computes the moving average of the number of duplic<strong>at</strong>es in the last period. Whenever the agent receivesa first round request from another agent, <strong>and</strong> it had sent a request in th<strong>at</strong> round, then it co<strong>ns</strong>iders the request as a duplic<strong>at</strong>e request,<strong>and</strong> increments the appropri<strong>at</strong>e counters. A request object does not co<strong>ns</strong>ider duplic<strong>at</strong>e requests if it did not itself send arequest in the first round. If the agent has a repair object pending, then it does not co<strong>ns</strong>ider the arrival of duplic<strong>at</strong>e requests forth<strong>at</strong> packet. <strong>The</strong> object methods SRM/request::dup-request?{} <strong>and</strong> SRM/repair::dup-request?{} encodethese policies, <strong>and</strong> return 0 or 1 as required.A request object also computes the elapsed time between when the loss is detected to when it receives the first request. <strong>The</strong>agent computes a moving average of this elapsed time. <strong>The</strong> object computes the elapsed time (or delay) when it cancels itsscheduled event for the first round. <strong>The</strong> object invokes Agent/SRM::upd<strong>at</strong>e-ave to compute the moving average of the delay.<strong>The</strong> agent keeps similar st<strong>at</strong>istics of the duplic<strong>at</strong>e repairs, <strong>and</strong> the repair delay.<strong>The</strong> agent stores the number of rounds taken for one loss recovery, to e<strong>ns</strong>ure th<strong>at</strong> subsequent loss recovery phases for th<strong>at</strong>packet th<strong>at</strong> are not definitely not due to d<strong>at</strong>a loss do not account for these st<strong>at</strong>istics. <strong>The</strong> agent stores the number of routestaken for a phase in the array old_. When a new loss recovery object is i<strong>ns</strong>tanti<strong>at</strong>ed, the object will use the agent’s i<strong>ns</strong>tanceprocedure round?{} to determine the number of rounds in a previous loss recovery phase for th<strong>at</strong> packet.36.6 Session ObjectsSession objects, like the loss recovery objects (Section 36.5), are derived from the base class SRM Unlike the loss recoveryobjects though, the agent only cre<strong>at</strong>es one session object for the lifetime of the agent. <strong>The</strong> co<strong>ns</strong>tructor invokes the baseclass co<strong>ns</strong>tructor as before; it then sets its i<strong>ns</strong>tance variable sessionDelay_. <strong>The</strong> agent cre<strong>at</strong>es the session object when itstart{}s. At th<strong>at</strong> time, it also invokes SRM/session::schedule, to send a session message after sessionDelay_ seconds.When the object sends a session message, it will schedule to send the next one after some interval. It will also upd<strong>at</strong>e itsst<strong>at</strong>istics. send-session{} writes out the trace entry “S SESSION”.<strong>The</strong> class overrides the evTrace{} routine th<strong>at</strong> writes out the trace entries. SRM/session::evTrace disable writing out thetrace entry for session messages.Two types of session message scheduling str<strong>at</strong>egies are currently available: <strong>The</strong> function in the base class schedules sendingsession messages <strong>at</strong> fixed intervals of sessionDelay_ jittered around a small value to avoid synchroniz<strong>at</strong>ion among all theagents <strong>at</strong> all the nodes. class SRM/session/logScaledchedules sending messages <strong>at</strong> intervals of sessionDelaytimes log 2 (groupSize_) so th<strong>at</strong> the frequency of session messages is inversely proportional to the size of the group.<strong>The</strong> base class th<strong>at</strong> sends messages <strong>at</strong> fixed intervals is the default sessionFunction_ for the agent.318


36.7 Extending the Base Class AgentIn the earlier section on configur<strong>at</strong>ion parameters (Section 36.1.2), we had shown how to trivially extend the agent to getdeterministic <strong>and</strong> probabilistic protocol behavior. In this section, we describe how to derive more complex exte<strong>ns</strong>io<strong>ns</strong> to theprotocol for fixed <strong>and</strong> adaptive timer mechanisms.36.7.1 Fixed Timers<strong>The</strong> fixed timer mechanism are done in the derived class Agent/SRM/Fixed <strong>The</strong> main difference with fixed timers isth<strong>at</strong> the repair parameters are set to log(groupSize_). <strong>The</strong>refore, the repair procedure of a fixed timer agent will set D 1<strong>and</strong> D 2 to be proportional to the group size before scheduling the repair object.36.7.2 Adaptive TimersAgents using adaptive timer mechanisms modify their request <strong>and</strong> repair parameters under three conditio<strong>ns</strong> (1) every time anew loss object is cre<strong>at</strong>ed; (2) when sending a message; <strong>and</strong> (3) when they receive a duplic<strong>at</strong>e, if their rel<strong>at</strong>ive distance to theloss is less than th<strong>at</strong> of the agent th<strong>at</strong> sends the duplic<strong>at</strong>e. All three changes require exte<strong>ns</strong>io<strong>ns</strong> to the agent <strong>and</strong> the loss objects.<strong>The</strong> class Agent/SRM/Adaptive uses class SRM/request/Adaptive <strong>and</strong> class SRM/repair/Adaptiveas the request <strong>and</strong> repair functio<strong>ns</strong> respectively. In addition, the last item requires extending the packet headers, to advertisetheir distances to the loss. <strong>The</strong> corresponding compiled class for the agent is the class ASRMAgent.Recompute for Each New Loss Object Each time a new request object is cre<strong>at</strong>ed, SRM/request/Adaptive::set-paramsinvokes $agent_ recompute-request-params. <strong>The</strong> agent method recompute-request-params(). uses thest<strong>at</strong>istics about duplic<strong>at</strong>es <strong>and</strong> delay to modify C 1 <strong>and</strong> C 2 for the current <strong>and</strong> future requests.Similarly, SRM/request/Adaptive::set-params for a new repair object invokes $agent_ recompute-repair-params.<strong>The</strong> agent method recompute-repair-params(). uses the st<strong>at</strong>istics objects to modify D 1 <strong>and</strong> D 2 for the current <strong>and</strong>future repairs.Sending a Message If a loss object sends a request in its first round_, then the agent, in the i<strong>ns</strong>tance procedure sending-request{},will lower C 1 , <strong>and</strong> set its i<strong>ns</strong>tance variable closest_(requestor) to 1.Similarly, a loss object th<strong>at</strong> sends a repair in its first round_ will invoke the agent’s i<strong>ns</strong>tance procedure, sending-repair{},to lower D 1 <strong>and</strong> set closest_(repairor) to 1.Advertising the Distance Each agent must add additional inform<strong>at</strong>ion to each request/repair th<strong>at</strong> it sends out. <strong>The</strong> baseclass SRMAgent invokes the virtual method addExtendedHeaders() for each SRM packet th<strong>at</strong> it sends out. <strong>The</strong>method is invoked after adding the SRM packet headers, <strong>and</strong> before the packet is tra<strong>ns</strong>mitted. <strong>The</strong> adaptive SRM agentoverloads addExtendedHeaders() to specify its distances in the additional headers. When sending a request, th<strong>at</strong> agentunequivocally knows the identity of the sender. As an example, the definition of addExtendedHeaders() for the adaptiveSRM agent is:void addExtendedHeaders(Packet* p) {SRMinfo* sp;hdr_srm* sh = (hdr_srm*) p->access(off_srm_);319


}hdr_asrm* seh = (hdr_asrm*) p->access(off_asrm_);switch (sh->type()) {case SRM_RQST:sp = get_st<strong>at</strong>e(sh->sender());seh->distance() = sp->distance_;break;...}Similarly, the method parseExtendedHeaders() is invoked every time an SRM packet is received. It sets the agentmember variable pdistance_ to the distance advertised by the peer th<strong>at</strong> sent the message. <strong>The</strong> member variable is boundto an i<strong>ns</strong>tance variable of the same name, so th<strong>at</strong> the peer distance can be accessed by the appropri<strong>at</strong>e i<strong>ns</strong>tance procedures.<strong>The</strong> corresponding parseExtendedHeaders() method for the Adaptive SRM agent is simply:void parseExtendedHeaders(Packet* p) {hdr_asrm* seh = (hdr_asrm*) p->access(off_asrm_);pdistance_ = seh->distance();}Finally, the adaptive SRM agent’s extended headers are defined as struct hdr_asrm. <strong>The</strong> header declar<strong>at</strong>ion is identicalto declaring other packet headers in <strong>ns</strong>. Unlike most other packet headers, these are not autom<strong>at</strong>ically available in the packet.<strong>The</strong> interpreted co<strong>ns</strong>tructor for the first adaptive agent will add the header to the packet form<strong>at</strong>. For example, the start of theco<strong>ns</strong>tructor for the Agent/SRM/Adaptive agent is:Agent/SRM/Adaptive set done_ 0Agent/SRM/Adaptive i<strong>ns</strong>tproc init args {if ![$class set done_] {set pm [[Simul<strong>at</strong>or i<strong>ns</strong>tance] set packetManager_]TclObject set off_asrm_ [$pm allochdr aSRM]$class set done_ 1}}eval $self next $args...36.8 SRM objectsSRM objects are a subclass of agent objects th<strong>at</strong> implement the SRM reliable multicast tra<strong>ns</strong>port protocol. <strong>The</strong>y inherit all ofthe generic agent functionalities. <strong>The</strong> methods for this object is described in the next section 36.9. Configur<strong>at</strong>ion parametersfor this object are:packetSize_ <strong>The</strong> d<strong>at</strong>a packet size th<strong>at</strong> will be used for repair messages. <strong>The</strong> default value is 1024.requestFunction_ <strong>The</strong> algorithm used to produce a retra<strong>ns</strong>mission request, e.g., setting request timers. <strong>The</strong> default value isSRM/request. Other possible request functio<strong>ns</strong> are SRM/request/Adaptive, used by the Adaptive SRM code.repairFunction_ <strong>The</strong> algorithm used to produce a repair, e.g., compute repair timers. <strong>The</strong> default value is SRM/repair. Otherpossible request functio<strong>ns</strong> are SRM/repair/Adaptive, used by the Adaptive SRM code.320


sessionFunction_ <strong>The</strong> algorithm used to gener<strong>at</strong>e session messages. Default is SRM/sessio<strong>ns</strong>essionDelay_ <strong>The</strong> basic interval of session messages. Slight r<strong>and</strong>om vari<strong>at</strong>ion is added to this interval to avoid globalsynchroniz<strong>at</strong>ion of session messages. User may want to adjust this variable according to their specific simul<strong>at</strong>ion.Default value is 1.0.C1_, C2_ <strong>The</strong> parameters which control the request timer. Refer to [8] for detail. <strong>The</strong> default value is C1_ = C2_ = 2.0.D1_, D2_ <strong>The</strong> parameters which control the repair timer. Refer to [8] for detail. <strong>The</strong> default value is D1_ = D2_ = 1.0.requestBackoffLimit_ <strong>The</strong> maximum number of exponential backoffs. Default value is 5.St<strong>at</strong>e Variables are:st<strong>at</strong>s_ An array containing multiple st<strong>at</strong>istics needed by adaptive SRM agent. Including: duplic<strong>at</strong>e requests <strong>and</strong> repairs incurrent request/repair period, average number of duplic<strong>at</strong>e requests <strong>and</strong> repairs, request <strong>and</strong> repair delay in currentrequest/repair period, average request <strong>and</strong> repair delay.SRM/ADAPTIVE OBJECTS SRM/Adaptive objects are a subclass of the SRM objects th<strong>at</strong> implement the adaptive SRMreliable multicast tra<strong>ns</strong>port protocol. <strong>The</strong>y inherit all of the SRM object functionalities. St<strong>at</strong>e Variables are:(Refer to the SRM paper by Sally et al [Fall, K., Floyd, S., <strong>and</strong> Henderson, T., Ns Simul<strong>at</strong>or Tests for Reno FullTCP. URLftp://ftp.ee.lbl.gov/papers/fulltcp.ps. July 1997.] for more detail.)pdistance_ This variable is used to pass the distance estim<strong>at</strong>e provided by the remote agent in a request or repair message.D1_, D2_ <strong>The</strong> same as th<strong>at</strong> in SRM agents, except th<strong>at</strong> they are initialized to log10(group size) when gener<strong>at</strong>ing the firstrepair.MinC1_, MaxC1_, MinC2_, MaxC2_ <strong>The</strong> minimum/maximum values of C1_ <strong>and</strong> C2_. Default initial values are definedin [8]. <strong>The</strong>se values define the dynamic range of C1_ <strong>and</strong> C2_.MinD1_, MaxD1_, MinD2_, MaxD2_ <strong>The</strong> minimum/maximum values of D1_ <strong>and</strong> D2_. Default initial values are definedin [8]. <strong>The</strong>se values define the dynamic range of D1_ <strong>and</strong> D2_.AveDups Higher bound for average duplic<strong>at</strong>es.AveDelay Higher bound for average delay.eps AveDups -dups determines the lower bound of the number of duplic<strong>at</strong>es, when we should adjust parameters to decreasedelay.36.9 Comm<strong>and</strong>s <strong>at</strong> a glance<strong>The</strong> following is a list of comm<strong>and</strong>s to cre<strong>at</strong>e/manipul<strong>at</strong>e srm agents in simul<strong>at</strong>io<strong>ns</strong>:set srm0 [new Agent/SRM]This cre<strong>at</strong>es an i<strong>ns</strong>tance of the SRM agent. In addition to the base class, two exte<strong>ns</strong>io<strong>ns</strong> of the srm agent have beenimplemented. <strong>The</strong>y are Agent/SRM/Fixed <strong>and</strong> Agent/SRM/Adaptive. See section 36.7 for details about these exte<strong>ns</strong>io<strong>ns</strong>.<strong>ns</strong>_ <strong>at</strong>tach-agent This <strong>at</strong>taches the srm agent i<strong>ns</strong>tance to the given .321


set grp [Node allocaddr]$srm set dst_ $grpThis assig<strong>ns</strong> the srm agent to a multicast group represented by the mcast address .Configur<strong>at</strong>ion parameters for srm agent may be set as follows:$srm set fid_ $srm set tg_ .. etcFor all possible parameters <strong>and</strong> their default values please lookup <strong>ns</strong>/tcl/mcast/srm.tcl <strong>and</strong> <strong>ns</strong>/tcl/mcast/srm-adaptive.tcl.set exp [new Applic<strong>at</strong>ion/Traffic/Exponential]$exp <strong>at</strong>tach-agent $srmThis comm<strong>and</strong> <strong>at</strong>taches a traffic gener<strong>at</strong>or (an exponential one in this example), to the srm agent.$srm start; $exp start<strong>The</strong>se comm<strong>and</strong>s start the srm agent <strong>and</strong> traffic gener<strong>at</strong>or. Note th<strong>at</strong> the srm agent <strong>and</strong> traffic gener<strong>at</strong>or have to be startedsepar<strong>at</strong>ely. Altern<strong>at</strong>ively, the traffic gener<strong>at</strong>or may be started through the agent as follows:$srm start-source.See <strong>ns</strong>/tcl/ex/srm.tcl for a simple example of setting up a SRM agent.322


Chapter 37PLMThis chapter describes the <strong>ns</strong> implement<strong>at</strong>ion of the PLM protocol [19]. <strong>The</strong> code of the PLM protocol is written in both C++<strong>and</strong> OTcl. <strong>The</strong> PLM Packet Pair gener<strong>at</strong>or is written in C++ <strong>and</strong> the PLM core machinery is written in OTcl. <strong>The</strong> chapterhas simply three parts: the first part shows how to cre<strong>at</strong>e <strong>and</strong> configure a PLM session; the second part describes the PacketPair source gener<strong>at</strong>or; the third part describes the architecture <strong>and</strong> internals of the PLM protocol. In this last part, r<strong>at</strong>her thangiving a list of procedures <strong>and</strong> functio<strong>ns</strong>, we introduce the main procedures per functionality (i<strong>ns</strong>tanti<strong>at</strong>ion of a PLM source,i<strong>ns</strong>tanti<strong>at</strong>ion of a PLM receiver, reception of a packet, detection of a loss, etc.).<strong>The</strong> procedures, functio<strong>ns</strong>, <strong>and</strong> variables described in this chapter can be found in: ~<strong>ns</strong>/plm/cbr-traffic-PP.cc, ~<strong>ns</strong>/plm/lossmonitor-plm.cc,~<strong>ns</strong>/tcl/plm/plm.tcl, ~<strong>ns</strong>/tcl/plm/plm-<strong>ns</strong>.tcl, ~<strong>ns</strong>/tcl/plm/plm-topo.tcl, ~<strong>ns</strong>/tcl/lib/<strong>ns</strong>-default.tcl.37.1 Configur<strong>at</strong>ionCre<strong>at</strong>ing a simple scenario with one PLM flow (only one receiver)This simple example can be run as is (several complex scenarios can be found in the file ~<strong>ns</strong>/tcl/ex/simple-plm.tcl).set packetSize 500set plm_debug_flag 2set r<strong>at</strong>es "50e3 50e3 50e3 50e3 50e3"set r<strong>at</strong>es_cum [calc_cum $r<strong>at</strong>es]set level [llength $r<strong>at</strong>es]set Queue_sched_ FQset PP_burst_length 2set PP_estim<strong>at</strong>ion_length 3;#Packet size (in bytes);#Debugging output;#R<strong>at</strong>e of each layer;#Cumul<strong>at</strong>ed r<strong>at</strong>e of the layers (m<strong>and</strong><strong>at</strong>ory);#Number of layers (m<strong>and</strong><strong>at</strong>ory);#Scheduling of the queues;#PP burst length (in packets);#Minimum number of PP required to make an estim<strong>at</strong>eClass Scenario0 -superclass PLMTopologyScenario0 i<strong>ns</strong>tproc init args {eval $self next $args$self i<strong>ns</strong>tvar <strong>ns</strong> node$self build_link 1 2 100ms 256Kbset addr(1) [$self place_source 1 3]$self place_receiver 2 $addr(1) 5 1;#Build a link;#Set a PLM source;#Set a PLM receiver323


#set up the multicast routingDM set PruneTimeout 1000set mproto DMset mrth<strong>and</strong>le [$<strong>ns</strong> mrtproto $mproto {} ]};#A large PruneTimeout value is requiredset <strong>ns</strong> [new Simul<strong>at</strong>or -multicast on]$<strong>ns</strong> multicast$<strong>ns</strong> namtrace-all [open out.nam w]set scn [new Scenario0 $<strong>ns</strong>]$<strong>ns</strong> <strong>at</strong> 20 "exit 0"$<strong>ns</strong> run;#PLM needs multicast routing;#Nam output;#Call of the scenarioSeveral variables are introduced in this example. <strong>The</strong>y all need to be set in the simul<strong>at</strong>ion script (there is no default value forthese variables). In particular the two following lines are m<strong>and</strong><strong>at</strong>ory <strong>and</strong> must not be omitted:set r<strong>at</strong>es_cum [calc_cum $r<strong>at</strong>es]set level [llength $r<strong>at</strong>es]We describe now in detail each variable:packetSize represents the size of the packets in bytes sent by the PLM source.plm_debug_flag represents the verbose level of debugging output: from 0 no output to 3 full output. Forplm_debug_flag set to 3 (full output), long lines output are gener<strong>at</strong>ed which is not comp<strong>at</strong>ible with nam visualiz<strong>at</strong>ion.r<strong>at</strong>es is a list specifying the b<strong>and</strong>width of each layer (this is not the cumul<strong>at</strong>ed b<strong>and</strong>width!).r<strong>at</strong>es_cum is a list specifying the cumul<strong>at</strong>ed b<strong>and</strong>width of the layers: the first element of r<strong>at</strong>es_cum is the b<strong>and</strong>widtha layer 1, the second element of r<strong>at</strong>es_cum is the sum of the b<strong>and</strong>width of layer 1 <strong>and</strong> layer 2, etc. <strong>The</strong> proccalc_cum{} computes the cumul<strong>at</strong>ed r<strong>at</strong>es.level is the number of layers.Queue_sched_ represents the scheduling of the queues. This is used by the PLMTopology i<strong>ns</strong>tproc build_link. PLMrequires FQ scheduling or a vari<strong>at</strong>ion.PP_burst_length represents the size of the Packet Pair bursts in packets.PP_estim<strong>at</strong>ion_length represents the minimum number of Packet Pair required to compute an estim<strong>at</strong>e (see section37.3.3).All the simul<strong>at</strong>io<strong>ns</strong> for PLM should be setup using the PLMTopology environment (as in the example script where we definea PLMTopology superclass called Scenario0). <strong>The</strong> user interface is (all the i<strong>ns</strong>tproc can be found in ~<strong>ns</strong>/tcl/plm/plm-topo.tcl):build_link a b d bw cre<strong>at</strong>es a duplex link between node a <strong>and</strong> b with a delay d <strong>and</strong> a b<strong>and</strong>width bw. If either nodedoes not exist, build_link cre<strong>at</strong>es it.place_source n t cre<strong>at</strong>es <strong>and</strong> places a PLM source <strong>at</strong> node n <strong>and</strong> starts it <strong>at</strong> time t. place_source retur<strong>ns</strong> addrwhich allows to <strong>at</strong>tach receivers to this source.324


place_receiver n addr C nb cre<strong>at</strong>es <strong>and</strong> places a PLM receiver <strong>at</strong> node n <strong>and</strong> <strong>at</strong>tached it to the source which returnthe address addr. <strong>The</strong> check value for this PLM receiver is C. An optional parameter nb allows to get an i<strong>ns</strong>tanceof the PLM receiver called PLMrcvr($nb). This i<strong>ns</strong>tance is only useful to get some specific st<strong>at</strong>istics about thisreceiver (mainly the number of packets received or lost).37.2 <strong>The</strong> Packet Pair Source Gener<strong>at</strong>orThis section describes the Packet Pair source gener<strong>at</strong>or; the relevant files are: ~<strong>ns</strong>/plm/cbr-traffic-PP.cc, ~<strong>ns</strong>/tcl/lib/<strong>ns</strong>default.tcl.<strong>The</strong> OTcl class name of the PP source is: Applic<strong>at</strong>ion/Traffic/CBR_PP. <strong>The</strong> Packet Pair (PP) source gener<strong>at</strong>oris in the file ~<strong>ns</strong>/plm/cbr-traffic-PP.cc. This source gener<strong>at</strong>or is a vari<strong>at</strong>ion of the CBR source gener<strong>at</strong>or in ~<strong>ns</strong>/cbr_traffic.cc.We just describe the salient differences between the code of the CBR source <strong>and</strong> the code of the PP source. <strong>The</strong> default valuesin ~<strong>ns</strong>/tcl/lib/<strong>ns</strong>-default.tcl for the PP source gener<strong>at</strong>or are the same than for the CBR source. We need for the PP sourcegener<strong>at</strong>or a new parameter PBM_:Applic<strong>at</strong>ion/Traffic/CBR_PP set PBM_ 2;#Default value<strong>The</strong> OTcl i<strong>ns</strong>tvar bounded variable PBM_ (same name in C++ <strong>and</strong> in OTcl) specifies the number of back-to-back packets tobe sent. For PBM_=1 we have a CBR source, for PBM_=2 we have a Packet Pair source (a source which sends two packetsback-to-back), etc. <strong>The</strong> mean r<strong>at</strong>e of the PP source is r<strong>at</strong>e_, but the packets are sent in burst of PBM_ packets. Note th<strong>at</strong> wealso use the terminology Packet Pair source <strong>and</strong> Packet Pair burst for PBM_>2. We compute the next_interval as:double CBR_PP_Traffic::next_interval(int& size)/*(PP_ - 1) is the number of packets in the current burst.*/if (PP_ >= (PBM_ - 1))interval_ = PBM_*(double)(size_ sendmsg(size_, "NEW_BURST");elseagent_->sendmsg(size_);...325


37.3 Architecture of the PLM Protocol<strong>The</strong> code of the PLM protocol is divided in three files: ~<strong>ns</strong>/tcl/plm/plm.tcl, which contai<strong>ns</strong> the PLM protocol machinerywithout any specific interface with <strong>ns</strong>; ~<strong>ns</strong>/tcl/plm/plm-<strong>ns</strong>.tcl, which contai<strong>ns</strong> the specific <strong>ns</strong> interface. However, we do notguarantee the strict validity of this <strong>ns</strong> interfacing; ~<strong>ns</strong>/tcl/plm/plm-topo.tcl, which contai<strong>ns</strong> a user interface to build simul<strong>at</strong>io<strong>ns</strong>cenarios with PLM flows.In the following we do not discuss the various procedures per object (for i<strong>ns</strong>tance all the i<strong>ns</strong>tproc of the PLM class) but r<strong>at</strong>herper functionality (for i<strong>ns</strong>tance which i<strong>ns</strong>tproc among the various classes are involved in the i<strong>ns</strong>tanti<strong>at</strong>ion of a PLM receiver).For a given functionality, we do not describe in details all the code involved, but we give the principal steps.37.3.1 I<strong>ns</strong>tanti<strong>at</strong>ion of a PLM SourceTo cre<strong>at</strong>e a PLM source, place it <strong>at</strong> node n, <strong>and</strong> start it <strong>at</strong> t 0 , we call the PLMTopology i<strong>ns</strong>tproc place_source n t 0 .This i<strong>ns</strong>tproc return addr, the address required to <strong>at</strong>tach a receiver to this source. place_source calls the Simul<strong>at</strong>ori<strong>ns</strong>tproc PLMbuild_source_set th<strong>at</strong> cre<strong>at</strong>es as many Applic<strong>at</strong>ion/Traffic/CBR_PP i<strong>ns</strong>tances as there are layers (in thefollowing we call an i<strong>ns</strong>tance of the class Applic<strong>at</strong>ion/Traffic/CBR_PP a layer). Each layer corresponds to a different multicastgroup.To speed up the simul<strong>at</strong>io<strong>ns</strong> when the PLM sources start we use the following trick: At t = 0, PLMbuild_source_setrestricts each layer to send only one packet (maxpkts_ set to 1). Th<strong>at</strong> allows to build the multicast trees – one multicast treeper layer – without flooding the whole network. Indeed, each layer only sends one packet to build the corresponding multicasttree.<strong>The</strong> multicast trees take <strong>at</strong> most the maximum RTT of the network to be established <strong>and</strong> must be established before t 0 ,the PLM source starting time. <strong>The</strong>refore, t 0 must be carrefully chosen, otherwise the source sends a large number of uselesspackets. However, as we just need to start the PLM source after the multicast trees are estabished, t 0 can be largelyoverestim<strong>at</strong>ed. At time t 0 , we set maxpkts_ to 268435456 for all the layers.It is fundamental, in order to have persistent multicast trees, th<strong>at</strong> the prune timeout is set to a large value. For i<strong>ns</strong>tance, withDM routing:DM set PruneTimeout 1000Each layer of a same PLM source has the same flow id fid_. Co<strong>ns</strong>equently, each PLM source is co<strong>ns</strong>idered as a single flowfor a Fair Queueing scheduler. <strong>The</strong> PLM code manages autom<strong>at</strong>ically the fid_ to prevent different sources to have the samefid_. <strong>The</strong> fid_ starts <strong>at</strong> 1 for the first source <strong>and</strong> is increased by one for each new source. Be careful to avoid other flows(for i<strong>ns</strong>tance concurrent TCP flows) to have the same fid_ than the PLM sources. Additionally, If you co<strong>ns</strong>ider fid_ largerthan 32, do not forget to increase the MAXFLOW in ~<strong>ns</strong>/fq.cc (MAXFLOW must be set to the highest fid_ co<strong>ns</strong>idered in thesimul<strong>at</strong>ion).37.3.2 I<strong>ns</strong>tanti<strong>at</strong>ion of a PLM ReceiverAll the PLM machinery is implemented <strong>at</strong> the receiver. In this section we decribe the i<strong>ns</strong>tanti<strong>at</strong>ion process of a receiver. To cre<strong>at</strong>e,place <strong>at</strong> node n, <strong>at</strong>tach to source S, <strong>and</strong> start <strong>at</strong> t 1 a PLM receiver we call the PLMTopology i<strong>ns</strong>tproc build_receivern addr t 1 C where addr is the address returned by place_source when S was cre<strong>at</strong>ed, <strong>and</strong> C is the check value. <strong>The</strong>receiver cre<strong>at</strong>ed by build_receiver is an i<strong>ns</strong>tance of the class PLM/<strong>ns</strong>, the <strong>ns</strong> interface to the PLM machinery. Atthe initialis<strong>at</strong>ion of the receiver, the PLM i<strong>ns</strong>tproc init is called due to inheritance. init calls the PLM/<strong>ns</strong> i<strong>ns</strong>tproc326


UserInheritPLMTopologyI<strong>ns</strong>tanti<strong>at</strong>ePLMPLM/<strong>ns</strong>PLMLayerPLMLayerPLMLayer/<strong>ns</strong>PLMLayer/<strong>ns</strong>Agent/LossMonitor/PLMAgent/LossMonitor/PLMPLMLossTracePLMLossTraceNumber of layersFigure 37.1: Inheritance <strong>and</strong> i<strong>ns</strong>tanti<strong>at</strong>ion when we cre<strong>at</strong>e a receiver.cre<strong>at</strong>e-layer <strong>and</strong>, by this way, cre<strong>at</strong>es as many i<strong>ns</strong>tances of the class PLMLayer/<strong>ns</strong> (the <strong>ns</strong> interface to the PLMLayerclass) as there are layers. Each i<strong>ns</strong>tance of PLMLayer/<strong>ns</strong> cre<strong>at</strong>es an i<strong>ns</strong>tance of the class PLMLossTrace which is repo<strong>ns</strong>iblefor monitoring the received <strong>and</strong> lost packets thanks to the fact th<strong>at</strong> the class PLMLossTrace inherits from the classAgent/LossMonitor/PLM. Fig. 37.1 schem<strong>at</strong>ically describes the process of a PLM receiver i<strong>ns</strong>tanti<strong>at</strong>ion. In the following wedescribe the behavior of a PLM receiver when it receives a packet <strong>and</strong> when it detects a loss.37.3.3 Reception of a PacketWe cre<strong>at</strong>e a new c++ class PLMLossMonitor (~<strong>ns</strong>/plm/loss-monitor-plm.cc) th<strong>at</strong> inherits from LossMonitor. <strong>The</strong> OTcl classname of the c++ PLMLossMonitor class is Agent/LossMonitor/PLM.class PLMLossMonitor : public LossMonitorpublic:PLMLossMonitor();virtual void recv(Packet* pkt, H<strong>and</strong>ler*);protected:// PLM onlyint flag_PP_;double packet_time_PP_;int fid_PP_;;st<strong>at</strong>ic class PLMLossMonitorClass : public TclClasspublic:PLMLossMonitorClass() : TclClass("Agent/LossMonitor/PLM")TclObject* cre<strong>at</strong>e(int, co<strong>ns</strong>t char*co<strong>ns</strong>t*)return (new PLMLossMonitor());class_loss_mon_plm;327


We add in void PLMLossMonitor::recv(Packet* pkt, H<strong>and</strong>ler*) a Tcl call to the Agent/LossMonitor/PLMi<strong>ns</strong>tproc log-PP each time a packet is received :void LossMonitor::recv(Packet* pkt, H<strong>and</strong>ler*)...if (expected_ >= 0)...Tcl::i<strong>ns</strong>tance().evalf("%s log-PP", name());<strong>The</strong> Agent/LossMonitor/PLM i<strong>ns</strong>tproc log-PP is empty. In fact, we define the log-PP i<strong>ns</strong>tproc for the classPLMLossTrace. log-PP computes an estim<strong>at</strong>e of the available b<strong>and</strong>width based on a single PP burst (of lengthPP_burst_length in packets). Once log-PP has received the PP_burst_length packets of the burst, it computesthe estim<strong>at</strong>e <strong>and</strong> calls the PLM i<strong>ns</strong>tproc make_estim<strong>at</strong>e with the computed estim<strong>at</strong>e as argument.make_estim<strong>at</strong>e puts the estim<strong>at</strong>e based on a single PP (PP_value) in an array of estim<strong>at</strong>e samples (PP_estim<strong>at</strong>e).If PP_value is lower than the current subscription level (i.e. lower than the throughput achieved according to thecurrent number of layers subscribed), make_estim<strong>at</strong>e calls the PLM i<strong>ns</strong>tproc stability-drop which simplydrops layers until the current subscription level becomes lower than PP_value. make_estim<strong>at</strong>e makes an estim<strong>at</strong>ePP_estim<strong>at</strong>e_value by taking the minimum PP_value received during the last check_estim<strong>at</strong>e period(if there are <strong>at</strong> least PP_estim<strong>at</strong>ion_length single PP estim<strong>at</strong>e received). Once make_estim<strong>at</strong>e has aPP_estim<strong>at</strong>e_value it calls the PLM i<strong>ns</strong>tproc choose_layer which joi<strong>ns</strong> or drops layer(s) according to the currentsubscription level <strong>and</strong> to the PP_estim<strong>at</strong>e_value. For details about the PLM i<strong>ns</strong>tproc make_estim<strong>at</strong>e, refer toits code in ~<strong>ns</strong>/tcl/plm/plm.tcl.37.3.4 Detection of a LossEach time a loss is detected by an i<strong>ns</strong>tance of the class PLMLossMonitor, a call to the Agent/LossMonitor/PLM i<strong>ns</strong>tproclog-loss is triggered. <strong>The</strong> Agent/LossMonitor/PLM i<strong>ns</strong>tproc log-loss is empty. In fact, we define the log-lossi<strong>ns</strong>tproc for the class PLMLossTrace. <strong>The</strong> PLMLossTrace i<strong>ns</strong>tproc log-loss simply calls the PLM i<strong>ns</strong>tproc log-losswhich contai<strong>ns</strong> the PLM machinery in case of loss. In summary, log-loss only drops a layer when the loss r<strong>at</strong>e exceeds10% (this test is executed by the PLM i<strong>ns</strong>tproc exeed_loss_thresh). After a layer drop log-loss precludes any otherlayer drop due to loss for 500ms. For details about the PLM i<strong>ns</strong>tproc log-loss, refer to its code in ~<strong>ns</strong>/tcl/plm/plm.tcl.37.3.5 Joining or Leaving a LayerTo join a layer the PLM i<strong>ns</strong>tproc add-layer is called. This i<strong>ns</strong>tproc calls the PLMLayer i<strong>ns</strong>tproc join-group whichcalls the PLMLayer/<strong>ns</strong> i<strong>ns</strong>tproc join-group. To leave a layer the PLM i<strong>ns</strong>tproc drop-layer is called. This i<strong>ns</strong>tproccalls the PLMLayer i<strong>ns</strong>tproc leave-group which calls the PLMLayer/<strong>ns</strong> i<strong>ns</strong>tproc leave-group.37.4 Comm<strong>and</strong>s <strong>at</strong> a GlanceNote: This section is a copy paste of the end of section 37.1. We add this section to preserve homogeneity with the <strong>ns</strong> manual.328


All the simul<strong>at</strong>io<strong>ns</strong> for PLM should be set using the PLMTopology environment (as in the example script where we define aPLMTopology superclass called Scenario0). <strong>The</strong> user interface is (all the i<strong>ns</strong>tproc can be found in ~<strong>ns</strong>/tcl/plm/plm-topo.tcl):build_link a b d bw cre<strong>at</strong>es a duplex link between node a <strong>and</strong> b with a delay d <strong>and</strong> a b<strong>and</strong>width bw. If either nodedoes not exist, build_link cre<strong>at</strong>es it.place_source n t cre<strong>at</strong>es <strong>and</strong> places a PLM source <strong>at</strong> node n <strong>and</strong> starts it <strong>at</strong> time t. place_source retur<strong>ns</strong> addrwhich allows to <strong>at</strong>tach receivers to this source.place_receiver n addr C nb cre<strong>at</strong>es <strong>and</strong> places a PLM receiver <strong>at</strong> node n <strong>and</strong> <strong>at</strong>tached it to the source which returnthe address addr. <strong>The</strong> check value for this PLM receiver is C. An optional parameter nb allows to get an i<strong>ns</strong>tanceof the PLM receiver called PLMrcvr($nb). This i<strong>ns</strong>tance is only useful to get some specific st<strong>at</strong>istics about thisreceiver (mainly the number of packets received or lost).329


Part VIApplic<strong>at</strong>ion330


Chapter 38Applic<strong>at</strong>io<strong>ns</strong> <strong>and</strong> tra<strong>ns</strong>port agent APIApplic<strong>at</strong>io<strong>ns</strong> sit on top of tra<strong>ns</strong>port agents in <strong>ns</strong>. <strong>The</strong>re are two basic types of applic<strong>at</strong>io<strong>ns</strong>: traffic gener<strong>at</strong>ors <strong>and</strong> simul<strong>at</strong>ed applic<strong>at</strong>io<strong>ns</strong>.Figure 38.1 illustr<strong>at</strong>es two examples of how applic<strong>at</strong>io<strong>ns</strong> are composed <strong>and</strong> <strong>at</strong>tached to tra<strong>ns</strong>port agents. Tra<strong>ns</strong>portagents are described in Part V (Tra<strong>ns</strong>port).This chapter first describes the base class Applic<strong>at</strong>ion. Next, the tra<strong>ns</strong>port API, through which applic<strong>at</strong>io<strong>ns</strong> requestservices from underlying tra<strong>ns</strong>port agents, is described. Finally, the current implement<strong>at</strong>io<strong>ns</strong> of traffic gener<strong>at</strong>ors <strong>and</strong> sourcesare explained.38.1 <strong>The</strong> class Applic<strong>at</strong>ionApplic<strong>at</strong>ion is a C++ class defined as follows:class Applic<strong>at</strong>ion : public TclObject {public:Applic<strong>at</strong>ion();virtual void send(int nbytes);virtual void recv(int nbytes);virtual void resume();protected:int comm<strong>and</strong>(int argc, co<strong>ns</strong>t char*co<strong>ns</strong>t* argv);virtual void start();virtual void stop();Agent *agent_;int enableRecv_;// call OTcl recv or notint enableResume_;// call OTcl resume or not};Although objects of class Applic<strong>at</strong>ion are not meant to be i<strong>ns</strong>tanti<strong>at</strong>ed, we do not make it an abstract base classso th<strong>at</strong> it is visible from OTcl level. <strong>The</strong> class provides basic prototypes for applic<strong>at</strong>ion behavior (send(), recv(),resume(), start(), stop()), a pointer to the tra<strong>ns</strong>port agent to which it is connected, <strong>and</strong> flags th<strong>at</strong> indic<strong>at</strong>e whethera OTcl-level upcall should be made for recv() <strong>and</strong> resume() events.331


Traffic gener<strong>at</strong>orsApplic<strong>at</strong>ion/Traffic/ExponentialSimul<strong>at</strong>ed applic<strong>at</strong>io<strong>ns</strong>Applic<strong>at</strong>ion/FTPAPIAPIAgent/UDPAgent/TCP/FullTcp38.2 <strong>The</strong> tra<strong>ns</strong>port agent APIFigure 38.1: Example of Applic<strong>at</strong>ion CompositionIn real-world systems, applic<strong>at</strong>io<strong>ns</strong> typically access network services through an applic<strong>at</strong>io<strong>ns</strong> programming interface (API).<strong>The</strong> most popular of these APIs is known as “sockets.” In <strong>ns</strong>, we mimic the behavior of the sockets API through a setof well-defined API functio<strong>ns</strong>. <strong>The</strong>se functio<strong>ns</strong> are then mapped to the appropri<strong>at</strong>e internal agent functio<strong>ns</strong> (e.g., a call tosend(numBytes) causes TCP to increment its “send buffer” by a corresponding number of bytes).This section describes how agents <strong>and</strong> applic<strong>at</strong>io<strong>ns</strong> are hooked together <strong>and</strong> communic<strong>at</strong>e with one another via the API.38.2.1 Attaching tra<strong>ns</strong>port agents to nodesThis step is typically done <strong>at</strong> OTcl level. Agent management was also briefly discussed in Section 5.2.set src [new Agent/TCP/FullTcp]set sink [new Agent/TCP/FullTcp]$<strong>ns</strong>_ <strong>at</strong>tach-agent $node_(s1) $src$<strong>ns</strong>_ <strong>at</strong>tach-agent $node_(k1) $sink$<strong>ns</strong>_ connect $src $sink<strong>The</strong> above code illustr<strong>at</strong>es th<strong>at</strong> in <strong>ns</strong>, agents are first <strong>at</strong>tached to a node via <strong>at</strong>tach-agent. Next, the connect i<strong>ns</strong>tprocsets each agent’s destin<strong>at</strong>ion target to the other. Note th<strong>at</strong>, in <strong>ns</strong>, connect() has different semantics than in regular sockets.In <strong>ns</strong>, connect() simply establishes the destin<strong>at</strong>ion address for an agent, but does not set up the connection. As a result,the overlying applic<strong>at</strong>ion does not need to know its peer’s address. For TCPs th<strong>at</strong> exchange SYN segments, the first call tosend() will trigger the SYN exchange.To detach an agent from a node, the i<strong>ns</strong>tproc detach-agent can be used; this resets the target for the agent to a null agent.332


38.2.2 Attaching applic<strong>at</strong>io<strong>ns</strong> to agentsAfter applic<strong>at</strong>io<strong>ns</strong> are i<strong>ns</strong>tanti<strong>at</strong>ed, they must be connected to a tra<strong>ns</strong>port agent. <strong>The</strong> <strong>at</strong>tach-agent method can be used to<strong>at</strong>tach an applic<strong>at</strong>ion to an agent, as follows:set ftp1 [new Applic<strong>at</strong>ion/FTP]$ftp1 <strong>at</strong>tach-agent $src<strong>The</strong> following shortcut accomplishes the same result:set ftp1 [$src <strong>at</strong>tach-app FTP]<strong>The</strong> <strong>at</strong>tach-agent method, which is also used by <strong>at</strong>tach-app, is implemented in C++. It sets the agent_ pointer in classApplic<strong>at</strong>ion to point to the tra<strong>ns</strong>port agent, <strong>and</strong> then it calls <strong>at</strong>tachApp() in agent.cc to set the app_ pointerto point back to the applic<strong>at</strong>ion. By maintaining this binding only in C++, OTcl-level i<strong>ns</strong>tvars pointers are avoided <strong>and</strong>co<strong>ns</strong>istency between OTcl <strong>and</strong> C++ is guaranteed. <strong>The</strong> OTcl-level comm<strong>and</strong> [$ftp1 agent] can be used by applic<strong>at</strong>io<strong>ns</strong>to obtain the h<strong>and</strong>ler for the tra<strong>ns</strong>port agent.38.2.3 Using tra<strong>ns</strong>port agents via system callsOnce tra<strong>ns</strong>port agents have been configured <strong>and</strong> applic<strong>at</strong>io<strong>ns</strong> <strong>at</strong>tached, applic<strong>at</strong>io<strong>ns</strong> can use tra<strong>ns</strong>port services via the followingsystem calls. <strong>The</strong>se calls can be invoked <strong>at</strong> either OTcl or C++ level, thereby allowing applic<strong>at</strong>io<strong>ns</strong> to be coded in either C++or OTcl. <strong>The</strong>se functio<strong>ns</strong> have been implemented as virtual functio<strong>ns</strong> in the base class Agent, <strong>and</strong> can be redefined asneeded by derived Agents.• send(int nbytes)—Send nbytes of d<strong>at</strong>a to peer. For TCP agents, if nbytes == -1, this corresponds to an“infinite” send; i.e., the TCP agent will act as if its send buffer is continually replenished by the applic<strong>at</strong>ion.• sendmsg(int nbytes, co<strong>ns</strong>t char* flags = 0)—Identical to send(int nbytes), except th<strong>at</strong> it passesan additional string flags. Currently one flag value, “MSG_EOF,” is defined; MSG_EOF specifies th<strong>at</strong> this is the lastb<strong>at</strong>ch of d<strong>at</strong>a th<strong>at</strong> the applic<strong>at</strong>ion will submit, <strong>and</strong> serves as an implied close (so th<strong>at</strong> TCP can send FIN with d<strong>at</strong>a).• close()—Requests the agent to close the connection (only applicable for TCP).• listen()—Requests the agent to listen for new connectio<strong>ns</strong> (only applicable for Full TCP).• set_pkttype(int pkttype)—This function sets the type_ variable in the agent to pkttype. Packet typesare defined in packet.h. This function is used to override the tra<strong>ns</strong>port layer packet type for tracing purposes.Note th<strong>at</strong> certain calls are not applicable for certain agents; e.g., a call to close() a UDP connection results in a no-op.Additional calls can be implemented in specialized agents, provided th<strong>at</strong> they are made public member functio<strong>ns</strong>.38.2.4 Agent upcalls to applic<strong>at</strong>io<strong>ns</strong>Since presently in <strong>ns</strong> there is no actual d<strong>at</strong>a being passed between applic<strong>at</strong>io<strong>ns</strong>, agents can i<strong>ns</strong>tead announce to applic<strong>at</strong>io<strong>ns</strong>the occurrence of certain events <strong>at</strong> the tra<strong>ns</strong>port layer through “upcalls.” For example, applic<strong>at</strong>io<strong>ns</strong> can be notified of thearrival of a number of bytes of d<strong>at</strong>a; this inform<strong>at</strong>ion may aid the applic<strong>at</strong>ion in modelling real-world applic<strong>at</strong>ion behaviormore closely. Two basic “upcalls” have been implemented in base class Applic<strong>at</strong>ion <strong>and</strong> in the tra<strong>ns</strong>port agents:333


• recv(int nbytes)—Announces th<strong>at</strong> nbytes of d<strong>at</strong>a have been received by the agent. For UDP agents, thissignifies the arrival of a single packet. For TCP agents, this signifies the “delivery” of an amount of in-sequence d<strong>at</strong>a,which may be larger than th<strong>at</strong> contained in a single packet (due to the possibility of network reordering).• resume()—This indic<strong>at</strong>es to the applic<strong>at</strong>ion th<strong>at</strong> the tra<strong>ns</strong>port agent has sent out all of the d<strong>at</strong>a submitted to it up toth<strong>at</strong> point in time. For TCP, it does not indic<strong>at</strong>e whether the d<strong>at</strong>a has been ACKed yet, only th<strong>at</strong> it has been sent out forthe first time.<strong>The</strong> default behavior is as follows: Depending on whether the applic<strong>at</strong>ion has been implemented in C++ or OTcl, these C++functio<strong>ns</strong> call a similarly named (recv, resume) function in the applic<strong>at</strong>ion, if such methods have been defined.Although strictly not a callback to applic<strong>at</strong>io<strong>ns</strong>, certain Agents have implemented a callback from C++ to OTcl-level th<strong>at</strong>has been used by applic<strong>at</strong>io<strong>ns</strong> such as HTTP simul<strong>at</strong>ors. This callback method, done{}, is used in TCP agents. In TCP,done{} is called when a TCP sender has received ACKs for all of its d<strong>at</strong>a <strong>and</strong> is now closed; it therefore can be used tosimul<strong>at</strong>e a blocked TCP connection. <strong>The</strong> done{} method was primarily used before this API was completed, but may stillbe useful for applic<strong>at</strong>io<strong>ns</strong> th<strong>at</strong> do not want to use resume().To use done{} for FullTcp, for example, you can try:set myagent [new Agent/TCP/FullTcp]$myagent proc done... code you want ...If you want all the FullTCP’s to have the same code you could also do:Agent/TCP/FullTcp i<strong>ns</strong>tproc done... code you want ...By default, done{} does nothing.38.2.5 An exampleHere is an example of how the API is used to implement a simple applic<strong>at</strong>ion (FTP) on top of a FullTCP connection.set src [new Agent/TCP/FullTcp]set sink [new Agent/TCP/FullTcp]$<strong>ns</strong>_ <strong>at</strong>tach-agent $node_(s1) $src$<strong>ns</strong>_ <strong>at</strong>tach-agent $node_(k1) $sink$<strong>ns</strong>_ connect $src $sink# set up TCP-level connectio<strong>ns</strong>$sink listen;$src set window_ 100set ftp1 [new Applic<strong>at</strong>ion/FTP]$ftp1 <strong>at</strong>tach-agent $src$<strong>ns</strong>_ <strong>at</strong> 0.0 "$ftp1 start"334


In the configur<strong>at</strong>ion script, the first five lines of code alloc<strong>at</strong>es two new FullTcp agents, <strong>at</strong>taches them to the correct nodes,<strong>and</strong> "connects" them together (assig<strong>ns</strong> the correct destin<strong>at</strong>ion addresses to each agent). <strong>The</strong> next two lines configure theTCP agents further, placing one of them in LISTEN mode. Next, ftp1 is defined as a new FTP Applic<strong>at</strong>ion, <strong>and</strong> the<strong>at</strong>tach-agent method is called in C++ (app.cc).<strong>The</strong> ftp1 applic<strong>at</strong>ion is started <strong>at</strong> time 0:Applic<strong>at</strong>ion/FTP i<strong>ns</strong>tproc start {} {[$self agent] send -1; # Send indefinitely}Altern<strong>at</strong>ively, the FTP applic<strong>at</strong>ion could have been implemented in C++ as follows:void FTP::start(){agent_->send(-1);}// Send indefinitelySince the FTP applic<strong>at</strong>ion does not make use of callbacks, these functio<strong>ns</strong> are null in C++ <strong>and</strong> no OTcl callbacks are made.38.3 <strong>The</strong> class TrafficGener<strong>at</strong>orTrafficGener<strong>at</strong>or is an abstract C++ class defined as follows:class TrafficGener<strong>at</strong>or : public Applic<strong>at</strong>ion {public:TrafficGener<strong>at</strong>or();virtual double next_interval(int &) = 0;virtual void init() {}virtual double interval() { return 0; }virtual int on() { return 0; }virtual void timeout();virtual void recv() {}virtual void resume() {}protected:virtual void start();virtual void stop();double nextPkttime_;int size_;int running_;TrafficTimer timer_;};<strong>The</strong> pure virtual function next_interval() retur<strong>ns</strong> the time until the next packet is cre<strong>at</strong>ed <strong>and</strong> also sets the size in bytesof the next packet. <strong>The</strong> function start() calls init(void) <strong>and</strong> starts the timer. <strong>The</strong> function timeout() sends a packet <strong>and</strong>reschedules the next timeout. <strong>The</strong> function stop() cancels any pending tra<strong>ns</strong>missio<strong>ns</strong>. Callbacks are typically not used fortraffic gener<strong>at</strong>ors, so these functio<strong>ns</strong> (recv, resume) are null.Currently, there are four C++ classes derived from the class TrafficGener<strong>at</strong>or:335


1. EXPOO_Traffic—gener<strong>at</strong>es traffic according to an Exponential On/Off distribution. Packets are sent <strong>at</strong> a fixed r<strong>at</strong>eduring on periods, <strong>and</strong> no packets are sent during off periods. Both on <strong>and</strong> off periods are taken from an exponentialdistribution. Packets are co<strong>ns</strong>tant size.2. POO_Traffic—gener<strong>at</strong>es traffic according to a Pareto On/Off distribution. This is identical to the ExponentialOn/Off distribution, except the on <strong>and</strong> off periods are taken from a pareto distribution. <strong>The</strong>se sources can be used togener<strong>at</strong>e aggreg<strong>at</strong>e traffic th<strong>at</strong> exhibits long range dependency.3. CBR_Traffic—gener<strong>at</strong>es traffic according to a deterministic r<strong>at</strong>e. Packets are co<strong>ns</strong>tant size. Optionally, somer<strong>and</strong>omizing dither can be enabled on the interpacket departure intervals.4. TrafficTrace—gener<strong>at</strong>es traffic according to a trace file. Each record in the trace file co<strong>ns</strong>ists of 2 32-bit fields innetwork (big-endian) byte order. <strong>The</strong> first contai<strong>ns</strong> the time in microseconds until the next packet is gener<strong>at</strong>ed. <strong>The</strong>second contai<strong>ns</strong> the length in bytes of the next packet.<strong>The</strong>se classes can be cre<strong>at</strong>ed from OTcl. <strong>The</strong> OTcl classes names <strong>and</strong> associ<strong>at</strong>ed parameters are given below:Exponential On/Off An Exponential On/Off object is embodied in the OTcl class Applic<strong>at</strong>ion/Traffic/Exponential. <strong>The</strong>member variables th<strong>at</strong> parameterize this object are:packetSize_burst_time_idle_time_r<strong>at</strong>e_the co<strong>ns</strong>tant size of the packets gener<strong>at</strong>edthe average “on” time for the gener<strong>at</strong>orthe average “off” time for the gener<strong>at</strong>orthe sending r<strong>at</strong>e during “on” timesHence a new Exponential On/Off traffic gener<strong>at</strong>or can be cre<strong>at</strong>ed <strong>and</strong> parameterized as follows:set e [new Applic<strong>at</strong>ion/Traffic/Exponential]$e set packetSize_ 210$e set burst_time_ 500ms$e set idle_time_ 500ms$e set r<strong>at</strong>e_ 100kNOTE: <strong>The</strong> Exponential On/Off gener<strong>at</strong>or can be configured to behave as a Poisson process by setting the variable burst_time_to 0 <strong>and</strong> the variable r<strong>at</strong>e_ to a very large value. <strong>The</strong> C++ code guarantees th<strong>at</strong> even if the burst time is zero, <strong>at</strong> least onepacket is sent. Additionally, the next interarrival time is the sum of the assumed packet tra<strong>ns</strong>mission time (governed by thevariable r<strong>at</strong>e_) <strong>and</strong> the r<strong>and</strong>om vari<strong>at</strong>e corresponding to idle_time_. <strong>The</strong>refore, to make the first term in the sum verysmall, make the burst r<strong>at</strong>e very large so th<strong>at</strong> the tra<strong>ns</strong>mission time is negligible compared to the typical idle times.Pareto On/Off A Pareto On/Off object is embodied in the OTcl class Applic<strong>at</strong>ion/Traffic/Pareto. <strong>The</strong> member variablesth<strong>at</strong> parameterize this object are:packetSize_burst_time_idle_time_r<strong>at</strong>e_shape_the co<strong>ns</strong>tant size of the packets gener<strong>at</strong>edthe average "on" time for the gener<strong>at</strong>orthe average "off" time for the gener<strong>at</strong>orthe sending r<strong>at</strong>e during "on" timesthe "shape" parameter used by the pareto distributionA new Pareto On/Off traffic gener<strong>at</strong>or can be cre<strong>at</strong>ed as follows:336


set p [new Applic<strong>at</strong>ion/Traffic/Pareto]$p set packetSize_ 210$p set burst_time_ 500ms$p set idle_time_ 500ms$p set r<strong>at</strong>e_ 200k$p set shape_ 1.5CBR A CBR object is embodied in the OTcl class Applic<strong>at</strong>ion/Traffic/CBR. <strong>The</strong> member variables th<strong>at</strong> parameterize thisobject are:r<strong>at</strong>e_ the sending r<strong>at</strong>einterval_ (Optional) interval between packetspacketSize_ the co<strong>ns</strong>tant size of the packets gener<strong>at</strong>edr<strong>and</strong>om_ flag indic<strong>at</strong>ing whether or not to introduce r<strong>and</strong>om “noise” in the scheduled departure times (default isoff)maxpkts_ the maximum number of packets to send (default is (2 2 8)Hence a new CBR traffic gener<strong>at</strong>or can be cre<strong>at</strong>ed <strong>and</strong> parameterized as follows:set e [new Applic<strong>at</strong>ion/Traffic/CBR]$e set packetSize_ 48$e set r<strong>at</strong>e_ 64Kb$e set r<strong>and</strong>om_ 1<strong>The</strong> setting of a CBR object’s r<strong>at</strong>e_ <strong>and</strong> interval_ are mutually exclusive (the interval between packets is maintainedas an interval variable in C++, <strong>and</strong> some example <strong>ns</strong> scripts specify an interval r<strong>at</strong>her than a r<strong>at</strong>e). In a simul<strong>at</strong>ion, either ar<strong>at</strong>e or an interval (but not both) should be specified for a CBR object.Traffic Trace A Traffic Trace object is i<strong>ns</strong>tanti<strong>at</strong>ed by the OTcl class Applic<strong>at</strong>ion/Traffic/Trace. <strong>The</strong> associ<strong>at</strong>ed class Tracefileis used to enable multiple Traffic/Trace objects to be associ<strong>at</strong>ed with a single trace file. <strong>The</strong> Traffic/Trace class usesthe method <strong>at</strong>tach-tracefile to associ<strong>at</strong>e a Traffic/Trace object with a particular Tracefile object. <strong>The</strong> method filename ofthe Tracefile class associ<strong>at</strong>es a trace file with the Tracefile object. <strong>The</strong> following example shows how to cre<strong>at</strong>e two Applic<strong>at</strong>ion/Traffic/Traceobjects, each associ<strong>at</strong>ed with the same trace file (called "example-trace" in this example). To avoidsynchroniz<strong>at</strong>ion of the traffic gener<strong>at</strong>ed, r<strong>and</strong>om starting places within the trace file are chosen for each Traffic/Trace object.set tfile [new Tracefile]$tfile filename example-traceset t1 [new Applic<strong>at</strong>ion/Traffic/Trace]$t1 <strong>at</strong>tach-tracefile $tfileset t2 [new Applic<strong>at</strong>ion/Traffic/Trace]$t2 <strong>at</strong>tach-tracefile $tfile38.3.1 An example<strong>The</strong> following code illustr<strong>at</strong>es the basic steps to configure an Exponential traffic source over a UDP agent, for traffic flowingfrom node s1 to node k1:337


set src [new Agent/UDP]set sink [new Agent/UDP]$<strong>ns</strong>_ <strong>at</strong>tach-agent $node_(s1) $src$<strong>ns</strong>_ <strong>at</strong>tach-agent $node_(k1) $sink$<strong>ns</strong>_ connect $src $sinkset e [new Applic<strong>at</strong>ion/Traffic/Exponential]$e <strong>at</strong>tach-agent $src$e set packetSize_ 210$e set burst_time_ 500ms$e set idle_time_ 500ms$e set r<strong>at</strong>e_ 100k$<strong>ns</strong>_ <strong>at</strong> 0.0 "$e start"38.4 Simul<strong>at</strong>ed applic<strong>at</strong>io<strong>ns</strong>: Telnet <strong>and</strong> FTP<strong>The</strong>re are currently two “simul<strong>at</strong>e applic<strong>at</strong>ion” classes derived from Applic<strong>at</strong>ion: Applic<strong>at</strong>ion/FTP <strong>and</strong> Applic<strong>at</strong>ion/Telnet.<strong>The</strong>se classes work by advancing the count of packets available to be sent by a TCP tra<strong>ns</strong>port agent. <strong>The</strong> actual tra<strong>ns</strong>missionof available packets is still controlled by TCP’s flow <strong>and</strong> congestion control algorithm.Applic<strong>at</strong>ion/FTP Applic<strong>at</strong>ion/FTP, implemented in OTcl, simul<strong>at</strong>es bulk d<strong>at</strong>a tra<strong>ns</strong>fer. <strong>The</strong> following are methods of theApplic<strong>at</strong>ion/FTP class:<strong>at</strong>tach-agentstartstop<strong>at</strong>taches an Applic<strong>at</strong>ion/FTP object to an agent.start the Applic<strong>at</strong>ion/FTP by calling the TCP agent’s send(-1) function, which causes TCP tobehave as if the applic<strong>at</strong>ion were continuously sending new d<strong>at</strong>a.stop sending.produce n set the counter of packets to be sent to n.producemore n increase the counter of packets to be sent by n.send n similar to producemore, but sends n bytes i<strong>ns</strong>tead of packets.Applic<strong>at</strong>ion/Telnet Applic<strong>at</strong>ion/Telnet objects gener<strong>at</strong>e packets in one of two ways. If the member variable interval_is non-zero, then inter-packet times are chosen from an exponential distribution with average equal to interval_. Ifinterval_ is zero, then inter-arrival times are chosen according to the tcplib distribution (see tcplib-telnet.cc). <strong>The</strong> startmethod starts the packet gener<strong>at</strong>ion process.38.5 Applic<strong>at</strong>io<strong>ns</strong> objectsAn applic<strong>at</strong>ion object may be of two types, a traffic gener<strong>at</strong>or or a simul<strong>at</strong>ed applic<strong>at</strong>ion. Traffic gener<strong>at</strong>or objects gener<strong>at</strong>etraffic <strong>and</strong> can be of four types, namely, exponential, pareto, CBR <strong>and</strong> traffic trace.Applic<strong>at</strong>ion/Traffic/Exponential objects Exponential traffic objects gener<strong>at</strong>e On/Off traffic. During "on" periods, packetsare gener<strong>at</strong>ed <strong>at</strong> a co<strong>ns</strong>tant burst r<strong>at</strong>e. During "off" periods, no traffic is gener<strong>at</strong>ed. Burst times <strong>and</strong> idle times are takenfrom exponential distributio<strong>ns</strong>. Configur<strong>at</strong>ion parameters are:338


PacketSize_ co<strong>ns</strong>tant size of packets gener<strong>at</strong>ed.burst_time_ average on time for gener<strong>at</strong>or.idle_time_ average off time for gener<strong>at</strong>or.r<strong>at</strong>e_ sending r<strong>at</strong>e during on time.Applic<strong>at</strong>ion/Traffic/Pareto Applic<strong>at</strong>ion/Traffic/Pareto objects gener<strong>at</strong>e On/Off traffic with burst times <strong>and</strong> idle times takenfrom pareto distributio<strong>ns</strong>. Configur<strong>at</strong>ion parameters are:PacketSize_ co<strong>ns</strong>tant size of packets gener<strong>at</strong>ed.burst_time_ average on time for gener<strong>at</strong>or.idle_time_ average off time for gener<strong>at</strong>or.r<strong>at</strong>e_ sending r<strong>at</strong>e during on time.shape_ the shape parameter used by pareto distribution.Applic<strong>at</strong>ion/Traffic/CBR CBR objects gener<strong>at</strong>e packets <strong>at</strong> a co<strong>ns</strong>tant bit r<strong>at</strong>e.$cbr startCauses the source to start gener<strong>at</strong>ing packets.$cbr stopCauses the source to stop gener<strong>at</strong>ing packets.Configur<strong>at</strong>ion parameters are:PacketSize_ co<strong>ns</strong>tant size of packets gener<strong>at</strong>ed.r<strong>at</strong>e_ sending r<strong>at</strong>e.interval_ (optional) interval between packets.r<strong>and</strong>om_ whether or not to introduce r<strong>and</strong>om noise in the scheduled departure times. defualt is off.maxpkts_ maximum number of packets to send.Applic<strong>at</strong>ion/Traffic/Trace Applic<strong>at</strong>ion/Traffic/Trace objects are used to gener<strong>at</strong>e traffic from a trace file. $trace <strong>at</strong>tach-tracefiletfileAttach the Tracefile object tfile to this trace. <strong>The</strong> Tracefile object specifies the trace file from which the traffic d<strong>at</strong>a isto be read. Multiple Applic<strong>at</strong>ion/Traffic/Trace objects can be <strong>at</strong>tached to the same Tracefile object. A r<strong>and</strong>om startingplace within the Tracefile is chosen for each Applic<strong>at</strong>ion/Traffic/Trace object.<strong>The</strong>re are no configur<strong>at</strong>ion parameters for this object.A simul<strong>at</strong>ed applic<strong>at</strong>ion object can be of two types, Telnet <strong>and</strong> FTP.Applic<strong>at</strong>ion/Telnet TELNET objects produce individual packets with inter-arrival times as follows. If interval_ is non-zero,then inter-arrival times are chosen from an exponential distribution with average interval_. If interval_ is zero, theninter-arrival times are chosen using the "tcplib" telnet distribution.$telnet startCauses the Applic<strong>at</strong>ion/Telnet object to start producing packets.$telnet stopCauses the Applic<strong>at</strong>ion/Telnet object to stop producing packets.$telnet <strong>at</strong>tach Attaches a Telnet object to agent.Configur<strong>at</strong>ion Parameters are:interval_ <strong>The</strong> average inter-arrival time in seconds for packets gener<strong>at</strong>ed by the Telnet object.339


Applic<strong>at</strong>ion FTP FTP objects produce bulk d<strong>at</strong>a for a TCP object to send.$ftp startCauses the source to produce maxpkts_ packets.$ftp produce Causes the FTP object to produce n packets i<strong>ns</strong>tantaneously.$ftp stopCauses the <strong>at</strong>tached TCP object to stop sending d<strong>at</strong>a.$ftp <strong>at</strong>tach agentAttaches a Applic<strong>at</strong>ion/FTP object to agent.$ftp producemore Causes the Applic<strong>at</strong>ion/FTP object to produce count more packets.Configur<strong>at</strong>ion Parameters are:maxpkts <strong>The</strong> maximum number of packets gener<strong>at</strong>ed by the source.TRACEFILE OBJECTS Tracefile objects are used to specify the trace file th<strong>at</strong> is to be used for gener<strong>at</strong>ing traffic (see Applic<strong>at</strong>ion/Traffic/Traceobjects described earlier in this section). $tracefile is an i<strong>ns</strong>tance of the Tracefile Object. $tracefilefilename Set the filename from which the traffic trace d<strong>at</strong>a is to be read to trace-input.<strong>The</strong>re are no configur<strong>at</strong>ion parameters for this object. A trace file co<strong>ns</strong>ists of any number of fixed length records. Each recordco<strong>ns</strong>ists of 2 32 bit fields. <strong>The</strong> first indic<strong>at</strong>es the interval until the next packet is gener<strong>at</strong>ed in microseconds. <strong>The</strong> secondindic<strong>at</strong>es the length of the next packet in bytes.38.6 Comm<strong>and</strong>s <strong>at</strong> a glanceFollowing are some tra<strong>ns</strong>port agent <strong>and</strong> applic<strong>at</strong>ion rel<strong>at</strong>ed comm<strong>and</strong>s commonly used in simul<strong>at</strong>ion scripts:set tcp1 [new Agent/TCP]$<strong>ns</strong>_ <strong>at</strong>tach-agent $node_(src) $tcp1set sink1 [new Agent/TCPSink]$<strong>ns</strong>_ <strong>at</strong>tach-agent $node_(snk) $sink1$<strong>ns</strong>_ connect $tcp1 $sink1This cre<strong>at</strong>es a source tcp agent <strong>and</strong> a destin<strong>at</strong>ion sink agent. Both the tra<strong>ns</strong>port agents are <strong>at</strong>tached to their resoective nodes.Finally an end-to-end connection is setup between the src <strong>and</strong> sink.set ftp1 [new Applic<strong>at</strong>ion/FTP]$ftp1 <strong>at</strong>tach-agent $agentor set ftp1 [$agent <strong>at</strong>tach-app FTP] Both the above comm<strong>and</strong>s achieve the same. An applic<strong>at</strong>ion (ftp in thisexample) is cre<strong>at</strong>ed <strong>and</strong> <strong>at</strong>tached to the source agent. An applic<strong>at</strong>ion can be of two types, a traffic gener<strong>at</strong>or or a simul<strong>at</strong>edapplic<strong>at</strong>ion. Types of Traffic gener<strong>at</strong>ors currently present are: Applic<strong>at</strong>ion/Traffic/Exponential, Applic<strong>at</strong>ion/Traffic/Pareto,Applic<strong>at</strong>ion/Traffic/CBR, <strong>and</strong> Applic<strong>at</strong>ion/Traffic/Trace. See section 38.3 for details. Types of simul<strong>at</strong>ed applic<strong>at</strong>io<strong>ns</strong>currently implemented are: Applic<strong>at</strong>ion/FTP <strong>and</strong> Applic<strong>at</strong>ion/Telnet. See section 38.4 for details.340


Chapter 39Web cache as an applic<strong>at</strong>ionAll applic<strong>at</strong>io<strong>ns</strong> described above are “virtual” applic<strong>at</strong>io<strong>ns</strong>, in the se<strong>ns</strong>e th<strong>at</strong> they do not actually tra<strong>ns</strong>fer their own d<strong>at</strong>ain the simul<strong>at</strong>or; all th<strong>at</strong> m<strong>at</strong>ter is the size <strong>and</strong> the time when d<strong>at</strong>a are tra<strong>ns</strong>ferred. Sometimes we may want applic<strong>at</strong>io<strong>ns</strong>to tra<strong>ns</strong>fer their own d<strong>at</strong>a in simul<strong>at</strong>io<strong>ns</strong>. One such example is web caching, where we want HTTP servers to send HTTPheaders to caches <strong>and</strong> clients. <strong>The</strong>se headers contain page modific<strong>at</strong>ion time inform<strong>at</strong>ion <strong>and</strong> other caching directives, whichare important for some cache co<strong>ns</strong>istency algorithms.In the following, we first describe general issues regarding tra<strong>ns</strong>mitting applic<strong>at</strong>ion-level d<strong>at</strong>a in <strong>ns</strong>, then we discuss specialissues, as well as APIs, rel<strong>at</strong>ed to tra<strong>ns</strong>mitting applic<strong>at</strong>ion d<strong>at</strong>a using TCP as tra<strong>ns</strong>port. We will then proceed to discuss theinternal design of HTTP client, server, <strong>and</strong> proxy cache.39.1 Using applic<strong>at</strong>ion-level d<strong>at</strong>a in <strong>ns</strong>In order to tra<strong>ns</strong>mit applic<strong>at</strong>ion-level d<strong>at</strong>a in <strong>ns</strong>, we provide a uniform structure to pass d<strong>at</strong>a among applic<strong>at</strong>io<strong>ns</strong>, <strong>and</strong> topass d<strong>at</strong>a from applic<strong>at</strong>io<strong>ns</strong> to tra<strong>ns</strong>port agents (Figure 39.1). It has three major components: a represent<strong>at</strong>ion of a uniformapplic<strong>at</strong>ion-level d<strong>at</strong>a unit (ADU), a common interface to pass d<strong>at</strong>a between applic<strong>at</strong>io<strong>ns</strong>, <strong>and</strong> two mechanisms to pass d<strong>at</strong>abetween applic<strong>at</strong>io<strong>ns</strong> <strong>and</strong> tra<strong>ns</strong>port agents.39.1.1 ADU<strong>The</strong> functionality of an ADU is similar to th<strong>at</strong> of a Packet. It needs to pack user d<strong>at</strong>a into an array, which is then included inthe user d<strong>at</strong>a area of an <strong>ns</strong>packet by an Agent (this is not supported by current Agents. User must derive new agents to acceptuser d<strong>at</strong>a from applic<strong>at</strong>io<strong>ns</strong>, or use an wrapper like TcpApp. We’ll discuss this l<strong>at</strong>er).Compared with Packet, ADU provides this functionality in a different way. In Packet, a common area is alloc<strong>at</strong>ed for allpacket headers; an offset is used to access different headers in this area. In ADU this is not applicable, because some ADUalloc<strong>at</strong>es their space dynamically according the the availability of user d<strong>at</strong>a. For example, if we want to deliver an OTclscript between applic<strong>at</strong>io<strong>ns</strong>, the size of the script is undetermined beforeh<strong>and</strong>. <strong>The</strong>refore, we choose a less efficient but moreflexible method. Each ADU defines its own d<strong>at</strong>a members, <strong>and</strong> provides methods to serialize them (i.e., pack d<strong>at</strong>a into anarray <strong>and</strong> extract them from an array). For example, in the abstract base class of all ADU, AppD<strong>at</strong>a, we have:class AppD<strong>at</strong>a {341


send_d<strong>at</strong>a(ADU)Applic<strong>at</strong>ion(HttpApp, ...)process_d<strong>at</strong>a(ADU)Applic<strong>at</strong>ion(HttpApp, ...)Agent Wrapper(TcpApp, ...)send_d<strong>at</strong>a(ADU)process_d<strong>at</strong>a(ADU)send(bytes)recv(bytes)Agents supporting user d<strong>at</strong>a(HttpInvalAgent, ...)Agent (TCP, ...)packetspacketsFigure 39.1: Examples of applic<strong>at</strong>ion-level d<strong>at</strong>a flowpriv<strong>at</strong>e:AppD<strong>at</strong>aType type_; // ADU typepublic:struct hdr {AppD<strong>at</strong>aType type_;};public:AppD<strong>at</strong>a(char* b) {assert(b != NULL);type_ = ((hdr *)b)->type_;}virtual void pack(char* buf) co<strong>ns</strong>t;}Here pack(char* buf) is used to write an AppD<strong>at</strong>a object into an array, <strong>and</strong> AppD<strong>at</strong>a(char* b) is used to build anew AppD<strong>at</strong>a from a “serialized” copy of the object in an array.When deriving new ADU from the base class, users may add more d<strong>at</strong>a, but <strong>at</strong> the same time a new pack(char *b) <strong>and</strong>a new co<strong>ns</strong>tructor should be provided to write <strong>and</strong> read those new d<strong>at</strong>a members from an array. For an example as how toderive from an ADU, look <strong>at</strong> <strong>ns</strong>/webcache/http-aux.h.39.1.2 Passing d<strong>at</strong>a between applic<strong>at</strong>io<strong>ns</strong><strong>The</strong> base class of Applic<strong>at</strong>ion, Process, allows applic<strong>at</strong>io<strong>ns</strong> to pass d<strong>at</strong>a or request d<strong>at</strong>a between each other. It is defined asfollows:class Process {public:Process() : target_(0) {}inline Process*& target() { return target_; }342


virtual void process_d<strong>at</strong>a(int size, char* d<strong>at</strong>a) = 0;virtual void send_d<strong>at</strong>a(int size, char* d<strong>at</strong>a = 0);protected:Process* target_;};Process enables Applic<strong>at</strong>ion to link together.39.1.3 Tra<strong>ns</strong>mitting user d<strong>at</strong>a over UDPCurrently there is no support in class Agent to tra<strong>ns</strong>mit user d<strong>at</strong>a. <strong>The</strong>re are two ways to tra<strong>ns</strong>mit a serialized ADU throughtra<strong>ns</strong>port agents. First, for UDP agent (<strong>and</strong> all agents derived from there), we can derive from class UDP <strong>and</strong> add a newmethod send(int nbytes, char *userd<strong>at</strong>a) to pass user d<strong>at</strong>a from Applic<strong>at</strong>ion to Agent. To pass d<strong>at</strong>a from anAgent to an Applic<strong>at</strong>ion is somewh<strong>at</strong> trickier: each agent has a pointer to its <strong>at</strong>tached applic<strong>at</strong>ion, we dynamically cast thispointer to an AppConnector <strong>and</strong> then call AppConnector::process_d<strong>at</strong>a().As an example, we illustr<strong>at</strong>e how class HttpInvalAgent is implemented. It is based on UDP, <strong>and</strong> is intended to deliver webcache invalid<strong>at</strong>ion messages (<strong>ns</strong>/webcache/inval-agent.h). It is defined as:class HttpInvalAgent : public Agent {public:HttpInvalAgent();virtual void recv(Packet *, H<strong>and</strong>ler *);virtual void send(int realsize, AppD<strong>at</strong>a* d<strong>at</strong>a);protected:int off_inv_;};Here recv(Packet*, H<strong>and</strong>ler*) overridden to extract user d<strong>at</strong>a, <strong>and</strong> a new send(int, AppD<strong>at</strong>a*) is providedto include user d<strong>at</strong>a in packetes. An applic<strong>at</strong>ion (HttpApp) is <strong>at</strong>tached to an HttpInvalAgent using Agent::<strong>at</strong>tachApp()(a dynamic cast is needed). In send(), the following code is used to write user d<strong>at</strong>a from AppD<strong>at</strong>a to the user d<strong>at</strong>a area in apacket:Packet *pkt = allocpkt(d<strong>at</strong>a->size());hdr_inval *ih = (hdr_inval *)pkt->access(off_inv_);ih->size() = d<strong>at</strong>a->size();char *p = (char *)pkt->accessd<strong>at</strong>a();d<strong>at</strong>a->pack(p);In recv(), the following code is used to read user d<strong>at</strong>a from packet <strong>and</strong> to deliver to the <strong>at</strong>tached applic<strong>at</strong>ion:hdr_inval *ih = (hdr_inval *)pkt->access(off_inv_);((HttpApp*)app_)->process_d<strong>at</strong>a(ih->size(), (char *)pkt->accessd<strong>at</strong>a());Packet::free(pkt);343


39.1.4 Tra<strong>ns</strong>mitting user d<strong>at</strong>a over TCPTra<strong>ns</strong>mitting user d<strong>at</strong>a using TCP is trickier than doing th<strong>at</strong> over UDP, mainly because of TCP’s reassembly queue is onlyavailable for FullTcp. We deal with this problem by abstracting a TCP connection as a FIFO pipe.As indic<strong>at</strong>ed in section 38.2.4, tra<strong>ns</strong>mission of applic<strong>at</strong>ion d<strong>at</strong>a can be implemented via agent upcalls. Assuming we are usingTCP agents, all d<strong>at</strong>a are delivered in sequence, which mea<strong>ns</strong> we can view the TCP connection as a FIFO pipe. We emul<strong>at</strong>euser d<strong>at</strong>a tra<strong>ns</strong>mission over TCP as follows. We first provide buffer for applic<strong>at</strong>ion d<strong>at</strong>a <strong>at</strong> the sender. <strong>The</strong>n we count the bytesreceived <strong>at</strong> the receiver. When the receiver has got all bytes of the current d<strong>at</strong>a tra<strong>ns</strong>mission, it then gets the d<strong>at</strong>a directly fromthe sender. Class Applic<strong>at</strong>ion/TcpApp is used to implement this functionality.A TcpApp object contai<strong>ns</strong> a pointer to a tra<strong>ns</strong>port agent, presumably either a FullTcp or a SimpleTcp. 1 (Currently TcpAppdoesn’t support asymmetric TCP agents, i.e., sender is separ<strong>at</strong>ed from receiver). It provides the following OTcl interfaces:• connect: Connecting another TcpApp to this one. This connection is bi-directional, i.e., only one call to connectis needed, <strong>and</strong> d<strong>at</strong>a can be sent in either direction.• send: It takes two arguments: (nbytes, str). nbytes is the “nominal” size of applic<strong>at</strong>ion d<strong>at</strong>a. str is applic<strong>at</strong>iond<strong>at</strong>a in string form.In order to send applic<strong>at</strong>ion d<strong>at</strong>a in binary form, TcpApp provides a virtual C++ method send(int nbytes, intdsize, co<strong>ns</strong>t char *d<strong>at</strong>a). In fact, this is the method used to implement the OTcl method send. Because it’sdifficult to deal with binary d<strong>at</strong>a in Tcl, no OTcl interface is provided to h<strong>and</strong>le binary d<strong>at</strong>a. nbytes is the number of bytesto be tra<strong>ns</strong>mitted, dsize is the actual size of the array d<strong>at</strong>a.TcpApp provides a C++ virtual method process_d<strong>at</strong>a(int size, char*d<strong>at</strong>a) to h<strong>and</strong>le the received d<strong>at</strong>a. <strong>The</strong>default h<strong>and</strong>ling is to tre<strong>at</strong> the d<strong>at</strong>a as a tcl script <strong>and</strong> evalu<strong>at</strong>e the script. But it’s easy to derive a class to provide other typesof h<strong>and</strong>ling.Here is an example of using Applic<strong>at</strong>ion/TcpApp. A similar example is Test/TcpApp-2node in <strong>ns</strong>/tcl/test/test-suitewebcache.tcl.First, we cre<strong>at</strong>e FullTcp agents <strong>and</strong> connect them:set tcp1 [new Agent/TCP/FullTcp]set tcp2 [new Agent/TCP/FullTcp]# Set TCP parameters here, e.g., window_, iss_, . . .$<strong>ns</strong> <strong>at</strong>tach-agent $n1 $tcp1$<strong>ns</strong> <strong>at</strong>tach-agent $n2 $tcp2$<strong>ns</strong> connect $tcp1 $tcp2$tcp2 listen<strong>The</strong>n we cre<strong>at</strong>e TcpApps <strong>and</strong> connect them:set app1 [new Applic<strong>at</strong>ion/TcpApp $tcp1]set app2 [new Applic<strong>at</strong>ion/TcpApp $tcp2]$app1 connect $app21 A SimpleTcp agent is used solely for web caching simul<strong>at</strong>io<strong>ns</strong>. It is actually an UDP agent. It has neither error recovery nor flow/congestion control.It doesn’t do packet segment<strong>at</strong>ion. Assuming a loss-free network <strong>and</strong> in-order packet delivery, SimpleTcp agent simplifies the trace files <strong>and</strong> hence aids thedebugging of applic<strong>at</strong>ion protocols, which, in our case, is the web cache co<strong>ns</strong>istency protocol.344


TclObjectProcessApplic<strong>at</strong>ionHttpApp, ...Applic<strong>at</strong>ion/TcpAppApplic<strong>at</strong>ion/FTPApplic<strong>at</strong>ion/TelnetApplic<strong>at</strong>ion/Traffic/*Figure 39.2: Hierarchy of classes rel<strong>at</strong>ed to applic<strong>at</strong>ion-level d<strong>at</strong>a h<strong>and</strong>lingNow we let $app1 be sender <strong>and</strong> $app2 be receiver:$<strong>ns</strong> <strong>at</strong> 1.0 "$app1 send 100 \"$app2 app-recv 100\""Where app-recv is defined as:Applic<strong>at</strong>ion/TcpApp i<strong>ns</strong>tproc app-recv { size } {global <strong>ns</strong>puts "[$<strong>ns</strong> now] app2 receives d<strong>at</strong>a $size from app1"}39.1.5 Class hierarchy rel<strong>at</strong>ed to user d<strong>at</strong>a h<strong>and</strong>lingWe conclude this section by providing a hierarchy of classes involved in this section (Figure 39.2).39.2 Overview of web cache classes<strong>The</strong>re are three major classes rel<strong>at</strong>ed to web cache, as it is in the real world: client (browser), server, <strong>and</strong> cache. Becausethey share a common fe<strong>at</strong>ure, i.e., the HTTP protocol, they are derived from the same base class Http (Name of OTclclass, it’s called HttpApp in C++). For the following reaso<strong>ns</strong>, it’s not a real Applic<strong>at</strong>ion. First, an HTTP object (i.e.,client/cache/server) may want to maintain multiple concurrent HTTP connectio<strong>ns</strong>, but an Applic<strong>at</strong>ion contai<strong>ns</strong> only oneagent_. Also, an HTTP object needs to tra<strong>ns</strong>mit real d<strong>at</strong>a (e.g., HTTP header) <strong>and</strong> th<strong>at</strong>’s provided by TcpApp i<strong>ns</strong>tead ofany Agent. <strong>The</strong>refore, we choose to use a st<strong>and</strong>alone class derived from TclObject for common fe<strong>at</strong>ures of all HTTP objects,which are managing HTTP connectio<strong>ns</strong> <strong>and</strong> a set of pages. In the rest of the section, we’ll discuss these functionalities ofHttp. In the next three sectio<strong>ns</strong>, we’ll in turn describe HTTP client, cache <strong>and</strong> server.39.2.1 Managing HTTP connectio<strong>ns</strong>Every HTTP connection is embodied as a TcpApp object. Http maintai<strong>ns</strong> a hash of TcpApp objects, which are all of itsactive connectio<strong>ns</strong>. It assumes th<strong>at</strong> to any other Http, it has only one HTTP connection. It also allows dynamic establishment345


<strong>and</strong> teardown of connectio<strong>ns</strong>. Only OTcl interface is provided for establishing, tearing down a connection <strong>and</strong> sending d<strong>at</strong><strong>at</strong>hrough a connection.OTcl methodsFollowing is a list of OTcl interfaces rel<strong>at</strong>ed to connection management in Http objects:idget-cnc 〈client〉is-connected 〈server〉send 〈client〉 〈bytes〉 〈callback〉connect 〈client〉 〈TCP〉disconnect 〈client〉return the id of the Http object, which is the id of the node the object is <strong>at</strong>tached to.return the TCP agent associ<strong>at</strong>ed with $client (Http object).return 0 if not connected to $server, 1 otherwise.send $bytes of d<strong>at</strong>a to $client. When it’s done, execute $callback (a OTcl comm<strong>and</strong>).associ<strong>at</strong>e a TCP agent with $client (Http object). Th<strong>at</strong> agent will be used to send packetsto $client.delete the associ<strong>at</strong>ion of a TCP agent with $client. Note th<strong>at</strong> neither the TCP agent nor$client is not deleted, only the associ<strong>at</strong>ion is deleted.Configur<strong>at</strong>ion parameter By default, Http objects use Agent/SimpleTcp as tra<strong>ns</strong>port agents (section 39.1.4). <strong>The</strong>y canalso use Agent/FullTcp agents, which allows Http objects to oper<strong>at</strong>e in a lossy network. Class variable codeTRANSPORT_is used for this purpose. E.g., Http set TRANSPORT_FullTcp tells all Http objects use FullTcp agents.This configur<strong>at</strong>ion should be done before simul<strong>at</strong>ion starts, <strong>and</strong> it should not change during simul<strong>at</strong>ion, because FullTcpagents do not inter-oper<strong>at</strong>e with SimpleTcp agents.39.2.2 Managing web pagesHttp also provides OTcl interfaces to manage a set of pages. <strong>The</strong> real management of pages are h<strong>and</strong>led by class PagePool<strong>and</strong> its subclasses. Because different HTTP objects have different requirements for page management, we allow differentPagePool subclasses to be <strong>at</strong>tached to different subclasses of Http class. Meanwhile, we export a common set of PagePoolinterfaces to OTcl through Http. For example, a browser may use a PagePool only to gener<strong>at</strong>e a request stream, so its PagePoolonly needs to contain a list of URLs. But a cache may want to store page size, last modific<strong>at</strong>ion time of every page i<strong>ns</strong>tead ofa list of URLs. However, this separ<strong>at</strong>ion is not clearcut in the current implement<strong>at</strong>ion.Page URLs are represented in the form of: 〈ServerName〉:〈SequenceNumber〉 where the ServerName is the name ofOTcl object, <strong>and</strong> every page in every server should have a unique SequenceNumber. Page contents are ignored. I<strong>ns</strong>tead,every page contai<strong>ns</strong> several <strong>at</strong>tributes, which are represented in OTcl as a list of the following (〈name〉 〈value〉) pairs: “modtime〈val〉” (page modific<strong>at</strong>ion time), “size 〈val〉” (page size), <strong>and</strong> “age 〈val〉”} <strong>The</strong> ordering of these pairs is not significant.Following is a list of rel<strong>at</strong>ed OTcl methods.set-pagepool 〈pagepool〉enter-page 〈pageid〉 〈<strong>at</strong>tributes〉get-page 〈pageid〉get-modtime 〈pageid〉exist-page 〈pageid〉get-size 〈pageid〉get-cachetime 〈pageid〉set page pooladd a page with id $pageid into pool. $<strong>at</strong>tributes is the <strong>at</strong>tributes of $pageid, as describedabove.return page <strong>at</strong>tributes in the form<strong>at</strong> described above.return the last modific<strong>at</strong>ion time of the page $pageid.return 0 if $pageid doesn’t exist in this Http object, 1 otherwise.return the size of $pageid.return the time when page $pageid is entered into the cache.346


39.2.3 DebuggingHttpApp provides two debugging methods. log registers a file h<strong>and</strong>le as the trace file for all HttpApp-specific traces. Itstrace form<strong>at</strong> is described in section 39.9. evTrace logs a particular event into trace file. It conc<strong>at</strong>en<strong>at</strong>es time <strong>and</strong> the id ofthe HttpApp to the given string, <strong>and</strong> writes it out. Details can be found in <strong>ns</strong>/webcache/http.cc.39.3 Representing web pagesWe represent web pages as the abstract class Page. It is defined as follows:class Page {public:Page(int size) : size_(size) {}int size() co<strong>ns</strong>t { return size_; }int& id() { return id_; }virtual WebPageType type() co<strong>ns</strong>t = 0;protected:int size_;int id_;};It represents the basic properties of a web page: size <strong>and</strong> URL. Upon it we derive two classes of web pages: ServerPage <strong>and</strong>ClientPage. <strong>The</strong> former contai<strong>ns</strong> a list of page modific<strong>at</strong>ion times, <strong>and</strong> is supposed to by used by servers. It was originallydesigned to work with a special web server trace; currently it is not widely used in <strong>ns</strong>. <strong>The</strong> l<strong>at</strong>ter, ClientPage, is the defaultweb page for all page pools below.A ClientPage has the following major properties (we omit some variables used by web cache with invalid<strong>at</strong>ion, which has toomany details to be covered here):• HttpApp* server_ - Pointer to the original server of this page.• double age_ - Lifetime of the page.• int st<strong>at</strong>us_ - St<strong>at</strong>us of the page. Its contents are explained below.<strong>The</strong> st<strong>at</strong>us (32-bit) of a ClientPage is separ<strong>at</strong>ed into two 16-bit parts. <strong>The</strong> first part (with mask 0x00FF) is used to store pagest<strong>at</strong>us, the second part (with mask 0xFF00) is used to store expected page actio<strong>ns</strong> to be performed by cache. Available pagest<strong>at</strong>us are (again, we omit those closely rel<strong>at</strong>ed to web cache invalid<strong>at</strong>ion):HTTP_VALID_PAGEHTTP_UNCACHEABLEPage is valid.Page is uncacheable. This option can be used to simul<strong>at</strong>e CGI pages or dynamic server pages.CilentPage has the following major C++ methods:• type() - Retur<strong>ns</strong> the type of the page. Assuming pages of the same type should have identical oper<strong>at</strong>io<strong>ns</strong>, we letall ClientPage to be of type “HTML”. If l<strong>at</strong>er on other types of web pages are needed, a class may be derived fromClientPage (or Page) with the desired type.347


TclObjectPagePoolPagePool/CompM<strong>at</strong>hPagePool/M<strong>at</strong>hPagePool/ClientPagePool/ProxyTraceFigure 39.3: Class hierarchy of page pools• name(char *buf) - Print the page’s name into the given buffer. A page’s name is in the form<strong>at</strong> of: 〈ServerName〉:〈PageID〉.• split_name(co<strong>ns</strong>t char *name, PageID& id) - Split a given page name into its two components. This isa st<strong>at</strong>ic method.• mtime() - Retur<strong>ns</strong> the last modific<strong>at</strong>ion time of the page.• age() - Retur<strong>ns</strong> the lifetime of the page.39.4 Page poolsPagePool <strong>and</strong> its derived classes are used by servers to gener<strong>at</strong>e page inform<strong>at</strong>ion (name, size, modific<strong>at</strong>ion time, lifetime,etc.), by caches to describe which pages are in storage, <strong>and</strong> by clients to gener<strong>at</strong>e a request stream. Figure 39.3 provides anoverview of the class hierarchy here.Among these, class PagePool/Client is mostly used by caches to store pages <strong>and</strong> other cache-rel<strong>at</strong>ed inform<strong>at</strong>ion; other threeclasses are used by servers <strong>and</strong> clients. In the following we describe these classes one by one.39.4.1 PagePool/M<strong>at</strong>hThis is the simplest type of page pool. It has only one page, whose size can be gener<strong>at</strong>ed by a given r<strong>and</strong>om variable. Pagemodific<strong>at</strong>ion sequence <strong>and</strong> request sequence are gener<strong>at</strong>ed using two given r<strong>and</strong>om variables. It has the following OTclmethods:gen-pageidgen-sizegen-modtime 〈pageID〉 〈mt〉ranvar-age 〈rv〉ranvar-size 〈rv〉Retur<strong>ns</strong> the page ID which will be requested next. Because it has only one page, it alwaysretur<strong>ns</strong> 0.Retur<strong>ns</strong> the size of the page. It can be gener<strong>at</strong>ed by a given r<strong>and</strong>om variable.Retur<strong>ns</strong> the next modific<strong>at</strong>ion time of the page. 〈mt〉 gives the last modific<strong>at</strong>ion time. Ituses the lifetime r<strong>and</strong>om variable.Set the file lifetime r<strong>and</strong>om variable as 〈rv〉.Set the file size r<strong>and</strong>om variable to be 〈rv〉.NOTE: <strong>The</strong>re are two ways to gener<strong>at</strong>e a request sequence. With all page pools except PagePool/ProxyTrace, request sequenceis gener<strong>at</strong>ed with a r<strong>and</strong>om variable which describes the request interval, <strong>and</strong> the gen-pageid method of other page pools348


gives the page ID of the next request. PagePool/ProxyTrace loads the request stream during initializ<strong>at</strong>ion phase, so it does notneed a r<strong>and</strong>om variable for request interval; see its description below.An example of using PagePool/M<strong>at</strong>h is <strong>at</strong> Section 39.8. Th<strong>at</strong> script is also available <strong>at</strong> <strong>ns</strong>/tcl/ex/simple-webcache.tcl.39.4.2 PagePool/CompM<strong>at</strong>hIt improves over PagePool/M<strong>at</strong>h by introducing a compound page model. By a compound page we mean a page whichco<strong>ns</strong>ists of a main text page <strong>and</strong> a number of embedded objects, e.g., GIFs. We model a compound page as a main page<strong>and</strong> several component objects. <strong>The</strong> main page is always assigned with ID 0. All component pages have the same size;both the main page size <strong>and</strong> component object size is fixed, but adjustable through OTcl-bound variables main_size_ <strong>and</strong>comp_size_, respectively. <strong>The</strong> number of component objects can be set using the OTcl-bound variable num_pages_.PagePool/CompM<strong>at</strong>h has the following major OTcl methods:gen-size 〈pageID〉ranvar-main-age 〈rv〉gen-pageidgen-modtime 〈pageID〉 〈mt〉If 〈pageID〉 is 0, return main_size_, otherwise return comp_size_.Set r<strong>and</strong>om variable for main page lifetime. Another one, ranvar-obj-age, set th<strong>at</strong> forcomponent objects.Always retur<strong>ns</strong> 0, which is the main page ID.Retur<strong>ns</strong> the next modific<strong>at</strong>ion time of the given page 〈pageID〉. If the given ID is 0, it usesthe main page lifetime r<strong>and</strong>om variable; otherwise it uses the component object lifetimer<strong>and</strong>om variable.An example of using PagePool/CompM<strong>at</strong>h is available <strong>at</strong> <strong>ns</strong>/tcl/ex/simple-webcache-comp.tcl.39.4.3 PagePool/ProxyTrace<strong>The</strong> above two page pool synthesize request stream to a single web page by two r<strong>and</strong>om variables: one for request interval,another for requested page ID. Sometimes users may want more complic<strong>at</strong>ed request stream, which co<strong>ns</strong>ists of multiplepages <strong>and</strong> exhibits sp<strong>at</strong>ial locality <strong>and</strong> temporal locality. <strong>The</strong>re exists one proposal (SURGE [3]) which gener<strong>at</strong>es suchrequest streams, we choose to provide an altern<strong>at</strong>ive solution: use real web proxy cache trace (or server trace).<strong>The</strong> class PagePool/ProxyTrace uses real traces to drive simul<strong>at</strong>ion. Because there exist many web traces with differentform<strong>at</strong>s, they should be converted into a intermedi<strong>at</strong>e form<strong>at</strong> before fed into this page pool. <strong>The</strong> converter is available<strong>at</strong> http://mash.cs.berkeley.edu/dist/vint/webcache-trace-conv.tar.gz. It accepts four trace form<strong>at</strong>s: DEC proxy trace (1996),UCB Home-IP trace, NLANR proxy trace, <strong>and</strong> EPA web server trace. It converts a given trace into two files: pglog <strong>and</strong>reqlog. Each line in pglog has the following form<strong>at</strong>:[ ]Each line, except the last line, in reqlog has the following form<strong>at</strong>:[ ]<strong>The</strong> last line in reqlog records the dur<strong>at</strong>ion of the entire trace <strong>and</strong> the total number of unique URLs:i 349


PagePool/ProxyTrace takes these two file as input, <strong>and</strong> use them to drive simul<strong>at</strong>ion. Because most existing web proxy tracesdo not contain complete page modific<strong>at</strong>ion inform<strong>at</strong>ion, we choose to use a bimodal page modific<strong>at</strong>ion model [7]. We allowuser to select x% of the pages to have one r<strong>and</strong>om page modific<strong>at</strong>ion interval gener<strong>at</strong>or, <strong>and</strong> the rest of the pages to haveanother gener<strong>at</strong>or. In this way, it’s possible to let x% pages to be dynamic, i.e., modified frequently, <strong>and</strong> the rest st<strong>at</strong>ic. Hotpages are evenly distributed among all pages. For example, assume 10% pages are dynamic, then if we sort pages into a listaccording to their popularity, then pages 0, 10, 20, . . . are dynamic, rest are st<strong>at</strong>ic. Because of this selection mechanism, weonly allow bimodal r<strong>at</strong>io to change in the unit of 10%.In order to distribute requests to different requestors in the simul<strong>at</strong>or, PagePool/ProxyTrace maps the client ID in the traces torequestors in the simul<strong>at</strong>or using a modulo oper<strong>at</strong>ion.PagePool/ProxyTrace has the following major OTcl methods:get-poolsizeget-dur<strong>at</strong>ionbimodal-r<strong>at</strong>ioset-client-num 〈num〉gen-request 〈ClientID〉gen-size 〈PageID〉bimodal-r<strong>at</strong>io 〈r<strong>at</strong>io〉ranvar-dp 〈ranvar〉set-reqfile 〈file〉set-pgfile 〈file〉gen-modtime 〈PageID〉 〈LastModTime〉Retur<strong>ns</strong> the total number of pages.Retur<strong>ns</strong> the dur<strong>at</strong>ion of the trace.Retur<strong>ns</strong> the bimodal r<strong>at</strong>io.Set the number of requestors in the simul<strong>at</strong>ion.Gener<strong>at</strong>e the next request for the given requestor.Retur<strong>ns</strong> the size of the given page.Set the dynamic pages to be 〈r<strong>at</strong>io〉*10 percent. Note th<strong>at</strong> this r<strong>at</strong>io changes inunit of 10%.Set page modific<strong>at</strong>ion interval gener<strong>at</strong>or for dynamic pages. Similarly, ranvarsp〈ranvar〉 sets the gener<strong>at</strong>or for st<strong>at</strong>ic pages.Set request stream file, as discussed above.Set page inform<strong>at</strong>ion file, as discussed above.Gener<strong>at</strong>e next modific<strong>at</strong>ion time for the given page.An example of using PagePool/ProxyTrace is available <strong>at</strong> <strong>ns</strong>/tcl/ex/simple-webcache-trace.tcl.39.4.4 PagePool/Client<strong>The</strong> class PagePool/Client helps caches to keep track of pages resident in cache, <strong>and</strong> to store various cache-rel<strong>at</strong>ed inform<strong>at</strong>ionabout pages. It is mostly implemented in C++, because it is mainly used internally <strong>and</strong> little functionality is needed by users.It has the following major C++ methods:• get_page(co<strong>ns</strong>t char* name) - Retur<strong>ns</strong> a pointer to the page with the given name.• add_page(co<strong>ns</strong>t char *name, int size, double mt, double et, double age) - Add a pagewith given size, last modific<strong>at</strong>ion time (mt), cache entry time (et), <strong>and</strong> page lifetime (age).• remove_page(co<strong>ns</strong>t char* name) - Remove a page from cache.This page pool should support various cache replacement algorithms, however, it has not been implemented yet.39.4.5 PagePool/WebTraf<strong>The</strong> class PagePool/WebTraf is a st<strong>and</strong>alone Web traffic modle th<strong>at</strong> utilizes PagePool framework. However, this class hasnothing to do with the HttpApp classes. Because we are only interested in using it to study Web traffic p<strong>at</strong>tern here, <strong>and</strong> do350


not want to be bothered with the burden of tra<strong>ns</strong>mitting HTTP headers, etc. It has the following two major d<strong>at</strong>a structures.Details can be found in <strong>ns</strong>/webcache/webtraf.cc <strong>and</strong> <strong>ns</strong>/webcache/webtraf.h, the architecture WebTraf model is also looselydescribed in [10], Section 2.4, paragraph 3-4 <strong>and</strong> the appendix A.1.• WebTrafSession - a class th<strong>at</strong> models Web user session. It is defined as follows:class WebTrafSession : public TimerH<strong>and</strong>ler {public:WebTrafSession(WebTrafPool *mgr, Node *src, int np, int id) : rvInterPage_(NULL),rvPageSize_(NULL), rvInterObj_(NULL), rvObjSize_(NULL), mgr_(mgr), src_(src),nPage_(np), curPage_(0), donePage_(0), id_(id), interPageOption_(1) {}virtual ~WebTrafSession();// Queried by individual pages/objectsinline R<strong>and</strong>omVariable*& interPage() { return rvInterPage_; }inline R<strong>and</strong>omVariable*& pageSize() { return rvPageSize_; }inline R<strong>and</strong>omVariable*& interObj() { return rvInterObj_; }inline R<strong>and</strong>omVariable*& objSize() { return rvObjSize_; }void donePage(void* ClntD<strong>at</strong>a); // all the pages within this// session have been sentvoid launchReq(void* ClntD<strong>at</strong>a, int obj, int size);inline int id() co<strong>ns</strong>t { return id_; }inline WebTrafPool* mgr() { return mgr_; }priv<strong>at</strong>e:virtual void expire(Event *e = 0); // Lanuch request for a pagevirtual void h<strong>and</strong>le(Event *e); // schedule the timer for next page}R<strong>and</strong>omVariable *rvInterPage_, *rvPageSize_, *rvInterObj_, *rvObjSize_;WebTrafPool* mgr_;Node* src_; // One Web client (source of request) per sessionnt nPage_; // number of pages per sessionint curPage_; // number of pages th<strong>at</strong> have been sentint id_; // page IDint interPageOption_;• WebPage - a class th<strong>at</strong> models Web Page. It is defined as follows:class WebPage : public TimerH<strong>and</strong>ler {public:WebPage(int id, WebTrafSession* sess, int nObj, Node* dst) :id_(id), sess_(sess), nObj_(nObj), curObj_(0),doneObj_(0), dst_(dst) {}virtual ~WebPage() {}inline void start() { // Call expire() <strong>and</strong> schedule the next one if neededvoid doneObject() { // All the objects within this page have been sentinline int id() co<strong>ns</strong>t { return id_; }Node* dst() { return dst_; }inline int curObj() co<strong>ns</strong>t { return curObj_; }inline int doneObj() co<strong>ns</strong>t { return doneObj_; }priv<strong>at</strong>e:virtual void expire(Event* = 0) { // Launch request for an objectvirtual void h<strong>and</strong>le(Event *e) { // schedule the timer for the next object351


}int id_; // object IDWebTrafSession* sess_; // the session th<strong>at</strong> requested this pageint nObj_; // number of object in this pageint curObj_ ; // number of object th<strong>at</strong> have been sentNode* dst_; // server th<strong>at</strong> this page has been requested fromFollowing is a list of rel<strong>at</strong>ed OTcl methods to the WebTraf class.set-num-session 〈number-of-session〉set-num-server 〈number-of-server〉set-num-client 〈number-of-client〉set-interPageOption 〈option〉doneObj 〈webpage〉set-server 〈id〉 〈node〉set-client 〈id〉 〈node〉recycle 〈tcp〉 〈sink〉cre<strong>at</strong>e-session 〈session-index〉 〈pages-per-sess〉〈launch-time〉 〈inter-page-rv〉 〈page-size-rv〉〈inter-obj-rv〉 〈obj-size-rv〉set the total number of sessio<strong>ns</strong> in the WebTraf pool.set the total number of servers.set the total number clients.<strong>The</strong>re are two ways to interpret inter-page time: One is the time betweenthe start of two co<strong>ns</strong>ecutive page downloads by the same user,<strong>and</strong> the other is the time between the end of previous page download<strong>and</strong> the start of the following page by the same user. $option can beset to either 0 or 1 (default is 1). When $option is set to 1, the secondinterpret<strong>at</strong>ion is used for "inter-page" time. <strong>The</strong> first interpr<strong>at</strong><strong>at</strong>ion isadopted when $option is set to 0. Note the resulted traffic volume usingthe first interpret<strong>at</strong>ion is much higher than the second interpret<strong>at</strong>ion.all the objects in $webpage have been sent.set $node as server $id.set $node as client $id.Recycle a TCP source/sink pair.Cre<strong>at</strong>e a Web session. $session-index is the sesson index. $pages-persessis the total number of pages per session. $launch-time is sessio<strong>ns</strong>tarting time. $inter-page-rv is the r<strong>and</strong>om variable th<strong>at</strong> gener<strong>at</strong>es pageinter-arrival time. $page-size-rv is the r<strong>and</strong>om variable th<strong>at</strong> gener<strong>at</strong>esnumber of objects per page. $inter-obj-rv is the r<strong>and</strong>om variable th<strong>at</strong>gener<strong>at</strong>es object inter-arrival time. $obj-size-rv is the r<strong>and</strong>om variableth<strong>at</strong> gener<strong>at</strong>es object size.<strong>The</strong> example script is available <strong>at</strong> <strong>ns</strong>/tcl/ex/web-traffic.tcl (also see <strong>ns</strong>/tcl/ex/large-scale-web-traffic.tcl for use of a large-scaleweb traffic simul<strong>at</strong>ion)39.5 Web clientClass Http/Client models behavior of a simple web browser. It gener<strong>at</strong>es a sequence of page requests, where request interval<strong>and</strong> page IDs are r<strong>and</strong>omized. It’s a pure OTcl class inherited from Http. Next we’ll walk through its functionalities <strong>and</strong>usage.Cre<strong>at</strong>ing a client First of all, we cre<strong>at</strong>e a client <strong>and</strong> connect it to a cache <strong>and</strong> a web server. Currently a client is onlyallowed to connect to a single cache, but it’s allowed to connect to multiple servers. Note th<strong>at</strong> this has to be called AFTERthe simul<strong>at</strong>ion starts (i.e., after $<strong>ns</strong> run is called). This remai<strong>ns</strong> true for all of the following methods <strong>and</strong> code examples ofHttp <strong>and</strong> its derived classes, unless explicitly said.352


# Assuming $server is a configured Http/Server.set client [new Http/Client $<strong>ns</strong> $node]$client connect $server;# client resides on this node;# connecting client to serverConfiguring request gener<strong>at</strong>ion For every request, Http/Client uses PagePool to gener<strong>at</strong>e a r<strong>and</strong>om page ID, <strong>and</strong> use ar<strong>and</strong>om variable to gener<strong>at</strong>e intervals between two co<strong>ns</strong>ecutive requests: 2$client set-page-gener<strong>at</strong>or $pgp$client set-interval-gener<strong>at</strong>or $ranvar;# <strong>at</strong>tach a configured PagePool;# <strong>at</strong>tach a r<strong>and</strong>om variableHere we assume th<strong>at</strong> PagePools of Http/Client share the same set of pages as PagePools of the server. Usually we simplifyour simul<strong>at</strong>ion by letting all clients <strong>and</strong> servers share the same PagePool, i.e., they have the same set of pages. When there aremultiple servers, or servers’ PagePools are separ<strong>at</strong>ed from those of clients’, care must be taken to make sure th<strong>at</strong> every clientsees the same set of pages as the servers to which they are <strong>at</strong>tached.StartingAfter the above setup, starting requests is very simple:$client start-session $cache $server;# assuming $cache is a configured Http/CacheOTcl interfaces Following is a list of its OTcl methods (in addition to those inherited from Http). This is not a completelist. More details can be found in <strong>ns</strong>/tcl/webcache/http-agent.tcl.send-request 〈server〉 〈type〉 〈pageid〉 〈args〉start-session 〈cache〉 〈server〉start 〈cache〉 〈server〉set-page-gener<strong>at</strong>or 〈pagepool〉set-interval-gener<strong>at</strong>or 〈ranvar〉send a request of page $pageid <strong>and</strong> type $type to $server. <strong>The</strong> only requesttype allowed for a client is GET. $args has a form<strong>at</strong> identical to th<strong>at</strong> of$<strong>at</strong>tributes described in Http::enter-page.start sending requests of a r<strong>and</strong>om page to $server via $cache.before sending requests, popul<strong>at</strong>e $cache with all pages in the client’s Page-Pool. This method is useful when assuming infinite-sized caches <strong>and</strong> wewant to observe behaviors of cache co<strong>ns</strong>istency algorithms in steady st<strong>at</strong>e.<strong>at</strong>tach a PagePool to gener<strong>at</strong>e r<strong>and</strong>om page IDs.<strong>at</strong>tach a r<strong>and</strong>om variable to gener<strong>at</strong>e r<strong>and</strong>om request intervals.39.6 Web serverClass Http/Server models behavior of a HTTP server. Its configur<strong>at</strong>ion is very simple. All th<strong>at</strong> a user needs to do is to cre<strong>at</strong>ea server, <strong>at</strong>tach a PagePool <strong>and</strong> wait:set server [new Http/Server $<strong>ns</strong> $node]$server set-page-gener<strong>at</strong>or $pgp;# <strong>at</strong>tach $server to $node;# <strong>at</strong>tach a page pool2 Some PagePool, e.g., PagePool/M<strong>at</strong>h, has only one page <strong>and</strong> therefore it always retur<strong>ns</strong> the same page. Some other PagePool, e.g. PagePool/Trace, hasmultiple pages <strong>and</strong> needs a r<strong>and</strong>om variable to pick out a r<strong>and</strong>om page.353


An Http/Server object waits for incoming requests after simul<strong>at</strong>ion starts. Usually clients <strong>and</strong> caches initi<strong>at</strong>es connection toan Http/Server. But it still has its own connect method, which allows an Http/Server object to actively connect to a certaincache (or client). Sometimes this is useful, as explained in Test/TLC1::set-groups{} in <strong>ns</strong>/tcl/test/test-suite-webcache.tcl.An Http/Server object accepts two types of requests: GET <strong>and</strong> IMS. GET request models normal client requests. For everyGET request, it retur<strong>ns</strong> the <strong>at</strong>tributes of the requested page. IMS request models If-Modified-Since used by TTL algorithmsfor cache co<strong>ns</strong>istency. For every IMS (If-Modified-Since) request, it compares the page modific<strong>at</strong>ion time given in the request<strong>and</strong> th<strong>at</strong> of the page in its PagePool. If the time indic<strong>at</strong>ed in the request is older, it sends back a respo<strong>ns</strong>e with very small size,otherwise it retur<strong>ns</strong> all of the page <strong>at</strong>tributes with respo<strong>ns</strong>e size equal the real page size.39.7 Web cacheCurrently 6 types of web caches are implemented, including the base class Http/Cache. Its five derived subclasses implement5 types of cache co<strong>ns</strong>istency algorithms: Plain old TTL, adaptive TTL, Omniscient TTL, Hierarchical multicast invalid<strong>at</strong>ion,<strong>and</strong> hierarchical multicast invalid<strong>at</strong>ion plus direct request.In the following we’ll only describe the base class Http/Cache, because all the subclasses involves discussion of cache co<strong>ns</strong>istencyalgorithms <strong>and</strong> it does not seem to be appropri<strong>at</strong>e here.39.7.1 Http/CacheClass Http/Cache models behavior of a simple HTTP cache with infinite size. It doesn’t contain removal algorithm, norco<strong>ns</strong>istency algorithm. It is not intended to be used by itself. R<strong>at</strong>her, it is meant to be a base class for experimenting withvarious cache co<strong>ns</strong>istency algorithms <strong>and</strong> other cache algorithms.Cre<strong>at</strong>ion <strong>and</strong> startup Cre<strong>at</strong>ing an Http/Cache requires the same set of parameters as Http/Client <strong>and</strong> Http/Server. Aftercre<strong>at</strong>ion, a cache needs to connect to a certain server. Note th<strong>at</strong> this cre<strong>at</strong>ion can also be done dynamically, when a requestcomes in <strong>and</strong> the cache finds th<strong>at</strong> it’s not connected to the server. However, we do not model this behavior in current code.Following code is an example:set cache [new HttpCache $<strong>ns</strong> $node]$cache connect $server;# <strong>at</strong>tach cache to $node;# connect to $serverLike Http/Server, an Http/Cache object waits for requests (<strong>and</strong> packets from server) after it’s initialized as above. Whenhierarchical caching is used, the following can be used to cre<strong>at</strong>e the hierarchy:$cache set-parent $parent;# set parent cacheCurrently all TTL <strong>and</strong> multicast invalid<strong>at</strong>ion caches support hierarchical caching. However, only the two multicast invalid<strong>at</strong>ioncaches allows multiple cache hierarchies to inter-oper<strong>at</strong>e.OTcl methods Although Http/Cache is a SplitObject, all of its methods are in OTcl. Most of them are used to process anincoming request. <strong>The</strong>ir rel<strong>at</strong>io<strong>ns</strong> can be illustr<strong>at</strong>ed with the flowchart below, followed by explain<strong>at</strong>io<strong>ns</strong>:354


cache-hit()is-co<strong>ns</strong>istent()Ysend cached pageignore the requestget-request()Nrefetch-pending()cache-miss()send-request()refetch()Figure 39.4: H<strong>and</strong>ling of incoming request in Http/Cacheget-request 〈client〉 〈type〉 〈pageid〉cache-miss 〈client〉 〈type〉 〈pageid〉cache-hit 〈client〉 〈type〉 〈pageid〉is-co<strong>ns</strong>istent 〈client〉 〈type〉 〈pageid〉refetch 〈client〉 〈type〉 〈pageid〉<strong>The</strong> entry point of processing any request. It checks if the requested page $pageidexists in the cache’s page pool, then call either cache-hit or cache-miss.This cache doesn’t have the page. Send a request to server (or parent cache) torefetch the page if it hasn’t already done so. Register $client in a list so th<strong>at</strong> whenthe cache gets the page, it’ll forward the page to all clients who have requested thepage.Checks the valid<strong>at</strong>ity of the cached page. If it’s valid, send $client the cached page,otherwise refetch the page.Retur<strong>ns</strong> 1 if $pageid is valid. This is intended to be overridden by subclasses.Refetch an invalid page from server. This is intended to be overridden by subclasses.39.8 Putting together: a simple exampleWe have seen all the pieces, now we present a script which provides a complete view of all pieces together. First, we buildtopology <strong>and</strong> other usual initializ<strong>at</strong>io<strong>ns</strong>:set <strong>ns</strong> [new Simul<strong>at</strong>or]# Cre<strong>at</strong>e topology/routingset node(c) [$<strong>ns</strong> node]set node(e) [$<strong>ns</strong> node]set node(s) [$<strong>ns</strong> node]$<strong>ns</strong> duplex-link $node(s) $node(e) 1.5Mb 50ms DropTail$<strong>ns</strong> duplex-link $node(e) $node(c) 10Mb 2ms DropTail$<strong>ns</strong> rtproto SessionNext we cre<strong>at</strong>e the Http objects:# HTTP logsset log [open "http.log" w]# Cre<strong>at</strong>e page pool as a central page gener<strong>at</strong>or. Use PagePool/M<strong>at</strong>hset pgp [new PagePool/M<strong>at</strong>h]set tmp [new R<strong>and</strong>omVariable/Co<strong>ns</strong>tant];## Page size gener<strong>at</strong>or$tmp set val_ 1024;## average page size$pgp ranvar-size $tmp355


set tmp [new R<strong>and</strong>omVariable/Exponential]$tmp set avg_ 5$pgp ranvar-age $tmp;## Page age gener<strong>at</strong>or;## average page age;## Cre<strong>at</strong>e a server <strong>and</strong> link it to the cen-;## Cre<strong>at</strong>e a cache;## Cre<strong>at</strong>e a client;## Poisson process as request sequence;## average request interval;## simul<strong>at</strong>ion start time;## simul<strong>at</strong>ion end timeset server [new Http/Server $<strong>ns</strong> $node(s)]tral page pool$server set-page-gener<strong>at</strong>or $pgp$server log $logset cache [new Http/Cache $<strong>ns</strong> $node(e)]$cache log $logset client [new Http/Client $<strong>ns</strong> $node(c)]set tmp [new R<strong>and</strong>omVariable/Exponential]$tmp set avg_ 5$client set-interval-gener<strong>at</strong>or $tmp$client set-page-gener<strong>at</strong>or $pgp$client log $logset startTime 1set finishTime 50$<strong>ns</strong> <strong>at</strong> $startTime "start-connection"$<strong>ns</strong> <strong>at</strong> $finishTime "finish"<strong>The</strong>n we define a procedure which will be called after simul<strong>at</strong>ion starts. <strong>The</strong> procedure will setup connectio<strong>ns</strong> among all Httpobjects.proc start-connection {} {global <strong>ns</strong> server cache client$client connect $cache$cache connect $server$client start-session $cache $server}At the end, the usual closing:proc finish {} {global <strong>ns</strong> log$<strong>ns</strong> flush-traceflush $logclose $logexit 0}$<strong>ns</strong> runThis script is also available <strong>at</strong> <strong>ns</strong>/tcl/ex/simple-webcache.tcl. Examining its output http.log, one will find th<strong>at</strong> the resultof the abse<strong>ns</strong>e cache co<strong>ns</strong>istency algorithm results in a lot of stale hits. This can be easily remedied by replacing “newHttp/Cache” line with: set cache [new Http/Cache/TTL $<strong>ns</strong> $node(e)]. For more complic<strong>at</strong>ed cache co<strong>ns</strong>istencyalgorithm examples, see <strong>ns</strong>/tcl/test/test-suite-webcache.tcl.356


39.9 Http trace form<strong>at</strong><strong>The</strong> trace file of Http agents are co<strong>ns</strong>tructed in a similar way as the SRM trace files. It co<strong>ns</strong>ists of multiple entries, each ofwhich occupies one line. <strong>The</strong> form<strong>at</strong> of each entry is:Time ObjectID Object Values<strong>The</strong>re are three types of objects: client (C), cache (E) <strong>and</strong> server (S). Following is a complete enumer<strong>at</strong>ion of all possibleevents <strong>and</strong> value types associ<strong>at</strong>ed with these three types of objects.Object Type Event Type ValuesE HIT 〈Prefix〉E MISS 〈Prefix〉 z 〈RequestSize〉E IMS 〈Prefix〉 z 〈Size〉 t 〈CacheEntryTime〉E REF p 〈PageID〉 s 〈ServerID〉 z 〈Size〉E UPD p 〈PageID〉 m 〈LastModifiedTime〉 z 〈PageSize〉s 〈ServerID〉E GUPD z 〈PageSize〉E SINV p 〈PageID〉 m 〈LastModTime〉 z 〈PageSize〉E GINV p 〈PageID〉 m 〈LastModTime〉E SPF p 〈PageID〉 c 〈DestCache〉E RPF p 〈PageID〉 c 〈SrcCache〉E ENT p 〈PageID〉 m 〈LastModifiedTime〉 z 〈PageSize〉s 〈ServerID〉C GET p 〈PageID〉 s 〈PageServerID〉 z 〈RequestSize〉C STA p 〈PageID〉 s 〈OrigServerID〉 l 〈StaleTime〉C RCV p 〈PageID〉 s 〈PageServerID〉 l 〈Respo<strong>ns</strong>eTime〉 z 〈PageSize〉S INV p 〈PageID〉 m 〈LastModifiedTime〉 z 〈Size〉S UPD p 〈PageID〉 m 〈LastModifiedTime〉 z 〈Size〉S SND p 〈PageID〉 m 〈LastModifiedTime〉 z 〈PageSize〉t 〈Requesttype〉S MOD p 〈PageID〉 n 〈NextModifyTime〉〈Prefix〉 is the inform<strong>at</strong>ion common to all trace entries. It includes:p 〈PageID〉 c 〈RequestClientID〉 s 〈PageServerID〉Short Explain<strong>at</strong>ion of event oper<strong>at</strong>io<strong>ns</strong>:357


Object Type Event Type Explain<strong>at</strong>ionE HIT Cache hit. PageSererID is the id of the “owner” of the page.E MISS Cache miss. In this case the cache will send a request to the server to fetch the page.E IMS If-Modified-Since. Used by TTL procotols to valid<strong>at</strong>e an expired page.E REF Page refetch. Used by invalid<strong>at</strong>ion protocols to refetch an invalid<strong>at</strong>ed page.E UPD Page upd<strong>at</strong>e. Used by invalid<strong>at</strong>ion protocols to “push” upd<strong>at</strong>esfrom parent cache to children caches.E SINV Send invalid<strong>at</strong>ion.E GINV Get invalid<strong>at</strong>ion.E SPF Send a pro formaE RPF Receive a pro formaE ENT Enter a page into local page cache.C GET Client sends a request for a page.C STA Client gets a stale hit. OrigModTime is the modific<strong>at</strong>ion timein the web server, CurrModTime is the local page’s modific<strong>at</strong>ion time.C RCV Client receives a page.S SND Server send a respo<strong>ns</strong>e.S UPD Server pushes a page upd<strong>at</strong>e to its “primary cache”. Used by invalid<strong>at</strong>ion protocol only.S INV Server sends an invalid<strong>at</strong>ion message. Used by invalid<strong>at</strong>ion protocol only.S MOD Server modified a page. <strong>The</strong> page will be modified next <strong>at</strong> 〈NextModifyTime〉.39.10 Comm<strong>and</strong>s <strong>at</strong> a glanceFollowing are the web cache rel<strong>at</strong>ed comm<strong>and</strong>s:set server [new Http/Server ]This cre<strong>at</strong>es an i<strong>ns</strong>tance of an Http server <strong>at</strong> the specified . An i<strong>ns</strong>tance of the simul<strong>at</strong>or needs to be passedas an argument.set client [new Http/Client ]This cre<strong>at</strong>es an i<strong>ns</strong>tance of a Http client <strong>at</strong> the given .set cache [new Http/Cache This comm<strong>and</strong> cre<strong>at</strong>es a cache.set pgp [new PagePool/]This cre<strong>at</strong>es a pagepool of the type specified. <strong>The</strong> different types of pagepool currently implemented are:PagePool/M<strong>at</strong>h, PagePool/CompM<strong>at</strong>h, PagePool/ProxyTrace <strong>and</strong> PagePool/Client. See section 39.4 for details on Otclinterface for each type of Pagepool.$server set-page-gener<strong>at</strong>or $server log <strong>The</strong> above comm<strong>and</strong>s co<strong>ns</strong>ist of server configur<strong>at</strong>ion. First the server is <strong>at</strong>tached to a central page pool . Next it is<strong>at</strong>tached to a log file.client set-page-gener<strong>at</strong>or $client set-interval-gener<strong>at</strong>or 358


$client log <strong>The</strong>se co<strong>ns</strong>ist configur<strong>at</strong>ion of the Http client. It is <strong>at</strong>tached to a central page pool . Next a r<strong>and</strong>om variable is <strong>at</strong>tached to the client th<strong>at</strong> is used by it (client) to gener<strong>at</strong>e intervals between two co<strong>ns</strong>ecutive requests. Lastly the client is<strong>at</strong>tached to a log file for logging its events.$cache log This is part of cache configur<strong>at</strong>ion th<strong>at</strong> allows the cache to log its events in a log-file.$client connect $cache connect Once the client, cache, <strong>and</strong> server are configured, they need to be connected as shown in above comm<strong>and</strong>s.$client start-session This starts sending request for a r<strong>and</strong>om page from the client to the via .359


Chapter 40Worm ModelIn this chapter, we describe a scalable worm propag<strong>at</strong>ion model in <strong>ns</strong>, namely the detailed-network <strong>and</strong> abstract-network (DN-AN) model. It combines packet-level simul<strong>at</strong>io<strong>ns</strong> with analytic worm spreading model. As shown in Figure 40.1, we modelthe Internet with two parts: detailed, <strong>and</strong> abstract part. A detailed-network could be an enterprise-network or the networkrun by an ISP. It simul<strong>at</strong>es network connectivity <strong>and</strong> packet tra<strong>ns</strong>mission. Users can evalu<strong>at</strong>e worm detection algorithms inthe detailed network. On the other h<strong>and</strong>, we abstract the rest of the Internet with a m<strong>at</strong>hem<strong>at</strong>ical model, namely susceptibleinfectious-removal(SIR) model (refer to [13] for detailed descriptio<strong>ns</strong>). Compared to the detailed network, we only trackseveral st<strong>at</strong>e variables in the abstract world, such as the number of infected hosts. <strong>The</strong> interaction between DN <strong>and</strong> AN isthrough actual packet tra<strong>ns</strong>missio<strong>ns</strong>, th<strong>at</strong> is, the probing traffic gener<strong>at</strong>ed by compromised hosts in both parts.For detailed description on DN-AN model, please refer to our draft paper. We implement the worm propag<strong>at</strong>ion model asapplic<strong>at</strong>io<strong>ns</strong>. <strong>The</strong> source code can be found <strong>at</strong> ~<strong>ns</strong>//apps/worm.{cc,h}. <strong>The</strong>re is also a sample script to illustr<strong>at</strong>e the DN-ANmodel under ~<strong>ns</strong>//tcl/ex/worm.tcl.40.1 OverviewWe implement the worm propag<strong>at</strong>ion model with three classes: class WormApp, DnhWormApp, <strong>and</strong> AnWormApp.class WormAppnd class DnhWormAppre used in the detailed network, representing invulnerable <strong>and</strong> vulnerable hostsrespectively. class AnWormApps the abstract network. Currently, our model only supports UDP-based worms.An vulnerable host is compromised upon receiving a probing packet. <strong>The</strong>n, it chooses a target host (r<strong>and</strong>omly or with certainpreference to local neighbors) to scan. Probing packets have no effect on invulnerable hosts. When the abstract networkreceives probing packets, it upd<strong>at</strong>es its current st<strong>at</strong>es.probingtrafficthe restunprotectedInternetthe protected networkFigure 40.1: <strong>The</strong> DN-AN model.360


40.2 Configur<strong>at</strong>ionTo set up simul<strong>at</strong>ion scenario, we first build the detailed network. We also need to cre<strong>at</strong>e one extra node to represent theabstract network, <strong>and</strong> connect it to the detailed network.For nodes in the detailed network, we first <strong>at</strong>tach a MessagePassing agent to each node:set a [new Agent/MessagePassing]$n <strong>at</strong>tach $a $probing_portIf the node represents a vulnerable host, we use class DnhWormAppset w [new Applic<strong>at</strong>ion/Worm/Dnh]$w <strong>at</strong>tach-agent $aOtherwise, we configure the node as invulnerable:set w [new Applic<strong>at</strong>ion/Worm]$w <strong>at</strong>tach-agent $aWe configure the abstract network as:set a [new Agent/MessagePassing]$na <strong>at</strong>tach $a $probing_portset w [new Applic<strong>at</strong>ion/Worm/An]$w <strong>at</strong>tach-agent $aIn order for the abstract network to receive probing packets gener<strong>at</strong>ed by nodes within the detailed networks, we need to usemanual routing. <strong>The</strong>re are some extra configur<strong>at</strong>ion for the abstract-network node:set p [$na set dmux_]$p defaulttarget $a[$na entry] defaulttarget $p40.3 Comm<strong>and</strong>s <strong>at</strong> a glanceSome common parameters can be configured through TCL script:ScanR<strong>at</strong>e # the r<strong>at</strong>e th<strong>at</strong> a compromised host sends probing packetsScanPort # the vulnerable service port numberScanPacketSize # the size of worm probing packetsBy default, compromised hosts scan the Internet r<strong>and</strong>omly. We can also simul<strong>at</strong>e local-scanning worm by setting the localscanningprobability:361


$w local-p 0.5Following are some comm<strong>and</strong>s to configure parameters for the abstract network:$w beta 0.1 # infection parameter$w gamma 0 # removal parameter$w addr-range 2000 200000 # the address space of the abstract network$w dn-range 0 1999 # the address space of the detailed network$w v_percent 0.01 # the percentage of vulnerable hosts in the abstract network362


Chapter 41PackMime-HTTP: Web Traffic Gener<strong>at</strong>ion<strong>The</strong> PackMime Internet traffic model was developed by researchers in the Internet Traffic Research group <strong>at</strong> Bell <strong>Lab</strong>s, basedon recent Internet traffic traces. PackMime includes a model of HTTP traffic, called PackMime-HTTP. <strong>The</strong> traffic inte<strong>ns</strong>itygener<strong>at</strong>ed by PackMime-HTTP is controlled by the r<strong>at</strong>e parameter, which is the average number of new HTTP connectio<strong>ns</strong>started each second. <strong>The</strong> PackMime-HTTP implement<strong>at</strong>ion in <strong>ns</strong>-2, developed <strong>at</strong> UNC-Chapel Hill, is capable of gener<strong>at</strong>ingHTTP/1.0 <strong>and</strong> HTTP/1.1 (persistent, non-pipelined) connectio<strong>ns</strong>.<strong>The</strong> goal of PackMime-HTTP is not to simul<strong>at</strong>e the interaction between a single web client <strong>and</strong> web server, but to simul<strong>at</strong>ethe TCP-level traffic gener<strong>at</strong>ed on a link shared by many web clients <strong>and</strong> servers.A typical PackMime-HTTP i<strong>ns</strong>tance co<strong>ns</strong>ists of two <strong>ns</strong> nodes: a server node <strong>and</strong> a client node. It is important to note th<strong>at</strong>these nodes do not correspond to a single web server or web client. A single PackMime-HTTP client node gener<strong>at</strong>es HTTPconnectio<strong>ns</strong> coming from a “cloud” of web clients. Likewise, a single PackMime-HTTP server node accepts <strong>and</strong> serves HTTPconnectio<strong>ns</strong> destined for a “cloud” of web servers. A single web client is represented by a single PackMime-HTTP clientapplic<strong>at</strong>ion, <strong>and</strong> a single web server is represented by a single PackMime-HTTP server applic<strong>at</strong>ion. <strong>The</strong>re are many clientapplic<strong>at</strong>io<strong>ns</strong> assigned to a single client <strong>ns</strong> node, <strong>and</strong> many server applic<strong>at</strong>io<strong>ns</strong> assigned to a single server <strong>ns</strong> node.In order to simul<strong>at</strong>e different RTTs, bottleneck links, <strong>and</strong>/or loss r<strong>at</strong>es for each connection, PackMime-HTTP is often usedin conjunction with DelayBox (see Chapter 22). DelayBox is a module developed <strong>at</strong> UNC-Chapel Hill for delaying <strong>and</strong>/ordropping packets in a flow according to a given distribution. See Section 41.3 for more inform<strong>at</strong>ion on using PackMime-HTTP<strong>and</strong> DelayBox together.<strong>The</strong> PackMime HTTP traffic model is described in detail in the following paper: J. Cao, W.S. Clevel<strong>and</strong>, Y. Gao, K. Jeffay,F.D. Smith, <strong>and</strong> M.C. Weigle , “Stochastic Models for Gener<strong>at</strong>ing Synthetic HTTP Source Traffic”, Proceedings of IEEEINFOCOM, Hong Kong, March 2004.41.1 Implement<strong>at</strong>ion DetailsPackMimeHTTP is an <strong>ns</strong> object th<strong>at</strong> drives the gener<strong>at</strong>ion of HTTP traffic. Each PackMimeHTTP object controls the oper<strong>at</strong>ionof two types of Applic<strong>at</strong>io<strong>ns</strong>, a PackMimeHTTP server Applic<strong>at</strong>ion <strong>and</strong> a PackMimeHTTP client Applic<strong>at</strong>ion. Each ofthese Applic<strong>at</strong>io<strong>ns</strong> is connected to a TCP Agent (Full-TCP). Note: PackMime-HTTP only supports Full-TCP agents.Each web server or web client cloud is represented by a single <strong>ns</strong> node th<strong>at</strong> can produce <strong>and</strong> co<strong>ns</strong>ume multiple HTTPconnectio<strong>ns</strong> <strong>at</strong> a time (Figure 41.1). For each HTTP connection, PackMimeHTTP cre<strong>at</strong>es (or alloc<strong>at</strong>es from the inactivepool, as described below) server <strong>and</strong> client Applic<strong>at</strong>io<strong>ns</strong> <strong>and</strong> their associ<strong>at</strong>ed TCP Agents. After setting up <strong>and</strong> starting each363


(<strong>ns</strong>node) clientcloudPackM ime(<strong>ns</strong>node) servercloud<strong>and</strong>AgentsFigure 41.1: PackMimeHTTP Architecture. Each PackMimeHTTP object controls a server <strong>and</strong> a client cloud. Each cloudcan represent multiple client or server Applic<strong>at</strong>io<strong>ns</strong>. Each Applic<strong>at</strong>ion represents either a single web server or a single webclient.serverApplic<strong>at</strong>io<strong>ns</strong><strong>and</strong>Agents clientApplic<strong>at</strong>io<strong>ns</strong>connection, PackMimeHTTP sets a timer to expire when the next new connection should begin. <strong>The</strong> time between newconnectio<strong>ns</strong> is governed by the connection r<strong>at</strong>e parameter supplied by the user. New connectio<strong>ns</strong> are started according to theconnection arrival times without regard to the completion of previous requests, but a new request between the same client <strong>and</strong>server pair (as with HTTP 1.1) begi<strong>ns</strong> only after the previous request-respo<strong>ns</strong>e pair has been completed.PackMimeHTTP h<strong>and</strong>les the re-use of Applic<strong>at</strong>io<strong>ns</strong> <strong>and</strong> Agents th<strong>at</strong> have completed their d<strong>at</strong>a tra<strong>ns</strong>fer. <strong>The</strong>re are 5 pools usedto maintain Applic<strong>at</strong>io<strong>ns</strong> <strong>and</strong> Agents – one pool for inactive TCP Agents <strong>and</strong> one pool each for active <strong>and</strong> inactive client <strong>and</strong>server Applic<strong>at</strong>io<strong>ns</strong>. <strong>The</strong> pools for active Applic<strong>at</strong>io<strong>ns</strong> e<strong>ns</strong>ure th<strong>at</strong> all active Applic<strong>at</strong>io<strong>ns</strong> are destroyed when the simul<strong>at</strong>ionis finished. Active TCP Agents do not need to be placed in a pool because each active Applic<strong>at</strong>ion contai<strong>ns</strong> a pointer to itsassoci<strong>at</strong>ed TCP Agent. New objects are only cre<strong>at</strong>ed when there are no Agents or Applic<strong>at</strong>io<strong>ns</strong> available in the inactive pools.41.1.1 PackMimeHTTP Client Applic<strong>at</strong>ionEach PackMimeHTTP client controls the HTTP request sizes th<strong>at</strong> are tra<strong>ns</strong>ferred. Each PackMimeHTTP client takes thefollowing steps:• if the connection is persistent <strong>and</strong> co<strong>ns</strong>ists of more than one request, then the client samples all request sizes, respo<strong>ns</strong>esizes, <strong>and</strong> inter-request times for the connection• if the connection only co<strong>ns</strong>ists of one request, then the client samples the request size <strong>and</strong> the respo<strong>ns</strong>e size• send the first HTTP request to the server• listen for the HTTP respo<strong>ns</strong>e• when the entire HTTP respo<strong>ns</strong>e has been received, the client sets a timer to expire when the next request should bemade, if applicable• when the timer expires, the next HTTP request is sent, <strong>and</strong> the above process is repe<strong>at</strong>ed until all requests have beencompleted364


41.1.2 PackMimeHTTP Server Applic<strong>at</strong>ionEach web server controls the respo<strong>ns</strong>e sizes th<strong>at</strong> are tra<strong>ns</strong>ferred. <strong>The</strong> server is started by when a new TCP connection isstarted. Each PackMimeHTTP client takes the following steps:• listen for an HTTP request from the associ<strong>at</strong>ed client• when the entire request arrives, the server samples the server delay time from the server delay distribution• set a timer to expire when the server delay has passed• when the timer expires, the server sends respo<strong>ns</strong>e (the size of which was sampled by the client <strong>and</strong> passed to the server)• this process is repe<strong>at</strong>ed until the requests are exhausted – the server is told how many requests will be sent in theconnection• send a FIN to close the connection41.2 PackMimeHTTP R<strong>and</strong>om VariablesThis implement<strong>at</strong>ion of PackMimeHTTP provides several <strong>ns</strong> R<strong>and</strong>omVariable objects for specifying distributio<strong>ns</strong> of Pack-MimeHTTP connection variables. <strong>The</strong> implement<strong>at</strong>io<strong>ns</strong> were taken from source code provided by Bell <strong>Lab</strong>s <strong>and</strong> modified tofit into the <strong>ns</strong> R<strong>and</strong>omVariable framework. This allows PackMimeHTTP connection variables to be specified by any type of<strong>ns</strong> R<strong>and</strong>omVariable, which now include PackMimeHTTP-specific r<strong>and</strong>om variables. If no R<strong>and</strong>omVariables are specified inthe TCL script, PackMimeHTTP will set these autom<strong>at</strong>ically.<strong>The</strong> PackMimeHTTP-specific r<strong>and</strong>om variable syntax for TCL scripts is as follows:• $<strong>ns</strong> [new R<strong>and</strong>omVariable/PackMimeHTTPFlowArrive ], where r<strong>at</strong>e is the specified Pack-MimeHTTP connection r<strong>at</strong>e (number of new connectio<strong>ns</strong> per second)• $<strong>ns</strong> [new R<strong>and</strong>omVariable/PackMimeHTTPReqSize ], where r<strong>at</strong>e is the specified PackMime-HTTP connection r<strong>at</strong>e• $<strong>ns</strong> [new R<strong>and</strong>omVariable/PackMimeHTTPRspSize ], where r<strong>at</strong>e is the specified PackMime-HTTP connection r<strong>at</strong>e• $<strong>ns</strong> [new R<strong>and</strong>omVariable/PackMimeHTTPPersistRspSize]• $<strong>ns</strong> [new R<strong>and</strong>omVariable/PackMimeHTTPPersistent ], where probability isthe probability th<strong>at</strong> the connection is persistent• $<strong>ns</strong> [new R<strong>and</strong>omVariable/PackMimeHTTPNumPages ], whereprobability is the probability th<strong>at</strong> there is a single page in the connection <strong>and</strong> shape <strong>and</strong> scale are parametersto the Weibull distribution to determine the number of pages in the connection.• $<strong>ns</strong> [new R<strong>and</strong>omVariable/PackMimeHTTPSingleObjPages ], where probabilityis the probability th<strong>at</strong> there is a single object on the current page.• $<strong>ns</strong> [new R<strong>and</strong>omVariable/PackMimeHTTPObjsPerPage ], where shape <strong>and</strong> scaleare parameters to the Gamma distribution to determine the number of objects on a single page.• $<strong>ns</strong> [new R<strong>and</strong>omVariable/PackMimeHTTPTimeBtwnObjs]• $<strong>ns</strong> [new R<strong>and</strong>omVariable/PackMimeHTTPTimeBtwnPages]365


HTTP respo<strong>ns</strong>esclients servers DelayBox DelayBox webFigureweb41.2: Example Topology Using PackMimeHTTP <strong>and</strong> DelayBox. <strong>The</strong> cloud of web clients is a single <strong>ns</strong> node, <strong>and</strong> thecloud of web servers is a single <strong>ns</strong> node. Each of the DelayBox nodes is a single <strong>ns</strong> node.requests HTTP• $<strong>ns</strong> [new R<strong>and</strong>omVariable/PackMimeHTTPServerDelay ], where shape <strong>and</strong> scaleare paramters to the Weibull distribution to determine server delay.• $<strong>ns</strong> [R<strong>and</strong>omVariable/PackMimeHTTPXmit ], where type is 0 for client-side delays<strong>and</strong> 1 for server-side delays. Note: This r<strong>and</strong>om variable is only used in conjunction with DelayBox. It retur<strong>ns</strong> 1/2 ofthe actual delay because it is meant to be used with 2 DelayBox nodes, each of which should delay the packets for 1/2of the actual delay.41.3 Use of DelayBox with PackMime-HTTPPackMimeHTTP uses <strong>ns</strong> to model the TCP-level interaction between web clients <strong>and</strong> servers on the simul<strong>at</strong>ed link. Tosimul<strong>at</strong>e network-level effects of HTTP tra<strong>ns</strong>fer through the clouds, use DelayBox (see 22). DelayBox is an <strong>ns</strong> analog todummynet, often used in network testbeds to delay <strong>and</strong> drop packets. <strong>The</strong> delay times model the propag<strong>at</strong>ion <strong>and</strong> queuingdelay incurred from the source to the edge of the cloud (or edge of the cloud to destin<strong>at</strong>ion). Since all HTTP connectio<strong>ns</strong> inPackMimeHTTP take place between only two <strong>ns</strong> nodes, there must be an <strong>ns</strong> object to delay packets in each flow, r<strong>at</strong>her thanjust having a st<strong>at</strong>ic delay on the link between the two nodes. DelayBox also models bottleneck links <strong>and</strong> packet loss on anindividual connection basis. Two DelayBox nodes are used as shown in Figure 41.3. One node is placed in front of the webclient cloud <strong>ns</strong> node to h<strong>and</strong>le client-side delays, loss, <strong>and</strong> bottleneck links. <strong>The</strong> other DelayBox node is placed in front ofthe web server cloud <strong>ns</strong> node to h<strong>and</strong>le the server-side delays, loss, <strong>and</strong> bottleneck links.41.4 ExampleMore examples (including those th<strong>at</strong> demo<strong>ns</strong>tr<strong>at</strong>e the use of DelayBox with PackMime) are available in the tcl/ex/packmime/directory of the <strong>ns</strong> source code. <strong>The</strong> valid<strong>at</strong>ion script test-suite-packmime.tcl is in tcl/test/ <strong>and</strong> can be runwith the comm<strong>and</strong> test-all-packmime from th<strong>at</strong> directory.Note: <strong>The</strong> only PackMime-HTTP parameters th<strong>at</strong> must be set are r<strong>at</strong>e, client, server, flow_arrive, req_size,<strong>and</strong> rsp_size. <strong>The</strong> example below shows the minimal parameters th<strong>at</strong> need to be set, but other parameters can be set tochange the default behavior (see “Comm<strong>and</strong>s <strong>at</strong> a Glance”).# test-packmime.tcl# useful co<strong>ns</strong>tantsset CLIENT 0set SERVER 1366


emove-all-packet-headers;add-packet-header IP TCP;set <strong>ns</strong> [new Simul<strong>at</strong>or];$<strong>ns</strong> use-scheduler Heap;# removes all packet headers# adds TCP/IP headers# i<strong>ns</strong>tanti<strong>at</strong>e the Simul<strong>at</strong>or# use the Heap scheduler# SETUP TOPOLOGY# cre<strong>at</strong>e nodesset n(0) [$<strong>ns</strong> node]set n(1) [$<strong>ns</strong> node]# cre<strong>at</strong>e link$<strong>ns</strong> duplex-link $n(0) $n(1) 10Mb 0ms DropTail# SETUP PACKMIMEset r<strong>at</strong>e 15set pm [new PackMimeHTTP]$pm set-client $n(0);$pm set-server $n(1);$pm set-r<strong>at</strong>e $r<strong>at</strong>e;$pm set-http-1.1;# name $n(0) as client# name $n(1) as server# new connectio<strong>ns</strong> per second# use HTTP/1.1# SETUP PACKMIME RANDOM VARIABLESglobal defaultRNG# cre<strong>at</strong>e RNGs (appropri<strong>at</strong>e RNG seeds are assigned autom<strong>at</strong>ically)set flowRNG [new RNG]set reqsizeRNG [new RNG]set rspsizeRNG [new RNG]# cre<strong>at</strong>e R<strong>and</strong>omVariablesset flow_arrive [new R<strong>and</strong>omVariable/PackMimeHTTPFlowArrive $r<strong>at</strong>e]set req_size [new R<strong>and</strong>omVariable/PackMimeHTTPFileSize $r<strong>at</strong>e $CLIENT]set rsp_size [new R<strong>and</strong>omVariable/PackMimeHTTPFileSize $r<strong>at</strong>e $SERVER]# assign RNGs to R<strong>and</strong>omVariables$flow_arrive use-rng $flowRNG$req_size use-rng $reqsizeRNG$rsp_size use-rng $rspsizeRNG# set PackMime variables$pm set-flow_arrive $flow_arrive$pm set-req_size $req_size$pm set-rsp_size $rsp_size# record HTTP st<strong>at</strong>istics$pm set-outfile "d<strong>at</strong>a-test-packmime.d<strong>at</strong>"$<strong>ns</strong> <strong>at</strong> 0.0 "$pm start"$<strong>ns</strong> <strong>at</strong> 30.0 "$pm stop"$<strong>ns</strong> run367


41.5 Comm<strong>and</strong>s <strong>at</strong> a Glance<strong>The</strong> following comm<strong>and</strong>s on the PackMimeHTTP class can be accessed from OTcl:[new PackMimeHTTP]Cre<strong>at</strong>es a new PackMimeHTTP object.$packmime startStart gener<strong>at</strong>ing connectio<strong>ns</strong>$packmime stopStop gener<strong>at</strong>ing new connectio<strong>ns</strong>$packmime set-client Associ<strong>at</strong>es the node with the PackMimeHTTP client cloud$packmime set-server Associ<strong>at</strong>es the node with the PackMimeHTTP server cloud$packmime set-r<strong>at</strong>e Set the average number of new connectio<strong>ns</strong> started per second$packmime set-req_size Set the HTTP request size distribution$packmime set-rsp_size Set the HTTP respo<strong>ns</strong>e size distribution$packmime set-flow_arrive Set the time between two co<strong>ns</strong>ecutive connectio<strong>ns</strong> starting$packmime set-server_delay Set the web server delay for fetching pages$packmime set-run Set the run number so th<strong>at</strong> the RNGs used for the r<strong>and</strong>om variables will use the same substream (see Chapter 25 on RNG formore details).$packmime get-pairsReturn the number of completed HTTP request-respo<strong>ns</strong>e pairs. See tcl/ex/packmime/pm-end-pairs.tcl for anexample of using get-pairs to end the simul<strong>at</strong>ion after a certain number of pairs have completed.$packmime set-TCP Sets the TCP type (Reno, Newreno, or Sack) for all connectio<strong>ns</strong> in the client <strong>and</strong> server clouds - Reno is the defaultHTTP/1.1-Specific Comm<strong>and</strong>s$packmime set-http-1.1Use HTTP/1.1 distributio<strong>ns</strong> for persistent connectio<strong>ns</strong> i<strong>ns</strong>tead of HTTP/1.0.$packmime no-pm-persistent-reqszBy default, PackMime-HTTP sets all request sizes in a persistent connection to be the same. This option tur<strong>ns</strong> th<strong>at</strong> behavioroff <strong>and</strong> samples a new request size from the request size distribution for each request in a persistent connection.368


$packmime no-pm-persistent-rspszBy default, PackMime-HTTP uses an algorithm (see PackMimeHTTPPersistRspSizeR<strong>and</strong>omVariable::value()in packmime_ranvar.h for details) for setting the respo<strong>ns</strong>e sizes in a persistent connection. This option tur<strong>ns</strong> th<strong>at</strong> behavioroff <strong>and</strong> samples a new respo<strong>ns</strong>e size from the respo<strong>ns</strong>e size distribution for each respo<strong>ns</strong>e in a persistent connection.$packmime set-prob_persistent Set the probability th<strong>at</strong> the connection is persistent$packmime set-num_pages Set the number of pages per connection$packmime set-prob_single_obj Set the probability th<strong>at</strong> the page contai<strong>ns</strong> a single object$packmime set-objs_per_page Set the number of objects per page$packmime set-time_btwn_pages Set the time between page requests (i.e., think time)$packmime set-time_btwn_objs Set the time between object requestsOutput-Specific Comm<strong>and</strong>s$packmime active-connectio<strong>ns</strong>Output the current number of active HTTP connectio<strong>ns</strong> to st<strong>and</strong>ard error$packmime total-connectio<strong>ns</strong>Output the total number of completed HTTP connectio<strong>ns</strong> to st<strong>and</strong>ard error$packmime set-warmup Sets wh<strong>at</strong> time output should start. Only used with set outfile.$packmime set-outfile Output the following fields (one line per HTTP request-repo<strong>ns</strong>e pair) to filename:• time HTTP respo<strong>ns</strong>e completed• HTTP request size (bytes)• HTTP respo<strong>ns</strong>e size (bytes)• HTTP respo<strong>ns</strong>e time (ms) – time between client sending HTTP request <strong>and</strong> client receiving complete HTTP respo<strong>ns</strong>e• source node <strong>and</strong> port identifier• number of active connectio<strong>ns</strong> <strong>at</strong> the time this HTTP request-respo<strong>ns</strong>e pair completed$packmime set-filesz-outfile Right after sending a respo<strong>ns</strong>e, output the following fields (one line per HTTP request-repo<strong>ns</strong>e pair) to filename:• time HTTP respo<strong>ns</strong>e sent• HTTP request size (bytes)369


• HTTP respo<strong>ns</strong>e size (bytes)• server node <strong>and</strong> port address$packmime set-samples-outfile Right before sending a request, output the following fields (one line per HTTP request-repo<strong>ns</strong>e pair) to filename:• time HTTP request sent• HTTP request size (bytes)• HTTP respo<strong>ns</strong>e size (bytes)• server node <strong>and</strong> port address$packmime set-debug Set the debugging level:• 1: Output the total number of connectio<strong>ns</strong> cre<strong>at</strong>ed <strong>at</strong> the end of the simul<strong>at</strong>ion• 2: Level 1 +output cre<strong>at</strong>ion/management of TCP agents <strong>and</strong> applic<strong>at</strong>io<strong>ns</strong>output on start of new connectionnumber of bytes sent by the client <strong>and</strong> expected respo<strong>ns</strong>e sizenumber of bytes sent by server• 3: Level 2 +output when TCP agents <strong>and</strong> applic<strong>at</strong>io<strong>ns</strong> are moved to the pool• 4: Level 3 +output number of bytes received each time client or server receive a packet370


Part VIIScale371


Chapter 42Session-level Packet DistributionThis section describes the internals of the Session-level Packet Distribution implement<strong>at</strong>ion in <strong>ns</strong>. <strong>The</strong> section is in twoparts: the first part is an overview of Session configur<strong>at</strong>ion (Section 42.1), <strong>and</strong> a “complete” description of the configur<strong>at</strong>ionparameters of a Session. <strong>The</strong> second part describes the architecture, internals, <strong>and</strong> the code p<strong>at</strong>h of the Session-level Packetdistribution.<strong>The</strong> procedures <strong>and</strong> functio<strong>ns</strong> described in this chapter can be found in ~<strong>ns</strong>/tcl/session/session.tcl.Session-level Packet Distribution is oriented towards performing multicast simul<strong>at</strong>io<strong>ns</strong> over large topologies. <strong>The</strong> memoryrequirements for some topologies using session level simul<strong>at</strong>io<strong>ns</strong> are:2048 nodes, degree of connectivity = 8 ≈ 40 MB2049–4096 nodes ≈ 167 MB4097–8194 nodes ≈ 671 MBNote however, th<strong>at</strong> session level simul<strong>at</strong>io<strong>ns</strong> ignore qeueing delays. <strong>The</strong>refore, the accuracy of simul<strong>at</strong>io<strong>ns</strong> th<strong>at</strong> use sourceswith a high d<strong>at</strong>a r<strong>at</strong>e, or those th<strong>at</strong> use multiple sources th<strong>at</strong> get aggreg<strong>at</strong>ed <strong>at</strong> points within the network is suspect.42.1 Configur<strong>at</strong>ionConfigur<strong>at</strong>ion of a session level simul<strong>at</strong>ion co<strong>ns</strong>ists of two parts, configur<strong>at</strong>ion of the session level details themselves (Section42.1.1) <strong>and</strong> adding loss <strong>and</strong> error models to the session level abstraction to model specific behaviours (Section 42.1.2).42.1.1 Basic Configur<strong>at</strong>ion<strong>The</strong> basic configur<strong>at</strong>ion co<strong>ns</strong>ists of cre<strong>at</strong>ing <strong>and</strong> configuring a multicast session. Each Session (i.e., a multicast tree) must beconfigured strictly in this order: (1) cre<strong>at</strong>e <strong>and</strong> configure the session source, (2) cre<strong>at</strong>e the session helper <strong>and</strong> <strong>at</strong>tach it to thesession source, <strong>and</strong> finally, (3) have the session members join the session.set <strong>ns</strong> [new SessionSim]set node [$<strong>ns</strong> node]set group [$<strong>ns</strong> allocaddr];# preamble initializ<strong>at</strong>ion372


SourceSourceLossy LinkLossy Links121233Figure 42.1: Comparison of Multicast Trees for Detailed vs. Session Routingset udp [new Agent/UDP]$udp set dst_ $groupset src [new Applic<strong>at</strong>ion/Traffic/CBR]$src <strong>at</strong>tach-agent $udp$<strong>ns</strong> <strong>at</strong>tach-agent $node $udp$<strong>ns</strong> cre<strong>at</strong>e-session $node $udpset rcvr [new Agent/NULL]$<strong>ns</strong> <strong>at</strong>tach-agent $node $rcvr$<strong>ns</strong> <strong>at</strong> 0.0 "$node join-group $rcvr $group";# cre<strong>at</strong>e <strong>and</strong> configure the source;# cre<strong>at</strong>e <strong>at</strong>tach session helper to src;# configure the receiver;# joining the session$<strong>ns</strong> <strong>at</strong> 0.1 "$src start"A session level simul<strong>at</strong>ion scales by tra<strong>ns</strong>l<strong>at</strong>ing the topology into a virtual mesh topology. <strong>The</strong> steps involved in doing thisare:1. All of the classifiers <strong>and</strong> replic<strong>at</strong>ors are elimin<strong>at</strong>ed. Each node only stores i<strong>ns</strong>tance variables to track its node id, <strong>and</strong>port ids.2. Links do not co<strong>ns</strong>ist of multiple components. Each link only stores i<strong>ns</strong>tance variables to track the b<strong>and</strong>width <strong>and</strong> delay<strong>at</strong>tributes.3. <strong>The</strong> topology, co<strong>ns</strong>isting of links is tra<strong>ns</strong>l<strong>at</strong>ed into a virtual mesh.Figure 42.1 shows the difference between a multicast tree in a detailed simul<strong>at</strong>ion <strong>and</strong> one in a session level simul<strong>at</strong>ion. Noticeth<strong>at</strong> the tra<strong>ns</strong>l<strong>at</strong>ion process results in a session level simul<strong>at</strong>ion ignoring queuing delays. For most simul<strong>at</strong>io<strong>ns</strong>, <strong>ns</strong> alreadyignores processing delays <strong>at</strong> all of the nodes.373


42.1.2 I<strong>ns</strong>erting a Loss ModuleWhen studying a protocol (e.g., SRM error recovery mechanism), it might be useful to study protocol behavior over lossylinks. However, since a session level simul<strong>at</strong>ion scales by abstracting out the internal topology, we need additional mechanismsto i<strong>ns</strong>ert a loss module appropri<strong>at</strong>ely. This subsection describes how one can cre<strong>at</strong>e these loss modules to model errorscenarios.Cre<strong>at</strong>ing a Loss Module Before we can i<strong>ns</strong>ert a loss module in between a source-receiver pair, we have to cre<strong>at</strong>e the lossmodule. Basically, a loss module compares two values to decide whether to drop a packet. <strong>The</strong> first value is obtained everytime when the loss module receives a packet from a r<strong>and</strong>om variable. <strong>The</strong> second value is fixed <strong>and</strong> configured when the lossmodule is cre<strong>at</strong>ed.<strong>The</strong> following code gives an example to cre<strong>at</strong>e a uniform 0.1 loss r<strong>at</strong>e.# cre<strong>at</strong>ing the uniform distribution r<strong>and</strong>om variableset loss_r<strong>and</strong>om_variable [new R<strong>and</strong>omVariable/Uniform]$loss_r<strong>and</strong>om_variable set min_ 0;# set the range of the r<strong>and</strong>om variable$loss_r<strong>and</strong>om_variable set max_ 100set loss_module [new ErrorModel];# cre<strong>at</strong>e the error model$loss_module drop-target [new Agent/Null]$loss_module set r<strong>at</strong>e_ 10 ;# set error r<strong>at</strong>e to 0.1 = 10 / (100 − 0)$loss_module ranvar $loss_r<strong>and</strong>om_variable;# <strong>at</strong>tach r<strong>and</strong>om var. to loss moduleA c<strong>at</strong>alogue of the r<strong>and</strong>om variable distributio<strong>ns</strong> was described earlier (Chapter 25). A more detailed discussion of errormodels was also described earlier in a different chapter (Chapter 13).I<strong>ns</strong>erting a Loss Module A loss module can only be i<strong>ns</strong>erted after the corresponding receiver has joined the group. <strong>The</strong>example code below illustr<strong>at</strong>es how a simul<strong>at</strong>ion script can introduce a loss module.set sessionhelper [$<strong>ns</strong> cre<strong>at</strong>e-session $node $src] ;# keep a h<strong>and</strong>le to the loss module$<strong>ns</strong> <strong>at</strong> 0.1 "$sessionhelper i<strong>ns</strong>ert-depended-loss $loss_module $rcvr"42.2 Architecture<strong>The</strong> purpose of Session-level packet distribution is to speed up simul<strong>at</strong>io<strong>ns</strong> <strong>and</strong> reduce memory co<strong>ns</strong>umption while maintainingreasonable accuracy. <strong>The</strong> first bottleneck observed is the memory co<strong>ns</strong>umption by heavy-weight links <strong>and</strong> nodes.<strong>The</strong>refore, in SessionSim (Simul<strong>at</strong>or for Session-level packet distribution), we keep only minimal amount of st<strong>at</strong>es for links<strong>and</strong> nodes, <strong>and</strong> connect the higher level source <strong>and</strong> receiver applic<strong>at</strong>io<strong>ns</strong> with appropri<strong>at</strong>e delay <strong>and</strong> loss modules. A particularsource in a group sends its d<strong>at</strong>a packets to a replic<strong>at</strong>or th<strong>at</strong> is respo<strong>ns</strong>ible for replic<strong>at</strong>ing the packets for all the receivers.Intermedi<strong>at</strong>e loss <strong>and</strong> delay modules between this replic<strong>at</strong>or <strong>and</strong> the receivers will guarantee the appropri<strong>at</strong>e end-to-end characteristics.To put it another way, a session level simul<strong>at</strong>ion abstracts out the topology, routing <strong>and</strong> queueing delays. Packetsin SessionSim do not get routed. <strong>The</strong>y only follow the established Session.374


42.3 InternalsThis section describes the internals of Session-level Packet Distribution. We first describe the OTcl primitives to configure asession level simul<strong>at</strong>ion (Section 42.3.1); we conclude with a brief note on hos packet forwarding is achieved (Section 42.3.2).42.3.1 Object LinkageWe describe three aspects of co<strong>ns</strong>tructing a session level simul<strong>at</strong>ion in <strong>ns</strong>: the modified topology routines th<strong>at</strong> permit thecre<strong>at</strong>ion of abstract nodes <strong>and</strong> links, establish the session helper for each active source, add receivers to the session byi<strong>ns</strong>erting the appropri<strong>at</strong>e loss <strong>and</strong> delay models when th<strong>at</strong> receiver joi<strong>ns</strong> the appropri<strong>at</strong>e group.Nodes <strong>and</strong> Links <strong>The</strong> node contai<strong>ns</strong> only its node id <strong>and</strong> the port number for the next agent. A link only contai<strong>ns</strong> the valuesof its b<strong>and</strong>width <strong>and</strong> delay.SessionNode i<strong>ns</strong>tproc init {} {$self i<strong>ns</strong>tvar id_ np_set id_ [Node getid]set np_ 0}SessionSim i<strong>ns</strong>tproc simplex-link { n1 n2 bw delay type } {$self i<strong>ns</strong>tvar bw_ delay_set sid [$n1 id]set did [$n2 id]}set bw_($sid:$did) [expr [string trimright $bw Mb] * 1000000]set delay_($sid:$did) [expr [string trimright $delay ms] * 0.001]Session Helper Each active source in a session requires a “session helper”. <strong>The</strong> session helper in <strong>ns</strong> is realised througha replic<strong>at</strong>or. This session helper is cre<strong>at</strong>ed when the user issues a cre<strong>at</strong>e-session{} to identify the source agent. <strong>The</strong>simul<strong>at</strong>or itself keeps a reference to the session helper in its i<strong>ns</strong>tance variable array, session_, indexed by the source <strong>and</strong>destin<strong>at</strong>ion address of the source.Note th<strong>at</strong> the destin<strong>at</strong>ion of source agent must be set before calling cre<strong>at</strong>e-session{}.SessionSim i<strong>ns</strong>tproc cre<strong>at</strong>e-session { node agent } {$self i<strong>ns</strong>tvar session_}set nid [$node id]set dst [$agent set dst_]set session_($nid:$dst) [new Classifier/Replic<strong>at</strong>or/Demuxer]$agent target $session_($nid:$dst);# <strong>at</strong>tach the replic<strong>at</strong>or to the sourcereturn $session_($nid:$dst) ;# keep the replic<strong>at</strong>or in the SessionSim i<strong>ns</strong>tance variable array session_375


Delay <strong>and</strong> Loss Modules Each receiver in a group requires a delay module th<strong>at</strong> reflects its delay with respect to theparticular source. When the receiver joi<strong>ns</strong> a group, join-group{} identifies all session helpers in session_. If thedestin<strong>at</strong>ion index m<strong>at</strong>ches the group address the receiver are joining, then the following actio<strong>ns</strong> are performed.1. A new slot of the session helper is cre<strong>at</strong>ed <strong>and</strong> assigned to the receiver.2. <strong>The</strong> routine computes the accumul<strong>at</strong>ed b<strong>and</strong>width <strong>and</strong> delay between the source <strong>and</strong> receiver using the SessionSimi<strong>ns</strong>tance procedures get-bw{} <strong>and</strong> get-delay{}.3. A co<strong>ns</strong>tant r<strong>and</strong>om variable is cre<strong>at</strong>ed; it will gener<strong>at</strong>e r<strong>and</strong>om delivery times using the accumul<strong>at</strong>ive delay as anestim<strong>at</strong>e of the average delay.4. A new delay module is cre<strong>at</strong>ed with the end-to-end b<strong>and</strong>width characteristics, <strong>and</strong> the r<strong>and</strong>om variable gener<strong>at</strong>or providesthe delay estim<strong>at</strong>es.5. <strong>The</strong> delay module in i<strong>ns</strong>erted into the session helper <strong>and</strong> interposed between the helper <strong>and</strong> the receiver.See Section 42.1.2 for similarly i<strong>ns</strong>erting a loss module for a receiver.SessionSim i<strong>ns</strong>tproc join-group { agent group } {$self i<strong>ns</strong>tvar session_foreach index [array names session_] {set pair [split $index :]if {[lindex $pair 1] == $group} {# Note: must i<strong>ns</strong>ert the chain of loss, delay,# <strong>and</strong> destin<strong>at</strong>ion agent in this order:$session_($index) i<strong>ns</strong>ert $agentset src [lindex $pair 0]set dst [[$agent set node_] id]set accu_bw [$self get-bw $dst $src]set delay [$self get-delay $dst $src];# i<strong>ns</strong>ert destin<strong>at</strong>ion agent into session replic<strong>at</strong>or;# find accum. b/w <strong>and</strong> delayset r<strong>and</strong>om_variable [new R<strong>and</strong>omVariable/Co<strong>ns</strong>tant]$r<strong>and</strong>om_variable set avg_ $delayset delay_module [new DelayModel]$delay_module b<strong>and</strong>width $accu_bw$delay_module ranvar $r<strong>and</strong>om_variable;# set delay variable;# configure the delay module}}}$session_($index) i<strong>ns</strong>ert-module $delay_module $agent ;# i<strong>ns</strong>ert the delay module42.3.2 Packet ForwardingPacket forwarding activities are executed in C++. A source applic<strong>at</strong>ion gener<strong>at</strong>es a packet <strong>and</strong> forwards to its target whichmust be a replic<strong>at</strong>or (session helper). <strong>The</strong> replic<strong>at</strong>or copies the packet <strong>and</strong> forwards to targets in the active slots which areeither delay modules or loss modules. If loss modules, a decision is made whether to drop the packet. If yes, the packet is376


Figure 42.2: Architectural Realiz<strong>at</strong>ion of a Session Level Simul<strong>at</strong>ion Sessionforwarded to the loss modules drop target. If not, the loss module forwards it to its target which must be a delay module. <strong>The</strong>delay module will forward the packet with a delay to its target which must be a receiver applic<strong>at</strong>ion.42.4 Comm<strong>and</strong>s <strong>at</strong> a glanceFollowing is a list of session-level rel<strong>at</strong>ed comm<strong>and</strong>s:set <strong>ns</strong> [new SessionSim]This comm<strong>and</strong> cre<strong>at</strong>es an i<strong>ns</strong>tance of the sessionmode simul<strong>at</strong>or.$<strong>ns</strong>_ cre<strong>at</strong>e-session This comm<strong>and</strong> cre<strong>at</strong>es <strong>and</strong> <strong>at</strong>taches a session-helper, which is basically a replic<strong>at</strong>or, for the source cre<strong>at</strong>ed <strong>at</strong> the.377


Chapter 43Asim: approxim<strong>at</strong>e analytical simul<strong>at</strong>ionThis chapter describes a fast approxim<strong>at</strong>e network simul<strong>at</strong>or, Asim. Asim solves the steady st<strong>at</strong>e of the network usingapproxim<strong>at</strong>e fixed points. <strong>The</strong> overall structure is shown in Figure 43.1. <strong>The</strong> user feeds a regular <strong>ns</strong> script <strong>and</strong> tur<strong>ns</strong> on theasim flag. Asim would do a fast approxim<strong>at</strong>e simul<strong>at</strong>ion of the network scenario <strong>and</strong> would present to the user the dropprobabilities of the routers, the delays <strong>and</strong> the approxim<strong>at</strong>e aggreg<strong>at</strong>e throughput of the links <strong>and</strong> the flows.In particular, we the following links/traffic are supported:• Drop Tail Queues• RED Queues• Bulk TCP flows with FTP traffic• Short lived TCP flows<strong>The</strong> d<strong>at</strong>a structures of Asim are popul<strong>at</strong>ed by a module within the Tcl space of <strong>ns</strong> from the user supplied script. Uponexecuting Asim, the results can be accessed using Tcl routines. To use the Asim within a script the user has to useSimul<strong>at</strong>or set useasim_ 1Flow st<strong>at</strong>ecomput<strong>at</strong>io<strong>ns</strong>NSscriptParserInitialconditio<strong>ns</strong>Terminalconditio<strong>ns</strong> ? Yes Networkst<strong>at</strong>eNoRouter st<strong>at</strong>ecomput<strong>at</strong>io<strong>ns</strong>Figure 43.1: <strong>The</strong> structure of Asim378


By default, this flag is set to 0A simple script is given belowproc addsrc { s } {global <strong>ns</strong>set t [$<strong>ns</strong> set src_]lappend t $s$<strong>ns</strong> set src_ $t}proc adddst { src } {global <strong>ns</strong>set t [$<strong>ns</strong> set dst_]lappend t $src$<strong>ns</strong> set dst_ $t}proc finish {} {}global <strong>ns</strong> fmo<strong>ns</strong>et drops [$fmon set pdrops_]set pkts [$fmon set parrivals_]set notDroped [$fmon set pdepartures_]set overflow_prob [expr 1.0 * $drops / $pkts]puts [form<strong>at</strong> "tdrops $drops tpkts $pkts o_prob. %7.4f" $overflow_prob]exit 0set N_ 100000set arrival 0set available $N_set endTime_ 200set <strong>ns</strong> [new Simul<strong>at</strong>or]$<strong>ns</strong> set useasim_ 1$<strong>ns</strong> <strong>at</strong> $endTime_ "finish"set src_ ""set dst_ ""$<strong>ns</strong> set src_ $src_$<strong>ns</strong> set dst_ $dst_set n(0) [$<strong>ns</strong> node]379


set n(1) [$<strong>ns</strong> node]set link(0:1) [$<strong>ns</strong> duplex-link $n(0) $n(1) 1Mbps 50ms RED]for {set i 0} { $i < 4} {incr i} {set ltcp($i) [new Agent/TCP]set ltcpsink($i) [new Agent/TCPSink]$<strong>ns</strong> <strong>at</strong>tach-agent $n(0) $ltcp($i)$<strong>ns</strong> <strong>at</strong>tach-agent $n(1) $ltcpsink($i)$<strong>ns</strong> connect $ltcp($i) $ltcpsink($i)set lftp($i) [new Applic<strong>at</strong>ion/FTP]$lftp($i) <strong>at</strong>tach-agent $ltcp($i)$<strong>ns</strong> <strong>at</strong> 0 "$lftp($i) start"}# Short term flowsaddsrc 1adddst 0set pool [new PagePool/WebTraf]# Set up server <strong>and</strong> client nodes$pool set-num-client [llength [$<strong>ns</strong> set src_]]$pool set-num-server [llength [$<strong>ns</strong> set dst_]]global <strong>ns</strong>et i 0foreach s [$<strong>ns</strong> set src_] {$pool set-client $i $n($s)incr i}set i 0foreach s [$<strong>ns</strong> set dst_] {$pool set-server $i $n($s)incr i}# Number of Pages per Sessio<strong>ns</strong>et numPage 100000$pool set-num-session 1set interPage [new R<strong>and</strong>omVariable/Exponential]$interPage set avg_ 0.5set pageSize [new R<strong>and</strong>omVariable/Co<strong>ns</strong>tant]$pageSize set val_ 1set interObj [new R<strong>and</strong>omVariable/Exponential]$interObj set avg_ 1set objSize [new R<strong>and</strong>omVariable/Co<strong>ns</strong>tant]$objSize set val_ 20380


# This is needed$pool use-asim$pool cre<strong>at</strong>e-session 0 $numPage 0 $interPage $pageSize $interObj $objSize# Dumps internal d<strong>at</strong>a structures to this dumpfile$<strong>ns</strong> asim-dump dumpfile# Calls asim-run$<strong>ns</strong> asim-run# Access asim st<strong>at</strong>isticsset l [$<strong>ns</strong> link $n(0) $n(1)]puts "after asim run, link bw = [$<strong>ns</strong> asim-getLinkTput $l] packets"puts "after asim run, flow bw = [$<strong>ns</strong> asim-getFlowTput $ltcp(0)] packets"381


Part VIIIEmul<strong>at</strong>ion382


Chapter 44Emul<strong>at</strong>ionThis chapter describes the emul<strong>at</strong>ion facility of <strong>ns</strong>. Emul<strong>at</strong>ion refers to the ability to introduce the simul<strong>at</strong>or into a livenetwork. Special objects within the simul<strong>at</strong>or are capable of introducing live traffic into the simul<strong>at</strong>or <strong>and</strong> injecting trafficfrom the simul<strong>at</strong>or into the live network.Emul<strong>at</strong>or cave<strong>at</strong>s:• While the interfaces described below are not expected to change drastically, this facility is still under development <strong>and</strong>should be co<strong>ns</strong>idered experimental <strong>and</strong> subject to change.• <strong>The</strong> facility described here has been developed under FreeBSD 2.2.5, <strong>and</strong> use on other systems has not been tested bythe author.• Because of the currently limited portability of emul<strong>at</strong>ion, it is only compiled into <strong>ns</strong>e (build it with “make <strong>ns</strong>e”), notst<strong>and</strong>ard <strong>ns</strong>.44.1 Introduction<strong>The</strong> emul<strong>at</strong>ion facility can be subdivided into two modes:1. opaque mode – live d<strong>at</strong>a tre<strong>at</strong>ed as opaque d<strong>at</strong>a packets2. protocol mode – live d<strong>at</strong>a may be interpreted/gener<strong>at</strong>ed by simul<strong>at</strong>orIn opaque mode, the simul<strong>at</strong>or tre<strong>at</strong>s network d<strong>at</strong>a as uninterpreted packets. In particular, real-world protocol fields are notdirectly manipul<strong>at</strong>ed by the simul<strong>at</strong>or. In opaque mode, live d<strong>at</strong>a packets may be dropped, delayed, re-ordered, or duplic<strong>at</strong>ed,but because no protocol processing is performed, protocol-specific traffic manipul<strong>at</strong>ion scenarios (e.g. “drop the TCP segmentcontaining a retra<strong>ns</strong>mission of sequence number 23045”) may not be performed. In protocol mode, the simul<strong>at</strong>or is able tointerpret <strong>and</strong>/or gener<strong>at</strong>e live network traffic containing arbitrary field assignments. To d<strong>at</strong>e (Mar 1998), only Opaque Modeis currently implemented.<strong>The</strong> interface between the simul<strong>at</strong>or <strong>and</strong> live network is provided by a collection of objects including tap agents <strong>and</strong> networkobjects. Tap agents embed live network d<strong>at</strong>a into simul<strong>at</strong>ed packets <strong>and</strong> vice-versa. Network objects are i<strong>ns</strong>talled in tap agents<strong>and</strong> provide an entrypoint for the sending <strong>and</strong> receipt of live d<strong>at</strong>a. Both objects are described in the following sectio<strong>ns</strong>.383


When using the emul<strong>at</strong>ion mode, a special version of the system scheduler is used: the RealTime scheduler. This scheduleruses the same underlying structure as the st<strong>and</strong>ard calendar-queue based scheduler, but ties the execution of events to realtime.It is described below.44.2 Real-Time Scheduler<strong>The</strong> real-time scheduler implements a soft real-time scheduler which ties event execution within the simul<strong>at</strong>or to real time.Provided sufficient CPU horsepower is available to keep up with arriving packets, the simul<strong>at</strong>or virtual time should closelytrack real-time. If the simul<strong>at</strong>or becomes too slow to keep up with elapsing real time, a warning is continually produced if theskew exceeds a pre-specified co<strong>ns</strong>tant “slop factor” (currently 10ms).<strong>The</strong> main disp<strong>at</strong>ch loop is found in the routine RealTimeScheduler::run(), in the file scheduler.cc. It followsessentially the following algorithm:• While simul<strong>at</strong>or is not halted– get current real time (“now”)– disp<strong>at</strong>ch all pending simul<strong>at</strong>or events prior to now– fetch next (future) event if there is one– delay until the next simul<strong>at</strong>or event is ready or a Tcl event occurs– if a tcl event occured, re-i<strong>ns</strong>ert next event in simul<strong>at</strong>or event queue <strong>and</strong> continue– otherwise, disp<strong>at</strong>ch simul<strong>at</strong>or event, continue– if there was no future even, check for Tcl events <strong>and</strong> continue<strong>The</strong> real-time scheduler should always be used with the emul<strong>at</strong>ion facility. Failure to do so may easily result in the simul<strong>at</strong>orrunning faster than real-time. In such cases, traffic passing through the simul<strong>at</strong>ed network will not be delayed by the properamount of time. Enabling the real-time scheduler requires the following specific<strong>at</strong>ion <strong>at</strong> the beginning of a simul<strong>at</strong>ion script:set <strong>ns</strong> [new Simul<strong>at</strong>or]$<strong>ns</strong> use-scheduler RealTime44.3 Tap Agents<strong>The</strong> class TapAgent is a simple class derived from the base Agent class. As such, it is able to gener<strong>at</strong>e simul<strong>at</strong>or packetscontaining arbitrarily-assigned values within the <strong>ns</strong> common header. <strong>The</strong> tap agent h<strong>and</strong>les the setting of the common headerpacket size field <strong>and</strong> the type field. It uses the packet type PT_LIVE for packets injected into the simul<strong>at</strong>or. Each tap agentcan have <strong>at</strong> most one associ<strong>at</strong>ed network object, although more than one tap agent may be i<strong>ns</strong>tanti<strong>at</strong>ed on a single simul<strong>at</strong>ornode.Configur<strong>at</strong>ion Tap agents are able to send <strong>and</strong> receive packets to/from an associ<strong>at</strong>ed Network object. Assuming a networkobject $netobj refers to a network object, a tap agent is configured using the network method:set a0 [new Agent/Tap]384


$a0 network $netobj$a0 set fid_ 26$a0 set prio_ 2$<strong>ns</strong> connect $a0 $a1Note th<strong>at</strong> the configur<strong>at</strong>ion of the flow ID <strong>and</strong> priority are h<strong>and</strong>led through the Agent base class. <strong>The</strong> purpose of settingthe flow id field in the common header is to label packets belonging to particular flows of live d<strong>at</strong>a. Such packets can bedifferentially tre<strong>at</strong>ed with respect to drops, reorderings, etc. <strong>The</strong> connect method i<strong>ns</strong>tructs agent $a0 to send its live trafficto the $a1 agent via the current route through the simul<strong>at</strong>ed topology.44.4 Network ObjectsNetwork objects provide access to a live network. <strong>The</strong>re are several forms of network objects, depending on the protocollayer specified for access to the underlying network, in addition to the facilities provided by the host oper<strong>at</strong>ing system. Useof some network objects requires special access privileges where noted. Generally, network objects provide an entrypointinto the live network <strong>at</strong> a particular protocol layer (e.g. link, raw IP, UDP, etc) <strong>and</strong> with a particular access mode (read-only,write-only, or read-write). Some network objects provide specialized facilities such as filtering or promiscuous access (i.e.the pcap/bpf network object) or group membership (i.e. UDP/IP multicast). <strong>The</strong> C++ class Network is provided as a baseclass from which specific network objects are derived. Three network objects are currently supported: pcap/bpf, raw IP, <strong>and</strong>UDP/IP. Each are described below.44.4.1 Pcap/BPF Network Objects<strong>The</strong>se objects provide an extended interface to the LBNL packet capture library (libpcap). (See ftp://ftp.ee.lbl.gov/libpcap.tafor more info). This library provides the ability to capture link-layer frames in a promiscuous fashion from network interfacedrivers (i.e. a copy is made for those programs making use of libpcap). It also provides the ability to read <strong>and</strong> write packettrace files in the “tcpdump” form<strong>at</strong>. <strong>The</strong> extended interface provided by <strong>ns</strong> also allows for writing frames out to the networkinterface driver, provided the driver itself allows this action. Use of the library to capture or cre<strong>at</strong>e live traffic may be protected;one generally requires <strong>at</strong> least read access to the system’s packet filter facility which may need to be arranged througha system administr<strong>at</strong>or.<strong>The</strong> packet capture library works on several UNIX-based pl<strong>at</strong>forms. It is optimized for use with the Berkeley Packet Filter(BPF) [25], <strong>and</strong> provides a filter compiler for the BPF pseudomachine machine code. On most systems supporting it, a kernelresidentBPF implement<strong>at</strong>ion processes the filter code, <strong>and</strong> applies the resulting p<strong>at</strong>tern m<strong>at</strong>ching i<strong>ns</strong>tructio<strong>ns</strong> to receivedframes. Those frames m<strong>at</strong>ching the p<strong>at</strong>ter<strong>ns</strong> are received through the BPF machinery; those not m<strong>at</strong>ching the p<strong>at</strong>tern areotherwise unaffected. BPF also supports sending link-layer frames. This is generally not suggested, as an entire properlyform<strong>at</strong>tedframe must be cre<strong>at</strong>ed prior to h<strong>and</strong>ing it off to BPF. This may be problem<strong>at</strong>ic with respect to assigning properlink-layer headers for next-hop destin<strong>at</strong>io<strong>ns</strong>. It is generally preferable to use the raw IP network object for sending IP packets,as the system’s routing function will be used to determine proper link-layer encapsul<strong>at</strong>ing headers.Configur<strong>at</strong>ion Pcap network objects may be configured as either associ<strong>at</strong>ed with a live network or with a trace file. Ifassoci<strong>at</strong>ed with a live network, the particular network interface to be used may be specified, as well as an optional promiscuousflag. As with all network objects, they may be opened for reading or writing. Here is an example:set me [exec hostname]set pf1 [new Network/Pcap/Live]$pf1 set promisc_ true385


set intf [$pf1 open readonly]puts "pf1 configured on interface $intf"set filt "(ip src host foobar) <strong>and</strong> (not ether broadcast)"set nbytes [$pf1 filter $filt]puts "filter compiled to $nbytes bytes"puts "drops: [$pf1 pdrops], pkts: [$pf1 pkts]"This example first determines the name of the local system which will be used in co<strong>ns</strong>tructing a BPF/libpcap filter predic<strong>at</strong>e.<strong>The</strong> new Network/Pcap/Live call cre<strong>at</strong>es an i<strong>ns</strong>tance of the pcap network object for capturing live traffic. <strong>The</strong>promisc_ flag tells the packet filter whether it should configure the undelying interface in promiscuous mode (if it is supported).<strong>The</strong> open call activ<strong>at</strong>es the packet filter, <strong>and</strong> may be specified as readonly, writeonly, or readwrite. Itretur<strong>ns</strong> the name of the network interface the filter is associ<strong>at</strong>ed with. <strong>The</strong> open call takes an optional extra parameter (notillustr<strong>at</strong>ed) indic<strong>at</strong>ing the name of the interface to use in cases where a particular interface should be used on a multi-homedhost. <strong>The</strong> filter method is used to cre<strong>at</strong>e a BPF-comp<strong>at</strong>ible packet filter program which is loaded into the underlying BPFmachinery. <strong>The</strong> filter method retur<strong>ns</strong> the number of bytes used by the filter predic<strong>at</strong>e. <strong>The</strong> pdrops <strong>and</strong> pkts methodsare available for st<strong>at</strong>istics collection. <strong>The</strong>y report the number of packets dropped by the filter due to buffer exhaustion <strong>and</strong> thetotal number of packets th<strong>at</strong> arrived <strong>at</strong> the filter, respectively (not the number of packets accepted by the filter).44.4.2 IP Network Objects<strong>The</strong>se objects provide raw access to the IP protocol, <strong>and</strong> allow the complete specific<strong>at</strong>ion of IP packets (including header).<strong>The</strong> implement<strong>at</strong>ion makes use of a raw socket. In most UNIX systems, access to such sockets requires super-user privileges.In addition, the interface to raw sockets is somewh<strong>at</strong> less st<strong>and</strong>ard than other types of sockets. <strong>The</strong> class Network/IPprovides raw IP functionality plus a base class from which other network objects implementing higher-layer protocols arederived.Configur<strong>at</strong>ion <strong>The</strong> configur<strong>at</strong>ion of a raw IP network object is compar<strong>at</strong>ively simple. <strong>The</strong> object is not associ<strong>at</strong>ed withany particular physical network interface; the system’s IP routing capability will be used to emit the specified d<strong>at</strong>agram outwhichever interface is required to reach the destin<strong>at</strong>ion address contained in the header. Here is an example of configuring anIP object:set ipnet [new Network/IP]$ipnet open writeonly...$ipnet close<strong>The</strong> IP network object supports only the open <strong>and</strong> close methods.44.4.3 IP/UDP Network Objects<strong>The</strong>se objects provide access to the system’s UDP implement<strong>at</strong>ion along with support for IP multicast group membershipoper<strong>at</strong>io<strong>ns</strong>. IN PROGRESS386


44.5 An Example<strong>The</strong> following code illustr<strong>at</strong>es a small but complete simul<strong>at</strong>ion script for setting up an emul<strong>at</strong>ion test using BPF <strong>and</strong> IP networkobjects. It was run on a multi-homed machine, <strong>and</strong> the simul<strong>at</strong>or essentially provides routing capability by reading framesfrom one interface, passing them through the simul<strong>at</strong>ed network, <strong>and</strong> writing them out via the raw IP network object:set me "10.0.1.1"set <strong>ns</strong> [new Simul<strong>at</strong>or]$<strong>ns</strong> use-scheduler RealTime## we want the test machine to have ip forwarding disabled, so# check this (this is how to do so under FreeBSD <strong>at</strong> least)#set ipforw [exec sysctl -n net.inet.ip.forwarding]if $ipforwputs "can not run with ip forwarding enabled"exit 1## alloc<strong>at</strong>e a BPF type network object <strong>and</strong> a raw-IP object#set bpf0 [new Network/Pcap/Live]set bpf1 [new Network/Pcap/Live]$bpf0 set promisc_ true$bpf1 set promisc_ trueset ipnet [new Network/IP]set nd0 [$bpf0 open readonly fxp0]set nd1 [$bpf1 open readonly fxp1]$ipnet open writeonly## try to filter out weird stuff like netbios pkts, arp requests, d<strong>ns</strong>,# also, don’t c<strong>at</strong>ch stuff to/from myself or broadcasted#set notme "(not ip host $me)"set notbcast "(not ether broadcast)"set ftp "<strong>and</strong> port ftp-d<strong>at</strong>a"set f0len [$bpf0 filter "(ip dst host bit) <strong>and</strong> $notme <strong>and</strong> $notbcast"]set f1len [$bpf1 filter "(ip src host bit) <strong>and</strong> $notme <strong>and</strong> $notbcast"]puts "filter lengths: $f0len (bpf0), $f1len (bpf1)"puts "dev $nd0 has address [$bpf0 linkaddr]"puts "dev $nd1 has address [$bpf1 linkaddr]"set a0 [new Agent/Tap]set a1 [new Agent/Tap]set a2 [new Agent/Tap]387


puts "i<strong>ns</strong>tall nets into taps..."$a0 network $bpf0$a1 network $bpf1$a2 network $ipnetset node0 [$<strong>ns</strong> node]set node1 [$<strong>ns</strong> node]set node2 [$<strong>ns</strong> node]$<strong>ns</strong> simplex-link $node0 $node2 10Mb 10ms DropTail$<strong>ns</strong> simplex-link $node1 $node2 10Mb 10ms DropTail$<strong>ns</strong> <strong>at</strong>tach-agent $node0 $a0$<strong>ns</strong> <strong>at</strong>tach-agent $node1 $a1$<strong>ns</strong> <strong>at</strong>tach-agent $node2 $a2$<strong>ns</strong> connect $a0 $a2$<strong>ns</strong> connect $a1 $a2puts "okey"$<strong>ns</strong> run44.6 Comm<strong>and</strong>s <strong>at</strong> a glanceFollowing is a list of emul<strong>at</strong>ion rel<strong>at</strong>ed comm<strong>and</strong>s:$<strong>ns</strong>_ use-scheduler RealTimeThis comm<strong>and</strong> sets up the real-time scheduler. Note th<strong>at</strong> a real-time scheduler should be used with any emul<strong>at</strong>ion facility.Otherwise it may result the simul<strong>at</strong>ed network running faster than real-time.set netob [new Network/]This comm<strong>and</strong> cre<strong>at</strong>es an i<strong>ns</strong>tance of a network object. Network objects are used to access a live network. Currently thetypes of network objects available are Network/Pcap/Live, Network/IP <strong>and</strong> Network/IP/UDP. See section 44.4 for details onnetwork objects.388


Part IXVisualiz<strong>at</strong>ion with Nam - <strong>The</strong> NetworkAnim<strong>at</strong>or389


Chapter 45Nam45.1 IntroductionNam is a Tcl/TK based anim<strong>at</strong>ion tool for viewing network simul<strong>at</strong>ion traces <strong>and</strong> real world packet traced<strong>at</strong>a. <strong>The</strong> designtheory behind nam was to cre<strong>at</strong>e an anim<strong>at</strong>or th<strong>at</strong> is able to read large anim<strong>at</strong>ion d<strong>at</strong>a sets <strong>and</strong> be exte<strong>ns</strong>ible enough so th<strong>at</strong> itcould be used indifferent network visualiz<strong>at</strong>ion situ<strong>at</strong>io<strong>ns</strong>. Under this co<strong>ns</strong>traint nam was designed to read simple anim<strong>at</strong>ionevent comm<strong>and</strong>s from a large trace file. In order to h<strong>and</strong>le large animtion d<strong>at</strong>a sets a minimum amount of inform<strong>at</strong>ion is keptin memory. Event comm<strong>and</strong>s are kept in the file <strong>and</strong> reread from the file whenever necessary.<strong>The</strong> first step to use nam is to produce the trace file. <strong>The</strong> trace file contai<strong>ns</strong> topology inform<strong>at</strong>ion, e.g., nodes, links, as wellas packet traces. <strong>The</strong> detailed form<strong>at</strong> is described in the section 46.1. Usually, the trace file is gener<strong>at</strong>ed by <strong>ns</strong>. During an<strong>ns</strong> simul<strong>at</strong>ion, user can produce topology configur<strong>at</strong>io<strong>ns</strong>, layout inform<strong>at</strong>ion, <strong>and</strong> packet traces using tracing events in <strong>ns</strong>.However any applic<strong>at</strong>ion can gener<strong>at</strong>e a nam trace file.When the trace file is gener<strong>at</strong>ed, it is ready to be anim<strong>at</strong>ed by nam. Upon startup, nam will read the tracefile, cre<strong>at</strong>e topology,pop up a window, do layout if necessary, <strong>and</strong> then pause <strong>at</strong> time 0. Through its user interface, nam provides control over manyaspects of anim<strong>at</strong>ion. <strong>The</strong>se functionalities will be described in detail in the USER INTERFACE section.<strong>The</strong>re are bugs in nam however each successive has become much more stable than the previous one. Please mail <strong>ns</strong>users@isi.eduif you encounter any bugs, or have suggestio<strong>ns</strong> for addiotional desired functionality.45.2 Nam Comm<strong>and</strong> Line Optio<strong>ns</strong>nam [ -g ] [ -t ] [ -i ] [ -j ][ -k ] [ -N ] [ -c ][ -f ] [ -r initial anim<strong>at</strong>ion r<strong>at</strong>e ][ -a ] [ -p ] [ -S ][ ]Comm<strong>and</strong> Line Optio<strong>ns</strong>390


-g Specify geometry of the window upon startup.-t I<strong>ns</strong>truct nam to use tkgraph, <strong>and</strong> specify input file nam for tkgraph.-i [Inform<strong>at</strong>ion for this option may not be accur<strong>at</strong>e] Specify r<strong>at</strong>e (real) milliseconds as the screenupd<strong>at</strong>e r<strong>at</strong>e. <strong>The</strong> default r<strong>at</strong>e i-N Specify the applic<strong>at</strong>ion name of this nam i<strong>ns</strong>tance. This applic<strong>at</strong>ion name may l<strong>at</strong>er be used in peer synchroniz<strong>at</strong>ion.-c <strong>The</strong> maximum size of the cache used to store ’active’ objects when doing anim<strong>at</strong>ing in reverse.-f Name of the initializ<strong>at</strong>ion files to be loaded during startup. In this file, user can define functio<strong>ns</strong> which will be called in the t-a Cre<strong>at</strong>e a separ<strong>at</strong>e i<strong>ns</strong>tance of nam.-p Print out nam trace file form<strong>at</strong>.-S Enable synchronous X behavior so it is easier for graphics debugging. For UNIX system running X only. is the name of the file containing the trace d<strong>at</strong>a to be anim<strong>at</strong>ed. If cannot be read, nam will try to open 45.3 User InterfaceStarting up nam will first cre<strong>at</strong>e the nam co<strong>ns</strong>ole window. You can have multiple anim<strong>at</strong>io<strong>ns</strong> running under the same nami<strong>ns</strong>tance. At the top of all nam windows is a menu bar. For the nam co<strong>ns</strong>ole there are ’File’ <strong>and</strong> ’Help’ menus. Under the’File’ there is a ’New’ comm<strong>and</strong> for cre<strong>at</strong>ing a <strong>ns</strong> topology using the nam editor (under co<strong>ns</strong>truction) , an ’Open’ comm<strong>and</strong>which allows you to open existing tracefiles, a ’WinList’ comm<strong>and</strong> th<strong>at</strong> popup a window will the names of all currentlyopened tracefiles, <strong>and</strong> a ’Quit’ comm<strong>and</strong> which exits nam. <strong>The</strong> ’Help’ menu contai<strong>ns</strong> a very limited popup help screen <strong>and</strong> acomm<strong>and</strong> to show version <strong>and</strong> copyright inform<strong>at</strong>ion.Once a tracefile has been loaded into nam (either by using the ’Open’ menu comm<strong>and</strong> or by specifying the tracefile on thecomm<strong>and</strong> line) an anim<strong>at</strong>ion window will appear. It has a ’Save layout’ comm<strong>and</strong> which will save the current network layoutto a file <strong>and</strong> a ’Print’ comm<strong>and</strong> which will print the current network layout.<strong>The</strong> ’Views’ menu has 4 butto<strong>ns</strong>:• New view button: Cre<strong>at</strong>es a new view of the same anim<strong>at</strong>ion. User can scroll <strong>and</strong> zoom on the newview. All views willbe anim<strong>at</strong>ed synchronously.• Show monitors checkbox: If checked, will show a pane <strong>at</strong> the lower half of window, where moni-tors will be displayed.• Show autolayout checkbox: If checked, will show a pane <strong>at</strong> the lower half of window, which con-tai<strong>ns</strong> input boxes <strong>and</strong>a button for autom<strong>at</strong>ic layout adjustments. This box will not be enabled when using link orientain layouts.• Show annot<strong>at</strong>ion checkbox: If checked, will show a listbox <strong>at</strong> the lower half of window, which will be used to listannot<strong>at</strong>io<strong>ns</strong> in the ascending order of time.Below the menu bar, there is a control bar containing 6 butto<strong>ns</strong>, a label, <strong>and</strong> a small scrollbar(scale). <strong>The</strong>y can be clicked inany order. We will explain them from left to right.• Button 1 («) - Rewind. When clicked, anim<strong>at</strong>ion time will go back <strong>at</strong> the r<strong>at</strong>e of 25 times the current screen upd<strong>at</strong>e r<strong>at</strong>e.• Button 2 () - Forward play. When clicked, anim<strong>at</strong>ion will be played forward with time increasing.• Button 5 (») - Fast Forward. When clicked, anim<strong>at</strong>ion time will go forward <strong>at</strong> the r<strong>at</strong>e of 25 times the current screenupd<strong>at</strong>e r<strong>at</strong>e.391


• Button 6 (Chevron logo) - Close current anim<strong>at</strong>ion window.Time label - Show the current anim<strong>at</strong>ion time (i.e., simul<strong>at</strong>ion time as in the trace file). R<strong>at</strong>e Slider - Controls the screenupd<strong>at</strong>e r<strong>at</strong>e (anim<strong>at</strong>ion granularity). <strong>The</strong> current r<strong>at</strong>e is displayed in the label above the slider.Below the first control bar, there is Main Display, which contai<strong>ns</strong> a tool bar <strong>and</strong> a main view pane with two panning scrollbars. All new views cre<strong>at</strong>ed by menu comm<strong>and</strong> ’Views/New view’ will have these three components. <strong>The</strong> tool bar contai<strong>ns</strong>two zoom butto<strong>ns</strong>. <strong>The</strong> button with an up arrow zooms in, the button with a down arrrow zooms out. <strong>The</strong> two scroll bars areused to pan the main anim<strong>at</strong>ion view.Clicking the left button on any of the objects in the main view pane will pop up a inform<strong>at</strong>ion window. For packet <strong>and</strong> agentobjects, there is a ’monitor’ button in the popup window. Clicking th<strong>at</strong> button will bring out the monitor pane (if it is notalready there), <strong>and</strong> add a monitor to the object. For link objects, there will be a ’Graph’ button. Clicking on th<strong>at</strong> button willbring up another popup window, where users can select between drawing a b<strong>and</strong>width utiliz<strong>at</strong>ion graph or drawing a link lossgraph of one simplex edge of the duplex link.Below the user interface objects we have discussed so far, there may or may not be a Monitor pane, depending on whetherthe checkbox ’Views/Show monitors’ is set. (<strong>The</strong> default is u<strong>ns</strong>et). All monitors will be shown in this pane. A monitor lookslike a big button in the pane. Currently only packets <strong>and</strong> agents may have monitors.A packet monitor shows the size, id, <strong>and</strong> sent time. When the packet reaches its destin<strong>at</strong>ion, the monitor will still be there,but will say th<strong>at</strong> the packet is invisible. An agent monitor shows the name of the agent, <strong>and</strong> if there are any variable tracesassoci<strong>at</strong>ed with this agent, they will be shown there as well.Below the monitor pane (or in its place if the monitor pane isn’t there), there is a Time Slider. It looks likea scaled ruler, witha tag ’TIME’ which can be dragged along the ruler. It is used to set the current anim<strong>at</strong>ion time. As you drag the ’TIME’ tag,current anim<strong>at</strong>ion time will be displayed in the time label in the control bar above. <strong>The</strong> left edge of the slider represents theearliest event time in the trace file <strong>and</strong> the right edge represents the last event time. Clicking left button on the ruler (not onthe tag) has the same effect as Rewind or Fast Forward, depending on the clicking position.<strong>The</strong> Autom<strong>at</strong>ic Layout Pane may be visible or hidden. If visible, it is below the time slider. It has three inputboxes <strong>and</strong> onerelayout button. <strong>The</strong> labeled input boxes let user adjust two autom<strong>at</strong>ic layout co<strong>ns</strong>tants, <strong>and</strong> the number of iter<strong>at</strong>io<strong>ns</strong> duringnext layout. When user press ENTER in any of the input boxes, or click the’relayout’ button, th<strong>at</strong> number of iter<strong>at</strong>io<strong>ns</strong> willbe performed. Refer to the AUTOMATIC LAYOUT section for details of usage.<strong>The</strong> bottom component of the nam window is a Annot<strong>at</strong>ion Listbox, where annot<strong>at</strong>io<strong>ns</strong> are displayed. Anannot<strong>at</strong>ion is a(time, string) pair, which describes a event occuring <strong>at</strong> th<strong>at</strong> time. Refer to <strong>ns</strong>(1) for functio<strong>ns</strong> to gener<strong>at</strong>e annot<strong>at</strong>io<strong>ns</strong>. Doubleclickingon an annot<strong>at</strong>ion in the listbox will bring nam to the time when th<strong>at</strong> annot<strong>at</strong>ion is recorded. When the pointer iswithin the listbox, clicking the right button will stop the anim<strong>at</strong>ion <strong>and</strong> bring up a popup menu with 3 optio<strong>ns</strong>: Add, Delete,Info. ’Add’ will bring up a dialog box with a text input to add a new annot<strong>at</strong>ion entry which has the current anim<strong>at</strong>ion time.<strong>The</strong> user can type an annot<strong>at</strong>ion string in the dialog box. ‘Delete’ will delete the annot<strong>at</strong>ion entry pointed by the pointer.‘Info’ will bring out a pane which shows both the annot<strong>at</strong>ion time <strong>and</strong> the annot<strong>at</strong>ion string.45.4 Keyboard Comm<strong>and</strong>sMost of the butto<strong>ns</strong> have keyboard equivalents. Note they only function when the mouse cursor is i<strong>ns</strong>ide the nam window.• - Typing a will pause nam if it’s not already paused. If nam is paused, will step theanim<strong>at</strong>ion one simul<strong>at</strong>ed clock tick. (If your keyboard autorepe<strong>at</strong>s, holding down is a goodway to slow-stepthrough the anim<strong>at</strong>ion.)392


• ’p’ or ’P’ - Pause but not step if paused.• ’c’ or ’C’ - Continue after a pause.• ’b’ or ’B’ - Decrease anim<strong>at</strong>ion time for one screen upd<strong>at</strong>e interval.• ’r’ or ’R’ - Rewind.• ’f’ or ’F’ - Fast Forward.• ’n’ or ’N’ - Jump to time of next event in the tracefile.• ’x’ or ’X’ - Undo the last r<strong>at</strong>e change.• ’u’ or ’U’ - Undo the last time slider drag.• ’>’ or ‘.’ Increase the granularity (speed up) by 5%.• ’movie.gifPlease note th<strong>at</strong> the programs xwdtoppm, ppmtogif, <strong>and</strong> gifmerge are not part of <strong>ns</strong>. You can get the first two from http://download.sourceforge.net/netpbm/ <strong>and</strong> gifmerge from http://www.the-labs.com/GIFMerge/.45.6 Network LayoutIn nam, a topology is specified by altern<strong>at</strong>ing node objects with edge objects. But to display the topology in a comprehe<strong>ns</strong>ibleway, a layout mechanism is needed. Currently nam provides three layout methods. First, user may specify layout by the link’sorient<strong>at</strong>ion. A link orient<strong>at</strong>ion is the angle between the edge <strong>and</strong> a horizontal line, in the interval [0, 2π]. During layout,nam will honor the given link orient<strong>at</strong>ion. Generally, it will first choose a reference node, then place other nodes using linkorient<strong>at</strong>io<strong>ns</strong> <strong>and</strong> link length. <strong>The</strong> link length is determined by link delay <strong>and</strong> connecting node sizes. This works well for small<strong>and</strong> manually gener<strong>at</strong>ed topologies.393


Second, when dealing with r<strong>and</strong>omly gener<strong>at</strong>ed topologies, we may want to do layout autom<strong>at</strong>ically. An autom<strong>at</strong>ic graphlayout algorithm has been adapted <strong>and</strong> implemented. <strong>The</strong> basic idea of the algorithm is to model the graph as balls (nodes)connected by springs (links). Balls will repulse each other, while springs pull them together. This system will (hopefully)converge after some number of iter<strong>at</strong>io<strong>ns</strong>. In practice, after a small number of iter<strong>at</strong>io<strong>ns</strong> (te<strong>ns</strong> or hundreds), most smallto medium sized graphs will converge to a visually comprehe<strong>ns</strong>ible structure. Larger graphs may take a combin<strong>at</strong>ion ofautom<strong>at</strong>ic layout <strong>and</strong> h<strong>and</strong> placement to achieve an acceptable layout.<strong>The</strong>re are 3 parameters to tune the autom<strong>at</strong>ic layout process: Ca Attractive force co<strong>ns</strong>tant, which controls springs’s forcebetween balls. Cr Repulsive force co<strong>ns</strong>tant, which controls the repulsive force between balls. Number of iter<strong>at</strong>io<strong>ns</strong> Howmany times to run the autolayout procedure.For small topologies with te<strong>ns</strong> of nodes, using the default parameters (perhaps with 20 to 30 more iter<strong>at</strong>io<strong>ns</strong>) will suffice toproduce a nice layout. But for larger topology, careful parameter tuning is necessary. Following is a empirical method tolayout a 100 node r<strong>and</strong>om tra<strong>ns</strong>it stub topologygener<strong>at</strong>ed by Georgia Tech’s ITM internet topology modeler. First, set Ca <strong>and</strong>Cr to 0.2, do about 30 iter<strong>at</strong>io<strong>ns</strong>, then set Cr to 1.0, Ca to about 0.01, then do about 10 iter<strong>at</strong>io<strong>ns</strong>, then set Ca to 0.5, Cr to 1.0,do about 6 iter<strong>at</strong>io<strong>ns</strong>.Third, there is a x,y coordin<strong>at</strong>e style layout. This was developed for use in displaying a wireless topologies in which permanentlinks don’t exist. Using this style, nodes events are given x <strong>and</strong> y coordin<strong>at</strong>e values indic<strong>at</strong>ing where those nodes should beplaced in a cartesian world.45.7 Anim<strong>at</strong>ion ObjectsNam does anim<strong>at</strong>ion using the following building blocks which are defined below:Node Nodes are cre<strong>at</strong>ed from ’n’ trace event in trace file. It represents a source, host, or router. Nam will skip over anyduplic<strong>at</strong>e definitio<strong>ns</strong> for the same node. A node may have three shapes, (circle, square, <strong>and</strong> hexagon), but once cre<strong>at</strong>edit cannot change its shape. Nodes can change its color during anim<strong>at</strong>ion. Nodes can be labeled.Link Links are cre<strong>at</strong>ed between nodes to form a network topology. Internally nam links are co<strong>ns</strong>ist of 2 simplex links. <strong>The</strong>trace event ’l’ cre<strong>at</strong>es two simplex links <strong>and</strong> does other necessary setup. <strong>The</strong>refore, for a users perspective all links areduplex links. Links can be labeled <strong>and</strong> also can change color during the anim<strong>at</strong>ion. Links cab be labeled as well.Queue Queues need to be co<strong>ns</strong>tructed in nam between two nodes. A nam queue is associ<strong>at</strong>ed to only one edge of a duplexlink. Queues are visualized as stacked packets. Packets are stacked along a line, the angle between the line <strong>and</strong> thehorizontal line can be specified in the queue trace event.Packet Packets are visualized as a block with an arrow. <strong>The</strong> direction of the arrow shows the flow direction of the packet.Queued packets are shown as little squares. A packet may be dropped from a queue or a link. Dropped packets areshown as falling rot<strong>at</strong>ing squares, <strong>and</strong> disappear <strong>at</strong> the end of the screen. Unfortun<strong>at</strong>ely, due to nam’s design droppedpackets are not visible during backward anim<strong>at</strong>ion.Agent Agents are used to separ<strong>at</strong>e protocol st<strong>at</strong>es from nodes. <strong>The</strong>y are always associ<strong>at</strong>ed with nodes. An agent has a name,which is a unique identifier of the agent. It is shown as a square with its name i<strong>ns</strong>ide, <strong>and</strong> is drawn next to its associ<strong>at</strong>ednode.394


Chapter 46Nam TraceNam is a Tcl/Tk based anim<strong>at</strong>ion tool th<strong>at</strong> is used to visualize the <strong>ns</strong> simul<strong>at</strong>io<strong>ns</strong> <strong>and</strong> real world packet trace d<strong>at</strong>a. <strong>The</strong> firststep to use nam is to produce a nam trace file. <strong>The</strong> nam trace file should contain topology inform<strong>at</strong>ion like nodes, links,queues, node connectivity etc as well as packet trace inform<strong>at</strong>ion. In this chapter we shall describe the nam trace form<strong>at</strong> <strong>and</strong>simple <strong>ns</strong> comm<strong>and</strong>s/APIs th<strong>at</strong> can be used to produce topology configur<strong>at</strong>io<strong>ns</strong> <strong>and</strong> control anim<strong>at</strong>ion in nam.<strong>The</strong> underlying design co<strong>ns</strong>traints for nam were th<strong>at</strong> it is able to h<strong>and</strong>le large amounts of trace d<strong>at</strong>a <strong>and</strong> th<strong>at</strong> its anim<strong>at</strong>ionprimitives be adaptable so th<strong>at</strong> it may be used in different types of network visualiz<strong>at</strong>ion. As a result, internally nam readsinform<strong>at</strong>ion from a file <strong>and</strong> keeps only a minimum amount of anim<strong>at</strong>ion event inform<strong>at</strong>ion in memory. Its anim<strong>at</strong>ion eventhas a fairly simple <strong>and</strong> co<strong>ns</strong>istent structure so th<strong>at</strong> it can many different visualiz<strong>at</strong>ion situ<strong>at</strong>io<strong>ns</strong>.46.1 Nam Trace Form<strong>at</strong><strong>The</strong> C++ class Trace used for <strong>ns</strong> tracing is used for nam tracing as well. Description of this class may be found under section26.3. <strong>The</strong> method Trace::form<strong>at</strong>() defines nam form<strong>at</strong> used in nam trace files which are used by nam for visualiz<strong>at</strong>ion of <strong>ns</strong>simul<strong>at</strong>io<strong>ns</strong>. Trace class method Trace::form<strong>at</strong>() is described in section 26.4 of chapter 26. If the macro NAM_TRACE hasbeen defined (by default it is defined in trace.h), then the following code is executed as part of the Trace::form<strong>at</strong>() function:if (namChan_ != 0)sprintf(nwrk_,"%c -t "TIME_FORMAT" -s %d -d %d -p %s -e %d -c %d-i %d -a %d -x %s.%s %s.%s %d %s %s",tt,Scheduler::i<strong>ns</strong>tance().clock(),s,d,name,th->size(),iph->flowid(),th->uid(),iph->flowid(),src_nodeaddr,src_portaddr,dst_nodeaddr,395


dst_portaddr,seqno,flags,sname);A nam trace file has a basic form<strong>at</strong> to it. Each line is a nam event. <strong>The</strong> first character on the line defines the type of event <strong>and</strong>is followed by several flags to set optio<strong>ns</strong> on th<strong>at</strong> event. Each event is termin<strong>at</strong>ed by a newline character. -t ...Depending on the event type, there are different flags following the time flag.<strong>The</strong>re are 2 sectio<strong>ns</strong> in th<strong>at</strong> file, st<strong>at</strong>ic intial configur<strong>at</strong>ion events <strong>and</strong> anim<strong>at</strong>ion events. All events with -t * in them areconfigur<strong>at</strong>ion events <strong>and</strong> should be <strong>at</strong> the beginning of the file. One thing to note is th<strong>at</strong> nam can also be fed the trace file froma stream which enables it to be used with realtime applic<strong>at</strong>io<strong>ns</strong>. See the section Using Streams with Realtime Applic<strong>at</strong>io<strong>ns</strong>for more inform<strong>at</strong>ion.Following we describe nam trace file form<strong>at</strong> for different classes events <strong>and</strong> anim<strong>at</strong>ion objects.46.1.1 Initializ<strong>at</strong>ion Events<strong>The</strong> first section of a trace file must contain initializ<strong>at</strong>ion inform<strong>at</strong>ion. All initializ<strong>at</strong>ion events will have the flag -t *. Thistells nam th<strong>at</strong> this event needs to be parsed before any anim<strong>at</strong>ion has started.Version <strong>The</strong> following line define the nam version as required to visualize the given trace:V -t -v -a Normally there is only one version string in a given tracefile, <strong>and</strong> it is usually the first line of the file. An example is thefollowing:V -t * -v 1.0a5 -a 0<strong>The</strong> flag -v 1.0a5 tells nam th<strong>at</strong> this script requires a version of nam > 1.0a5. For more inform<strong>at</strong>ion on this eventlook <strong>at</strong> the file tcl/st<strong>at</strong>s.tcl under the procedure nam_analysis.Wireless If you want to use wireless nodes in nam you need the wireless intializ<strong>at</strong>ion event.W -t * -x 600 -y 600This gives nam the size of the layout for the wireless world. <strong>The</strong> -x value is the width <strong>and</strong> -y is height. For moreinform<strong>at</strong>ion look <strong>at</strong> the file anim<strong>at</strong>or.tcl in the procedure infer-network-model.Hierarchy Hierarchical address inform<strong>at</strong>ion is defined by:A -t -n -o -c -a -h -m -s This trace gives the details of hierarchy, if hierarchical addressing is being used for simul<strong>at</strong>ion. Flag -n indic<strong>at</strong>e the total number of hierarchical tiers, which is 1 for fl<strong>at</strong> addressing, 2 for a 2-level hierarchy etc. Flag -o denotes the total number of bits used for addressing. Flag -h specifiesthe level of the address hierarchy. Flag -m <strong>and</strong> -s describes the address mask <strong>and</strong> the bit shiftof a given level in the address hierarchy, respectively. Here is an example of a trace for topology with 3 level hierachy:396


A -t * -n 3 -p 0 -o 0xffffffff -c 31 -a 1A -t * -h 1 -m 1023 -s 22A -t * -h 2 -m 2047 -s 11A -t * -h 3 -m 2047 -s 0Look <strong>at</strong> tcl/netModel.tcl under the nam_addressing procedure for more inform<strong>at</strong>ion.Color Table Entry A table of color entries can be built using:c -t -i -n Nam allows one to associ<strong>at</strong>e color names with integers. This is very useful in coloring packets. <strong>The</strong> flow id of a packetis used to color the packet using the corresponding color table entry color. Notice the color name should be one of thenames listed in color d<strong>at</strong>abase in X11 (/usr/X11/lib/rgb.txt).In addition to the above node <strong>and</strong> link layout events are also included in the initializ<strong>at</strong>ion section.46.1.2 Nodes<strong>The</strong> nam trace form<strong>at</strong> defining node st<strong>at</strong>e is:n -t -a -s -S -v -c -i -o"n" denotes the node st<strong>at</strong>e.Flags "-t" indic<strong>at</strong>es time <strong>and</strong> "-a" <strong>and</strong> "-s" denotes the node address <strong>and</strong> id."-S" gives the node st<strong>at</strong>e tra<strong>ns</strong>ition. <strong>The</strong> possible st<strong>at</strong>e tra<strong>ns</strong>ition values are:• UP, DOWN indic<strong>at</strong>es node recovery <strong>and</strong> failure.• COLOR indic<strong>at</strong>es node color change. If COLOR is given, a following -c is expected which gives the newcolor value. Also, flag -o is expected so th<strong>at</strong> backtracing can restore the old color of a node.• DLABEL indic<strong>at</strong>es addition of label to node. If DLABEL is given, a following -l -L isexpected th<strong>at</strong> gives the old-label, if any (for backtracing) <strong>and</strong> current label. Shape gives the node shape. <strong>The</strong> color of anode label can be specified via the -i flag."-v" is the shape of the node. <strong>The</strong> possible values are:• circle• box• hexagonAs an example, the linen -t * -a 4 -s 4 -S UP -v circle -c tan -i t<strong>and</strong>efines a node with address <strong>and</strong> id of 4 th<strong>at</strong> has the shape of a circle, <strong>and</strong> color of tan <strong>and</strong> label-color (-i) of tan.46.1.3 Links<strong>The</strong> nam trace for link st<strong>at</strong>es is given by:l -t -s -d -S -c -o orient<strong>at</strong>ion -r -D where <strong>and</strong> indic<strong>at</strong>e the same <strong>at</strong>tributes (<strong>and</strong> the same form<strong>at</strong>) as described above in the node st<strong>at</strong>e traces.Flag -o gives the link orient<strong>at</strong>ion (angle between link <strong>and</strong> the horizon). Valid orient<strong>at</strong>ion values are:397


• up• down• right• left• up-right• down-right• up-left• down-left• angle between 0 <strong>and</strong> 2piFlags -r <strong>and</strong> -D give the b<strong>and</strong>width (in Mb) <strong>and</strong> delay (in ms), respectively. An example of a link trace is:l -t * -s 0 -d 1 -S UP -r 1500000 -D 0.01 -c black -o right46.1.4 Queues<strong>The</strong> nam trace queue st<strong>at</strong>es is given by:q -t -s -d -a Queues are visualized in nam as a straight line along which packets (small squares) are packed. In queue trace events, the flag-a specifies the orient<strong>at</strong>ion of the line of the queue (angle between the queue line <strong>and</strong> the horizontal line, counter-clockwise).For example, the following line specifies a queue th<strong>at</strong> grows vertically upwards with respect to the screen (here 0.5 mea<strong>ns</strong>the angle of the queue line is pi/2):q -t * -s 0 -d 1 -a 0.546.1.5 PacketsWhen a trace line describes a packet, the event type may be + (enqueue), - (dequeue), r (receive), d (drop), or h (hop). -t -e -s -d -c -i is one of:h Hop: <strong>The</strong> packet started to be tra<strong>ns</strong>mitted on the link from to <strong>and</strong> is forwarded to the nexthop.r Receive: <strong>The</strong> packet finished tra<strong>ns</strong>mission <strong>and</strong> started to be received <strong>at</strong> the destin<strong>at</strong>ion.d Drop: <strong>The</strong> packet was dropped from the queue or link from to . Drop here doesn’t distinguishbetween dropping from queue or link. This is decided by the drop time.+ Enter queue: <strong>The</strong> packet entered the queue from to .398


- Leave queue: <strong>The</strong> packet left the queue from to .<strong>The</strong> other flags have the following meaning:-t is the time the event occurred.-s is the origin<strong>at</strong>ing node.-d is the destin<strong>at</strong>ion node.-p is the descriptive name of the type of packet seen. See section 26.5 for the different types of packets supportedin <strong>ns</strong>.-e is the size (in bytes) of the packet.-c is the convers<strong>at</strong>ion id or flow-id of th<strong>at</strong> session.-i is the packet id in the convers<strong>at</strong>ion.-a is the packet <strong>at</strong>tribute, which is currently used as color id.-x is taken from <strong>ns</strong>-traces <strong>and</strong> it gives the source <strong>and</strong> destin<strong>at</strong>ion node <strong>and</strong>port addresses, sequence number, flags (if any) <strong>and</strong> the type of message. For example -x {0.1 -2147483648.0-1 ----- SRM_SESS} denotes an SRM message being sent from node 0 (port 1).Additional flags may be added for some protocols.-P gives an ASCII string specifying a comma separ<strong>at</strong>ed list of packet types. Some values are:TCP A tcp d<strong>at</strong>a packet.ACK Generic acknowledgement.NACK Generic neg<strong>at</strong>ive acknowledgement.SRM SRM d<strong>at</strong>a packet.-n gives the packet sequence number.46.1.6 Node MarkingNode marks are colored concentric circles, boxes, or hexago<strong>ns</strong> around nodes. <strong>The</strong>y are cre<strong>at</strong>ed by:m -t -n -s -c -h -o <strong>and</strong> can be deleted by:m -t -n -s -XNote th<strong>at</strong> once cre<strong>at</strong>ed, a node mark cannot change its shape. <strong>The</strong> possible choices for shapes are, circle, box, <strong>and</strong> hexagon.<strong>The</strong>y are defined as lowercase strings exactly as above. A nam trace showing a node mark is:m -t 4 -s 0 -n m1 -c blue -h circleindic<strong>at</strong>ing node 0 is marked with a blue circle <strong>at</strong> time 4.0. <strong>The</strong> name of the mark is m1.399


46.1.7 Agent TracingAgent trace events are used to visualize protocol st<strong>at</strong>e. <strong>The</strong>y are always associ<strong>at</strong>ed with nodes. An agent event has a name,which is a unique identifier of the agent. An agent is shown as a square with its name i<strong>ns</strong>ide, <strong>and</strong> a line link the square to itsassoci<strong>at</strong>ed nodeAgent events are co<strong>ns</strong>tructed using the following form<strong>at</strong>:a -t -n -s Because in <strong>ns</strong>, agents may be detached from nodes, an agent may be deleted in nam with:a -t -n -s -XFor example, the following nam trace line cre<strong>at</strong>es an agent named srm(5) associ<strong>at</strong>ed with node 5 <strong>at</strong> time 0:a -t 0.00000000000000000 -s 5 -n srm(5)46.1.8 Variable TracingTo visualize st<strong>at</strong>e variables associ<strong>at</strong>ed with a protocol agent, we use fe<strong>at</strong>ure trace events. Currently we allow a fe<strong>at</strong>ure todisplay a simple variable, i.e., a variable with a single value. Notice th<strong>at</strong> the value is simple tre<strong>at</strong>ed as a string (without whitespace). Every fe<strong>at</strong>ure is required to be associ<strong>at</strong>ed with an agent. <strong>The</strong>n, it can be added or modified <strong>at</strong> any time after its agentis cre<strong>at</strong>ed. <strong>The</strong> trace line to cre<strong>at</strong>e a fe<strong>at</strong>ure is:f -t -s -a -T -n -v -o Flag isv for a simple variablel for a lists for a stopped timeru for an up-counting timerd for a down-counting timer.However, only v is implemented in <strong>ns</strong>. Flag -v gives the new value of the variable. Variable values are simpleASCII strings obeying the TCL string quoting conventio<strong>ns</strong>. List values obey the TCL list conventio<strong>ns</strong>. Timer values areASCII numeric. Flag -o gives the previous value of the variable. This is used in backward anim<strong>at</strong>ion.Here is an example of a simple fe<strong>at</strong>ure event:f -t 0.00000000000000000 -s 1 -n C1_ -a srm(1) -v 2.25000 -T vFe<strong>at</strong>ures may be deleted using:f -t -a -n -o -X46.1.9 Executing Tcl Procedures <strong>and</strong> External Code from within Nam<strong>The</strong>re is a special event th<strong>at</strong> can be put in a nam tracefile which allows us to run different tcl procedures. This event isrepresented by event type v.v -t -e 400


This event is very generic, in th<strong>at</strong> it may execute several different procedures <strong>at</strong> a given time, as long as it is in one line(no more than 256 characters). <strong>The</strong>re may be white spaces in the string which are passed as arguments to the tcl procedure.Unlike other events, the order of flags <strong>and</strong> the tcl procedure call is important.Here are some examples of this event in use:Setting playback speedNormally the user chooses a playback r<strong>at</strong>e via the r<strong>at</strong>e slider in the anim<strong>at</strong>ion window. A trace file may set the playback r<strong>at</strong>evia the set_r<strong>at</strong>e_ext comm<strong>and</strong>:v -t -e set_r<strong>at</strong>e_ext For example:v -t 2.5 -e set_r<strong>at</strong>e_ext 20ms 1For comp<strong>at</strong>ibility with earlier versio<strong>ns</strong> of nam, the set_r<strong>at</strong>e comm<strong>and</strong> is also supported. I<strong>ns</strong>tead of specifying the stepsize directly, you use 10 × log 10 . For example:v -t 2.5 -16.9897000433602 1In order to have more readable files, set_r<strong>at</strong>e_ext is preferred.Annot<strong>at</strong>ionThis procedure is used for displaying text annot<strong>at</strong>ion <strong>at</strong> specfic times:v -t -e sim_annot<strong>at</strong>ion For example:v -t 4 -e sim_annot<strong>at</strong>ion 4 3 node 0 added one markThis line calls a special tcl function sim_annot<strong>at</strong>ion in nam, which i<strong>ns</strong>erts the given string node 0 added onemark into nam’s annot<strong>at</strong>ion pane. Look <strong>at</strong> Anim<strong>at</strong>or i<strong>ns</strong>tproc sim_annot<strong>at</strong>ion in tcl/annot<strong>at</strong>ion.tcl for the implement<strong>at</strong>iondetails.Node Exec ButtonIn nam releases, version 1.0a10 <strong>and</strong> l<strong>at</strong>er there is support for running external userdefinable scripts or programs from nam byclicking on a node button.v -t 1.0 -e node_tclscript This line when read in a tracefile will add an extra button to node objects th<strong>at</strong> will execute a tcl script when clicked.For example:401


v -t 1.0 -e node_tclscript 2 "Echo Hello" {puts [exec echo hello]}<strong>The</strong> above line adds a button to node 2’s info window with the label "Echo Hello" <strong>and</strong> when this button is pressed the shellcomm<strong>and</strong> "echo hello" will be run <strong>and</strong> it’s output will be returned to nam <strong>and</strong> then output to the terminal via the tcl procedureputs.<strong>The</strong> functio<strong>ns</strong> th<strong>at</strong> implement the different nam trace form<strong>at</strong>s described above may be found in the following files: <strong>ns</strong>/trace.cc,<strong>ns</strong>/trace.h, <strong>ns</strong>/tcl/lib/<strong>ns</strong>-namsupp.tcl.46.1.10 Using Streams for Realtime Applic<strong>at</strong>io<strong>ns</strong>In addtion to reading from files nam can also read from a stream such as STDIN. Here is a little tutorial on how to send a namtrace stream to nam to make it oper<strong>at</strong>e with real-time d<strong>at</strong>a. First some background on how nam works internally. Basically, itthinks it is reading from a nam tracefile. <strong>The</strong> file has a form<strong>at</strong> to it. Each line is a nam event. <strong>The</strong> first character on the linedefines the type of event <strong>and</strong> is followed by several flags to set optio<strong>ns</strong> on th<strong>at</strong> event. Each event is termin<strong>at</strong>ed by a newlinecharacter. A nam tracefile has 2 sectio<strong>ns</strong>, st<strong>at</strong>ic configur<strong>at</strong>ion events <strong>and</strong> anim<strong>at</strong>ion events. All events with -t * in them areconfigur<strong>at</strong>ion events <strong>and</strong> should be sent to nam in one burst. Lines beginning with a # are comment lines. Currently commentsshould only be place in the anim<strong>at</strong>ion section of the file after the first anim<strong>at</strong>ion event.First of all you need to pipe your d<strong>at</strong>a to nam’s stdin <strong>and</strong> add the ’-’ flag to the nam comm<strong>and</strong>.For example:% c<strong>at</strong> wireless.nam | nam -nam will read the inform<strong>at</strong>ion from stdinFollowing is a short wireless anim<strong>at</strong>ion example. <strong>The</strong> first part of the script has line with -t * which tells nam th<strong>at</strong> these areinitial configur<strong>at</strong>ion inform<strong>at</strong>ion.V -t * -v 1.0a5 -a 0W -t * -x 600 -y 600<strong>The</strong> first 2 lines are used in the nam initializ<strong>at</strong>ion. <strong>The</strong>y need to be the first 2 lines sent to nam from your program. V is theminimum nam version needed to correctly run this script. W mea<strong>ns</strong> this is script contai<strong>ns</strong> wireless nodes which will be withinthe canvas size of width x <strong>and</strong> height y.n -t * -s 0 -x 0.0 -y 0.0 -z 20 -v circle -c black -wn -t * -s 1 -x 0.0 -y 200.0 -z 20 -v box -c black -wNext is the network layout inform<strong>at</strong>ion. <strong>The</strong> first line n cre<strong>at</strong>es a wireless (-w) circular (-v circle) node with id 0 (-s 0) <strong>at</strong>position 0.0,0.0 (-x 0.0 -y 0.0). It’s size (-z) is 20 <strong>and</strong> it’s color (-c) is black. <strong>The</strong> second is a wireless square (-v box) nodewith id 1 (-s 1) <strong>at</strong> 0.0,200.0. Each node has to have a unique id number given by the -s flag.A -t * -n 1 -p 0 -o 0xffffffff -c 31 -a 1A -t * -h 1 -m 2147483647 -s 0402


<strong>The</strong> A event line has to do with setting up hierarchical addressing in nam. It is necessary in wireless nam because packets aretre<strong>at</strong>ed as broadcast to every node.Now we are done with the configur<strong>at</strong>ion part of the nam file. Next are the anim<strong>at</strong>ion events. In order for nam to oper<strong>at</strong>e in aclose to real-time mode it needs to co<strong>ns</strong>tantly receive upd<strong>at</strong>es. As it is playing it will keeps reading lines from the nam trace<strong>and</strong> playing them back. <strong>The</strong> sequence of events must be in chronological order. For example the following lines change thecolor of node 1 from black to green back to black <strong>and</strong> then to black again.n -t 0.0 -s 1 -S COLOR -c green -o blackn -t 0.01 -s 1 -S COLOR -c black -o greenn -t 0.02 -s 1 -S COLOR -c black -o blackNotice th<strong>at</strong> the "-t " flags are always increasing. You cannot issue one event <strong>at</strong> -t 0.2 <strong>and</strong> then another l<strong>at</strong>er on <strong>at</strong> -t0.1. Nam has an internal counter of time <strong>and</strong> it executes an event once it’s time counter passes th<strong>at</strong> event time. It will executeevents in chronological order but only if they are given to it in chronological order. So the following WILL NOT work.n -t 0.0 -s 1 -S COLOR -c black -o blackn -t 0.02 -s 1 -S COLOR -c green -o blackn -t 0.01 -s 1 -S COLOR -c black -o greenSince nam has its own internal represent<strong>at</strong>ion of time which is different than current real world time you have to try <strong>and</strong>synchronize them. <strong>The</strong>re is no explicit <strong>and</strong> totally accur<strong>at</strong>e way to do this but you can have a rough synchroniz<strong>at</strong>ion of timeby having you applic<strong>at</strong>ion periodically send nam events even if nothing has happened. We have cre<strong>at</strong>ed a dummy or "no-op"event (T) for this purpose.T -t 0.5As described above, you MUST feed events to nam in non-decreasing timestamp order. Successive events <strong>at</strong> the same timeare OK. Before anim<strong>at</strong>ing to a given time, nam needs to know th<strong>at</strong> it’s got all the events for th<strong>at</strong> time, <strong>and</strong> so it actually hasto read an event AFTER th<strong>at</strong> time. <strong>The</strong>refore if you’re driving nam from an external process in real-time it will refuse toanim<strong>at</strong>e time t until it sees an event <strong>at</strong> time t+i (for any i > 0). To make nam play out events smoothly, you may therefore needto gener<strong>at</strong>e dummy events with intermedi<strong>at</strong>e timestamps (so th<strong>at</strong> nam knows it can advance). Events of type "T" are dummyevents, so this stream would produce jerky anim<strong>at</strong><strong>at</strong>ion:n -t 1.0 -s 1 -S COLOR -c green -o blackn -t 2.0 -s 1 -S COLOR -c black -o greenn -t 3.0 -s 1 -S COLOR -c black -o blackwhile this would be anim<strong>at</strong><strong>at</strong>ed much smoother:T -t 0.0T -t 0.5n -t 1.0 -s 1 -S COLOR -c green -o blackT -t 1.5n -t 2.0 -s 1 -S COLOR -c black -o greenT -t 2.5n -t 3.0 -s 1 -S COLOR -c black -o blackT -t 3.5T -t 4.0...403


If nam ever gets to the end of an event stream it will block <strong>and</strong> the program will appear as if it has frozen. <strong>The</strong> screen willnot be upd<strong>at</strong>ed until it can read another event so you must be sure to feed events to nam faster than or as fast as it can readthem. This technique works pretty well <strong>and</strong> allows nam to look as if it is running in real-time although in reality there will bea slight delay which is usually acceptable.One other thing to remember is th<strong>at</strong> your applic<strong>at</strong>ion should send these events based on it’s represent<strong>at</strong>ion of time from whenthe applic<strong>at</strong>ion started. Also, when sending events to nam they should be unbuffered so you will want to fflush(stdout); aftereach event.Another event which you can keep sending to nam would be an note which will show a the bottom of the nam window.v -t 0.08 -e sim_annot<strong>at</strong>ion 0.08 1 Time is 0.08v -t 0.09 -e sim_annot<strong>at</strong>ion 0.09 2 Time is 0.09v -t 0.10 -e sim_annot<strong>at</strong>ion 0.08 3 Time is 0.10<strong>The</strong> ’v’ event mea<strong>ns</strong> th<strong>at</strong> you will execute a tcl script <strong>at</strong> time -t, everything after -e is the script to execute. sim_annot<strong>at</strong>ionwrites a note <strong>at</strong> the bottom of the screen. <strong>The</strong> numbers after it are the time to write <strong>and</strong> a unique note id. Notice how Iincremented the note id with each successive note. <strong>The</strong> remaining is wh<strong>at</strong> is written to the screen. For example "Time is 0.08"followed by "Time is 0.09", etc...Th<strong>at</strong> is the basic idea behind making nam work in a real-time fashion. Following are two examples on how to gener<strong>at</strong>ewireless packet anim<strong>at</strong>io<strong>ns</strong> when using nam. To make a wireless broadcast which is shown as quickly exp<strong>and</strong>ing circle youcan use the following.+ -t 0.16 -s 0 -d -1 -p AODV -e 100 -c 2 -a 0 -i 0 -k MAC- -t 0.16 -s 0 -d -1 -p AODV -e 100 -c 2 -a 0 -i 0 -k MACh -t 0.16 -s 0 -d -1 -p AODV -e 100 -c 2 -a 0 -i 0 -k MAC’+’ event puts the packet onto the tra<strong>ns</strong>mission queue ’-’ event remove the packet from the queue <strong>and</strong> makes it ready tobroadcast ’h’ send the packet to the next hop which actually causes the anim<strong>at</strong>ion Here are the meanings of the flags -t time-s tra<strong>ns</strong>mitting node id -d destin<strong>at</strong>ion node id (-1 indic<strong>at</strong>es broadcast to world) -e size of tra<strong>ns</strong>mission -c ultim<strong>at</strong>e destin<strong>at</strong>ionof the packetTo show a packet being send from one particular node to another use the followingr -t 0.255 -s 1 -d -1 -p MAC -e 512 -c 0 -a 0 -i 0 -k MAC+ -t 0.255 -s 1 -d 0 -p AODV -e 512 -c 0 -a 0 -i 0 -k MAC- -t 0.255 -s 1 -d 0 -p AODV -e 512 -c 0 -a 0 -i 0 -k MACh -t 0.255 -s 1 -d 0 -p AODV -e 512 -c 0 -a 0 -i 0 -k MACr -t 0.255 -s 0 -d 1 -p AODV -e 512 -c 0 -a 0 -i 0 -k MACFirst the packet is received (’r’) from the wireless broadcast to node 1. It is then added to the outgoing queue (’+’) on node 1.Next, it is removed from the queue(’-’) <strong>and</strong> ready to be sent to node 0. <strong>The</strong>n the packet is sent to the next hop (’h’) node 0.This will trigger an anim<strong>at</strong>ion of a line the length of the packet size moving from node 1 to node 0. Finally it is received (’r’)by node 0 from node 1.For more nam events you can look <strong>at</strong> the nam section in the <strong>ns</strong> manualAlso, you can save a copy of the trace from a realtime source using the unix ’tee’ comm<strong>and</strong>. For example:404


% c<strong>at</strong> wireless.nam | tee saved_tracefile.nam | nam -Sometimes it is a bug in nam <strong>and</strong> sometimes it is a problem with the way your tracefile is form<strong>at</strong>ted. You may expect nam todo something th<strong>at</strong> it won’t do. Part of the philosophy in the design of nam is th<strong>at</strong> the detail of an anim<strong>at</strong>ion is h<strong>and</strong>led by thetracefile which makes nam more flexible but pushes some of the anim<strong>at</strong>ion complexity on to the programmer gener<strong>at</strong>ing thetracefile.46.1.11 Nam Trace File Form<strong>at</strong> Lookup TableThis is a listing of all possible nam trace event codes <strong>and</strong> the flags associ<strong>at</strong>ed with them. It was taken from the source code inthe file parser.cc. You can gener<strong>at</strong>e your own table by running nam -p.# : comment – this line is ignoredT :n :Dummy event to be used in time synchroniz<strong>at</strong>ion-t timenode-t time-s node id-v shape (circle, box, hexagon)-c color-z size of node-a address-x x loc<strong>at</strong>ion-y y loc<strong>at</strong>ion-i label color-b label-l label-o previous color-S st<strong>at</strong>e (UP, DOWN, COLOR)-L previous label-p label loc<strong>at</strong>ion-P previous label loc<strong>at</strong>ion-i i<strong>ns</strong>ide label color-I previous i<strong>ns</strong>ide label color-e label color-E previous label color-u x velocity-U x velocity-V y velocity-T node stop time-w wireless node405


l :link-t time-s source id-d destin<strong>at</strong>ion id-r tra<strong>ns</strong>mission r<strong>at</strong>e-D delay-h length-O orient<strong>at</strong>ion-b label-c color-o previous color-S st<strong>at</strong>e (UP, DOWN)-l label-L previous label-e label color-E previous label color+ : enqueue packet-t time-s source id-d destin<strong>at</strong>ion id-e extent-a packet color <strong>at</strong>tribute id-i id-l energy-c convers<strong>at</strong>ion-x comment-p packet type-k packet type- : dequeue packet-t time-s source id-d destin<strong>at</strong>ion id-e extent-a <strong>at</strong>tribute-i id-l energy-c convers<strong>at</strong>ion-x comment-p packet type-k packet type406


h :r :d :hop-t time-s source id-d destin<strong>at</strong>ion id-e extent-a <strong>at</strong>tribute-i id-l energy-c convers<strong>at</strong>ion-x comment-p packet type-k packet type-R wireless broadcast radius-D wireless broadcast dur<strong>at</strong>ionreceive-t time-s source id-d destin<strong>at</strong>ion id-e extent-a <strong>at</strong>tribute-i id-l energy-c convers<strong>at</strong>ion-x comment-p packet type-k packet type-R wireless broadcast radius-D wireless broadcast dur<strong>at</strong>iondrop line-t time-s source id-d destin<strong>at</strong>ion id-e extent-a <strong>at</strong>tribute-i id-l energy-c convers<strong>at</strong>ion-x comment-p packet type-k packet type407


E :D :P :a :session enqueue-t time-s source id-d destin<strong>at</strong>ion id-e extent-a <strong>at</strong>tribute-i id-l energy-c convers<strong>at</strong>ion-x comment-p packet type-k packet typesession dequeue-t time-s source id-d destin<strong>at</strong>ion id-e extent-a <strong>at</strong>tribute-i id-l energy-c convers<strong>at</strong>ion-x comment-p packet type-k packet typesession drop-t time-s source id-d destin<strong>at</strong>ion id-e extent-a <strong>at</strong>tribute-i id-l energy-c convers<strong>at</strong>ion-x comment-p packet type-k packet typeagent-t time-s source id-d destin<strong>at</strong>ion id-x remove agent-n agent name408


f :G :L :m :R :fe<strong>at</strong>ure-t time-s source id-d destin<strong>at</strong>ion id-x remove fe<strong>at</strong>ure-T type-n name-a agent-v value-o previous valuegroup-t time-n name-i node id-a group id-x remove from grouplan link-t time-s source id-d destin<strong>at</strong>ion id-o orient<strong>at</strong>ion-O orient<strong>at</strong>ionmark node-t time-n name-s node id-c color-h shape (circle, square, hexagon)-X remove markrouting event-t time-s source id-d destin<strong>at</strong>ion id-g multicast group-p packet source id or *-n neg<strong>at</strong>ive cache-x this route timed out-T timeout-m mode (iif or oif)409


v :V :N :W :g :A :c :q :execute tcl expression-t time-e tcl scriptset trace file version-t time-v time-a timeuse nam graphwireless range-t time-x X-y Yenergy st<strong>at</strong>us – for future use-t timehierarchical address space configur<strong>at</strong>ion – initiliz<strong>at</strong>ion only-t time-n hierarchy-p port shift-o port mask-c mulitcast shift-a multicast mask-h hierarchy-m node shift-s node maskcolor table configur<strong>at</strong>ion – initializ<strong>at</strong>ion only-t time-i id-n colorcre<strong>at</strong>e packet queue – initializ<strong>at</strong>ion only-t time-s source id-d destin<strong>at</strong>ion id-a orientaion410


X :layout lan-t time-n name-r r<strong>at</strong>e-D delay-o orient<strong>at</strong>ion-O orient<strong>at</strong>ion46.2 Ns comm<strong>and</strong>s for cre<strong>at</strong>ing <strong>and</strong> controlling nam anim<strong>at</strong>io<strong>ns</strong>This section describes different APIs in <strong>ns</strong>th<strong>at</strong> may be used to manipul<strong>at</strong>e nam anim<strong>at</strong>io<strong>ns</strong> for objects like nodes, links, queues<strong>and</strong> agents. <strong>The</strong> implement<strong>at</strong>ion of most of these APIs is contained in <strong>ns</strong>/tcl/lib/<strong>ns</strong>-namsupp.tcl. Demo<strong>ns</strong>tr<strong>at</strong>ion of nam APIsmay be found in <strong>ns</strong>/tcl/ex/nam-example.tcl.46.2.1 NodeNodes are cre<strong>at</strong>ed from the ”n” trace event in trace file. Each node represents a host or a router. Nam termin<strong>at</strong>es if thereare duplic<strong>at</strong>e definitio<strong>ns</strong> of the same node. Attributes specific to node are color, shape, label, label-color, position of label<strong>and</strong> adding/deleting mark on the node. Each node can have 3 shapes: circle (default), square, or hexagon. But once cre<strong>at</strong>ed,the shape of a node cannot be changed during the simul<strong>at</strong>ion. Different node may have different colors, <strong>and</strong> its color maybe changed during anim<strong>at</strong>ion. <strong>The</strong> following OTcl procedures are used to set node <strong>at</strong>tributes, they are methods of the classNode:$node color [color] ;# sets color of node$node shape [shape] ;# sets shape of node$node label [label] ;# sets label on node$node label-color [lcolor] ;# sets color of label$node label-<strong>at</strong> [ldirection] ;# sets position of label$node add-mark [name] [color] [shape] ;# adds a mark to node$node delete-mark [name] ;# deletes mark from node46.2.2 Link/QueueLinks are cre<strong>at</strong>ed between nodes to form a network topology. namlinks are internally simplex, but it is invisible to the users.<strong>The</strong> trace event ”l” cre<strong>at</strong>es two simplex links <strong>and</strong> other necessary setups, hence it looks to users identical to a duplex link.Link may have many colors <strong>and</strong> it can change its color during anim<strong>at</strong>ion. Queues are co<strong>ns</strong>tructed in nam between two nodes.Unlike link, nam queue is associ<strong>at</strong>ed to a simplex link. <strong>The</strong> trace event “q” only cre<strong>at</strong>es a queue for a simplex link. In nam,queues are visualized as stacked packets. Packets are stacked along a line, <strong>and</strong> the angle between the line <strong>and</strong> the horizontalline can be specified in the trace event “q”. Comm<strong>and</strong>s to setup different anim<strong>at</strong>ion <strong>at</strong>tributes of a link are as follows:$<strong>ns</strong> duplex-link-op <strong>The</strong> may be one of the following: orient, color, queuePos, label. Orient or the link orient<strong>at</strong>ion defines the anglebetween the link <strong>and</strong> horizontal. <strong>The</strong> optional orient<strong>at</strong>ion values may be difined in degrees or by text like right (0), right-up(45), right-down (-45), left (180), left-up (135), left-down (-135), up (90), down (-90). <strong>The</strong> queuePos or position of queue isdefined as the angle of the queue line with horizontal. Examples for each <strong>at</strong>tribute are given as following :411


$<strong>ns</strong> duplex-link-op orient right$<strong>ns</strong> duplex-link-op color "green"$<strong>ns</strong> duplex-link-op queuePos 0.5$<strong>ns</strong> duplex-link-op label "A";# orient<strong>at</strong>ion is set as right. <strong>The</strong> order;# in which links are cre<strong>at</strong>ed in nam;# depends on calling order of this function.46.2.3 Agent <strong>and</strong> Fe<strong>at</strong>uresAgents are used to separ<strong>at</strong>e protocol st<strong>at</strong>es from nodes. <strong>The</strong>y are always associ<strong>at</strong>ed with nodes. An agent has a name, whichis a unique identifier of the agent. It is shown as a square with its name i<strong>ns</strong>ide, <strong>and</strong> a line link the square to its associ<strong>at</strong>ednode. <strong>The</strong> following are comm<strong>and</strong>s th<strong>at</strong> support agent tracing:$<strong>ns</strong> add-agent-trace $<strong>ns</strong> delete-agent-trace $<strong>ns</strong> monitor-agent-trace Once the above comm<strong>and</strong> is used to cre<strong>at</strong>e an agent in nam trace, the tracevar method of the <strong>ns</strong>agent can be used to cre<strong>at</strong>efe<strong>at</strong>ure traces of a given variable in the agent. For example, the following code segment cre<strong>at</strong>es traces of the variable C1_ inan SRM agent $srm(0):$<strong>ns</strong> <strong>at</strong>tach-agent $n($i) $srm(0)$<strong>ns</strong> add-agent-trace $srm($i) srm(0)$<strong>ns</strong> monitor-agent-trace $srm(0) ;# turn nam monitor on from the start$srm(0) tracevar C1_46.2.4 Some Generic Comm<strong>and</strong>s$<strong>ns</strong> color defines color index for nam. Once specified, color-id can be used in place of the colorname in nam traces.$<strong>ns</strong> trace-annot<strong>at</strong>e i<strong>ns</strong>erts an annot<strong>at</strong>ion in nam. Notice th<strong>at</strong> if contai<strong>ns</strong> whitespaces, it must be quoted using the double quote. An example of this would be $<strong>ns</strong> <strong>at</strong> $time ”$<strong>ns</strong> trace-annot<strong>at</strong>e”Event A happened”” This annot<strong>at</strong>ion appears in the nam window <strong>and</strong> is used to control playing of nam by events.$<strong>ns</strong> set-anim<strong>at</strong>ion-r<strong>at</strong>e causes nam to set the anim<strong>at</strong>ion playout r<strong>at</strong>e to the given timestep value.Time is in seconds, with optional prefixes (for example, 1 is 1 second, or 2ms is 0.002 seconds).412


Part XOther413


Chapter 47Educ<strong>at</strong>ional use of NS <strong>and</strong> NAMThis chapter is about using <strong>ns</strong><strong>and</strong> nam for educ<strong>at</strong>ional purpose. <strong>ns</strong>is a discrete event simul<strong>at</strong>or <strong>and</strong> supports various flavorsof TCP, many different models of unicast <strong>and</strong> multicast routing, alongwith different multicast protocols. It supports mobilenetworking including local <strong>and</strong> s<strong>at</strong>ellite networks. It also supports applic<strong>at</strong>io<strong>ns</strong> like web caching. And <strong>ns</strong>uses nam, ananim<strong>at</strong>ion tool, developed in Tcl/Tk, to visualize the simul<strong>at</strong>ion packet traces which is cre<strong>at</strong>ed by running <strong>ns</strong>scripts. Thus<strong>ns</strong><strong>and</strong> nam could be used together to easily demo<strong>ns</strong>tr<strong>at</strong>e different networking issues in a classroom environment. In thischapter we’ll talk mostly about an educ<strong>at</strong>ional scripts’ d<strong>at</strong>abase th<strong>at</strong> we have developed. We’ll also talk about how to use namto run namtrace files.47.1 Using NS for educ<strong>at</strong>ional purposesWe have developed a web-based interface specifically to c<strong>at</strong>er to the above mentioned educ<strong>at</strong>ional need of using <strong>ns</strong>in theclassrooms. This web-interface is serviced by a d<strong>at</strong>abase of <strong>ns</strong> scripts th<strong>at</strong> could be used for classroom demo<strong>ns</strong>tr<strong>at</strong>io<strong>ns</strong> <strong>and</strong>/orother educ<strong>at</strong>ional purposes. It can be found <strong>at</strong> http://www.isi.edu/<strong>ns</strong>nam/script_inv. This page also serves as an interface foruploading or submitting similar scripts to the inventory. So even though we currently have only a few scripts in the inventoryto start with, we hope th<strong>at</strong> the inventory will eventually grow in size with script contributio<strong>ns</strong> from all of you. In the followingparagraphs we shall talk more about this educ<strong>at</strong>ional scripts’ index webpage.47.1.1 I<strong>ns</strong>talling/building/running <strong>ns</strong>In order to run the educ<strong>at</strong>ional scripts mentioned in the previous section, you would need to have a running version of <strong>ns</strong>in yourmachine. <strong>The</strong> homepage for <strong>ns</strong>is loc<strong>at</strong>ed <strong>at</strong> http://www.isi.edu/<strong>ns</strong>nam/<strong>ns</strong>. See <strong>ns</strong>-build page <strong>at</strong> http://www.isi.edu/<strong>ns</strong>nam/<strong>ns</strong>/<strong>ns</strong>build.htmlfor downloading <strong>and</strong> building <strong>ns</strong>in your machine. If you want to know about using <strong>ns</strong>to write/run scripts, visit<strong>ns</strong>tutorial for beginners <strong>at</strong> http://www.isi.edu/<strong>ns</strong>nam/<strong>ns</strong>/tutorial/index.html.47.1.2 <strong>The</strong> educ<strong>at</strong>ional scripts’ inventory page:<strong>The</strong> educ<strong>at</strong>ional script inventory page is loc<strong>at</strong>ed <strong>at</strong> http://www.isi.edu/<strong>ns</strong>nam/script_inv. It may be used either to search,browse <strong>and</strong> download one or more simul<strong>at</strong>ion scripts (<strong>and</strong>/or rel<strong>at</strong>ed files like the namtrace, scree<strong>ns</strong>hot, webpage describingwh<strong>at</strong>ever is being demo<strong>ns</strong>tr<strong>at</strong>ed through the simul<strong>at</strong>ion) from the inventory or to submit simul<strong>at</strong>ion scripts to the inventory.We discuss both the optio<strong>ns</strong> in the following paragraphs:414


SEARCH/VIEW/DOWNLOAD NS SCRIPTS: You could search the d<strong>at</strong>abase using keywords by going to the “Searchd<strong>at</strong>abase” page. You could also browse through the entire d<strong>at</strong>abase by going to the “View d<strong>at</strong>abase” page. <strong>The</strong> searchfunction is very basic <strong>at</strong> the present <strong>and</strong> we hope to extend it as the d<strong>at</strong>abase begi<strong>ns</strong> to grow in size. Each script entryin the d<strong>at</strong>abase has the following inform<strong>at</strong>ion:Name of the scriptName of the author, author’s email-id <strong>and</strong> webpage(if provided)Description of wh<strong>at</strong> the simul<strong>at</strong>ion does.<strong>ns</strong>version required to run the scriptAny other comments about script <strong>and</strong><strong>The</strong> c<strong>at</strong>egory of the script Currently we have c<strong>at</strong>egories of Applic<strong>at</strong>ion, Tra<strong>ns</strong>port (TCP <strong>and</strong> others), Routing (unicast<strong>and</strong> multicast), Multicast protocols, Queue management, Wireless <strong>and</strong> Others (to include any other c<strong>at</strong>egory).Other rel<strong>at</strong>ed files At the right h<strong>and</strong> down corner of each entry there might be links to a NamTracefile, a scree<strong>ns</strong>hot<strong>and</strong> a webpage for the simul<strong>at</strong>ion script, if these files/inform<strong>at</strong>ion have been submitted by the author along withthe script.In order to download any script or any of the rel<strong>at</strong>ed files, simply left-click on the filename <strong>and</strong> a download dialog boxwill appear where you can provide the p<strong>at</strong>h to download the file to.SUBMIT NS SCRIPTS TO INVENTORY: Incase you have simul<strong>at</strong>ion scripts suitable for classroom demo<strong>ns</strong>tr<strong>at</strong>io<strong>ns</strong>, youcould submit them to the inventory. You have to ATLEAST submit the following in order to successfully upload yourscript:Name of authorAuthor’s E-mailidName of script (<strong>and</strong> p<strong>at</strong>h to the loc<strong>at</strong>ion of your script) to contributeBrief description of scriptVersion of NS script usesC<strong>at</strong>egory for the scriptYou may OPTIONALLY provide the following along with the above required fields:Author’s WebPageNamtrace file (namdump for your script simul<strong>at</strong>ion)Scree<strong>ns</strong>hot (an image of your nam screen)Webpage (pointer to webpage you may have for the script)Other comments, if anyImportant: We suggest th<strong>at</strong> you provide the namtracefile alongwith your script since many users might want to use thenamtrace only, for visualiz<strong>at</strong>ion, <strong>and</strong> download script only when they want to make any changes to the simul<strong>at</strong>ion.47.2 Using NAM for educ<strong>at</strong>ional purposesInorder to visualize an <strong>ns</strong> simul<strong>at</strong>ion, you need to have the NAM tool i<strong>ns</strong>talled. You could either simply download the nambinary for your pl<strong>at</strong>form or download the nam distribution <strong>and</strong> build in your machine. <strong>The</strong> link for getting nam binaries aswell as nam source is http://www.isi.edu/<strong>ns</strong>nam/nam which also happe<strong>ns</strong> to be the nam homepage.Steps to use nam in powerpoint: After opening powerpoint, go to “Slide Show” (visible on the top menu) <strong>and</strong> click on “actionbutto<strong>ns</strong>”. Select the type of button you prefer. This would cre<strong>at</strong>e a button for your slide. Clicking on your button will popup an “Action Setting" window. I<strong>ns</strong>ide the window, there is a place called “Run Program” where you can define your namprogram to run.415


Bibliography[1] C. Alaettinoğlu, A.U. Shankar, K. Dussa-Zeiger, <strong>and</strong> I. M<strong>at</strong>ta. Design <strong>and</strong> implement<strong>at</strong>ion of MaRS: A routing testbed.Internetworking: Research <strong>and</strong> Experience, 5:17–41, 1994.[2] S<strong>and</strong>eep Bajaj, Lee Breslau, Deborah Estrin, Kevin Fall, Sally Floyd, Padma Haldar, Mark H<strong>and</strong>ley, Ahmed Helmy,John Heidemann, Polly Huang, S<strong>at</strong>ish Kumar, Steven McCanne, Reza Rejaie, Puneet Sharma, Kannan Varadhan, Ya Xu,Haobo Yu, <strong>and</strong> Daniel Zappala. Improving simul<strong>at</strong>ion for network research. Technical Report 99-702b, University ofSouthern California, March 1999. (revised September 1999).[3] Paul Barford <strong>and</strong> Mark Crovella. Gener<strong>at</strong>ing represent<strong>at</strong>ive web workloads for network <strong>and</strong> server peformance evalu<strong>at</strong>ion.In Proceedings of the ACM SIGMETRICS, pages 151–160, June 1998.[4] L.S. Brakmo, S. O’Malley, <strong>and</strong> L.L. Peterson. TCP vegas: New techniques for congestion detection <strong>and</strong> avoidance. InProceedings of the ACM SIGCOMM, pages 24–35, October 1994.[5] L.S. Brakmo, S. O’Malley, <strong>and</strong> L.L. Peterson. TCP vegas: New techniques for congestion detection <strong>and</strong> avoidance.Technical Report TR 94 04, Department of Computer Science, <strong>The</strong> University of Arizona, Tucson, AZ 85721, February1994.[6] R. Brown. Calendar queues: A fast O(1) priority queue implement<strong>at</strong>ion for the simul<strong>at</strong>ion event set problem. Communic<strong>at</strong>io<strong>ns</strong>of the ACM, 31(10):1220–1227, October 1988.[7] Pei Cao <strong>and</strong> Chengjie Liu. Maintaining strong cache co<strong>ns</strong>istency in the World-Wide Web. In Proceedings of the IEEEICDCS, pages 12–21, May 1997.[8] N. Christin, J. Liebeherr, <strong>and</strong> T. Abdelzaher. A quantit<strong>at</strong>ive assured forwarding service. In Proceedings of IEEEINFOCOM 2002, volume 2, pages 864–873, New York, NY, June 2002.[9] S. Deering, D. Estrin, D. Farinacci, V. Jacobson, Ching-Gung Liu, <strong>and</strong> L. Wei. An architecture for wise-area multicastrouting. Technical Report USC-SC-94-565, Computer Science Department, University of Southern California, LosAngeles, CA 90089., 1994.[10] Anja Feldmann, Anna C. Gilbert, Polly Huang, <strong>and</strong> Walter Willinger. Dynamics of IP traffic: A study of the role ofvariability <strong>and</strong> the impact of control. pages 301–313, Cambridge, MA, USA, August 1999.[11] S. Floyd, V. Jacobson, C. Liu, S. McCanne, <strong>and</strong> L. Zhang. A reliable multicast framework for light-weight sessio<strong>ns</strong> <strong>and</strong>applic<strong>at</strong>ion level framing. In Proceedings of the ACM SIGCOMM, pages 342–356, August 1995.[12] H. T. Friis. A note on a simple tra<strong>ns</strong>mission formula. Proc. IRE, 34, 1946.[13] H. W. Hethcote. <strong>The</strong> m<strong>at</strong>hem<strong>at</strong>ics of infectious diseases. SIAM Review, 42(4):599–653, October 2000.[14] A. Heybey. Netsim <strong>Manual</strong>. MIT, 1989.[15] R. Jain. <strong>The</strong> Art of Computer Systems Performance Analysis. John Wiley <strong>and</strong> So<strong>ns</strong>, Inc., 1996.[16] Pierre L’Ecuyer. Good parameters <strong>and</strong> implement<strong>at</strong>io<strong>ns</strong> for combined multiple recursive r<strong>and</strong>om number gener<strong>at</strong>ors.Oper<strong>at</strong>io<strong>ns</strong> Research, 47(1):159–164, 1999.416


[17] Pierre L’Ecuyer. Software for uniform r<strong>and</strong>om number gener<strong>at</strong>ion: Distinguishing the good <strong>and</strong> the bad. In Proceedingsof the 2001 Winter Simul<strong>at</strong>ion Conference, pages 95–105, December 2001.[18] Pierre L’Ecuyer, Richard Simard, E. Jack Chen, <strong>and</strong> W. David Kelton. An object-oriented r<strong>and</strong>om number package withmany long streams <strong>and</strong> substreams. Oper<strong>at</strong>io<strong>ns</strong> Research, 2001.[19] A. Legout <strong>and</strong> E.W. Biersack. PLM: Fast convergence for cumul<strong>at</strong>ive layered multicast tra<strong>ns</strong>mission schemes. InProceedings of the ACM SIGMETRICS, Santa Clara, CA, U.S.A., June 2000.[20] J. Liebeherr <strong>and</strong> N. Christin. JoBS: Joint buffer management <strong>and</strong> scheduling for differenti<strong>at</strong>ed services. In Proceedingsof IWQoS 2001, pages 404–418, Karlsruhe, Germany, June 2001.[21] J. Liebeherr <strong>and</strong> N. Christin. R<strong>at</strong>e alloc<strong>at</strong>ion <strong>and</strong> buffer management for differenti<strong>at</strong>ed services. Computer Networks,40(1):89–110, September 2002.[22] M. M<strong>at</strong>his <strong>and</strong> J. Mahdavi. Forward acknowledgement: Refining TCP congestion control. In Proceedings of the ACMSIGCOMM, August 1996.[23] M. M<strong>at</strong>his, J. Mahdavi, S. Floyd, <strong>and</strong> A. Romanov. TCP Selective Acknowledgement Optio<strong>ns</strong>, RFC 2018 edition, 1996.[24] S. McCanne <strong>and</strong> S. Floyd. <strong>ns</strong>—Network Simul<strong>at</strong>or. http://www-mash.cs.berkeley.edu/<strong>ns</strong>/.[25] S. McCanne <strong>and</strong> V. Jacobson. <strong>The</strong> bsd packet filter: A new architecture for user-level packet capture. pages 259–269,January 1993.[26] John Ousterhout. Scripting: Higher-level programming for the 21st century. IEEE Computer, 31(3):23–30, March 1998.[27] S.K. Park <strong>and</strong> R.W. Miller. R<strong>and</strong>om number gener<strong>at</strong>ion: Good ones are hard to find. Communic<strong>at</strong>io<strong>ns</strong> of the ACM,31(10):1192–1201, October 1988.[28] Peter Pieda, Jeremy Ethridge, M<strong>and</strong>eep Baines, <strong>and</strong> Farhan Shallwani. A Network Simul<strong>at</strong>or, Differenti<strong>at</strong>ed ServicesImplement<strong>at</strong>ion. Open IP, Nortel Networks, 2000.[29] T. S. Rappaport. Wireless communic<strong>at</strong>io<strong>ns</strong>, principles <strong>and</strong> practice. Prentice Hall, 1996.[30] D. Waitzman, C. Partridge, <strong>and</strong> S.E. Deering. Distance Vector Multicast Routing Protocol, RFC 1075 edition, 1988.417

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!