Ns 3 Tutorial Slides
Ns 3 Tutorial Slides
Acknowledgments
Thanks to Mathieu Lacage and Craig Dowell for assembling the tutorial source code and materials Thanks to ns-3 development team! Tom Henderson is supported by NSF CNS-0551686 (University of Washington)
Goals of this tutorial Learn about the ns-3 project and its goals Understand the software architecture, conventions, and basic usage of ns-3 Read and modify an example ns-3 script Learn how you might extend ns-3 to conduct your own research Provide feedback to the ns-3 development team
ns-3 tutorial March 2008 3
Assumptions Some familiarity with C++ programming language Some familiarity with Unix Network Programming (e.g., sockets) Some familiarity with discrete-event simulators
Outline
Introduction to ns-3 Reading ns-3 code Tweaking ns-3 code Extending ns-3 code
ns-3 features
open source licensing (GNU GPLv2) and development model Python scripts or C++ programs alignment with real systems (sockets, device driver interfaces) alignment with input/output standards (pcap traces, ns-2 mobility scripts) testbed integration is a priority modular, documented core
ns-3 models
ns-3 people
NSF PIs: Tom Henderson, Sumit Roy (University of Washington), George Riley (Georgia Tech.), Sally Floyd (ICIR) Associated Team: INRIA Sophia Antipolis, ` Planete group Walid Dabbous, Mathieu Lacage (software lead) Developers: Raj Bhattacharjea, Gustavo Carneiro, Craig Dowell, Joseph Kopena, Emmanuelle Laprise
ns-3 tutorial March 2008 9
11
12
14
Resources
Web site:
http://www.nsnam.org
Mailing list:
http://mailman.isi.edu/mailman/listinfo/ns-developers
Tutorial:
http://www.nsnam.org/docs/tutorial/tutorial.html
Code server:
http://code.nsnam.org
Wiki:
http://www.nsnam.org/wiki/index.php/Main_Page
ns-3 tutorial March 2008 15
Links to materials
Today's code
http://www.nsnam.org/tutorials/simutools08/ns -3-tutorial.tar.gz3-tutorial.tar.gz
Tutorial slides:
PPT: http://www.nsnam.org/tutorials/simutools08/ns -3-tutorial.ppt3-tutorial.ppt PDF: http://www.nsnam.org/tutorials/simutools08/ns -3-tutorial.pdf ns-3 tutorial March 2008 16
Questions so far?
17
Outline
Introduction to ns-3 Reading ns-3 code Tweaking ns-3 code Extending ns-3 code
18
Reading ns-3 code Browsing the source code Conceptual overview Script walkthrough
19
Basics
ns-3 is written in C++ Bindings in Python ns-3 uses the waf build system i.e., instead of ./configure;make, type ./waf simulation programs are C++ executables (python scripts)
20
examples ns3
samples src
tutorial utils
waf waf.bat
wscript
21
22
the waf build system Waf is a Python-based framework for configuring, compiling and installing applications.
It is a replacement for other tools such as Autotools, Scons, CMake or Ant http://code.google.com/p/waf/
Application Application
Protocol stack
Node NetDevice NetDevice
Packet(s)
Protocol stack
25
Fundamentals Key objects in the simulator are Nodes, Packets, and Channels
NodescontainApplications,stacks,and NetDevices
26
Node basics A Node is a husk of a computer to which applications, stacks, and NICs are added
Application Application Application
DTN
27
NetDevices and Channels NetDevices are strongly bound to Channels of a matching type
WifiChannel
WifiNetDevice
Node basics Two key abstractions are maintained: 1) applications use an (asynchronous, for now) sockets API 2) the boundary between IP and layer 2 mimics the boundary at the deviceindependent sublayer in Linux
i.e., Linux Packet Sockets
29
ns-3 Packets each network packet contains a byte buffer, a list of tags, and metadata
buffer: bit-by-bit (serialized) representation of headers and trailers tags: set of arbitrary, user-provided data structures (e.g., per-packet cross-layer messages, or flow identifiers) metadata: describes types of headers and and trailers that have been serialized
optional-- disabled by default
ns-3 tutorial March 2008 30
ns-3 Packets to add a new header, subclass from Header, and write your Serialize() and Deserialize() methods
how bits get written to/from the Buffer
Similar for Packet Tags Packet Buffer implements a (transparent) copy-on-write implementation
31
public:
void SetDestination (uint16_t port); ... void Serialize (Buffer::Iterator start) const;
Simulation basics Simulation time moves discretely from event to event C++ functions schedule events to occur at specific simulation times A simulation scheduler orders the event execution Simulation::Run() gets it all started Simulation stops at specific time or when events end
ns-3 tutorial March 2008 34
CSMA (LAN)
WiFi (Infrastructure )
WiFi (Infrastructure )
Hierarchical mobility 1) AdHoc movement in backbone 2) Local movement relative to Access Point
35
36
def main(): ## Set up some default values for the simulation. Use the Bind() ## technique to tell the system what subclass of Queue to use, ## and what the queue limit is ## The below Bind command tells the queue factory which class to ## instantiate, when the queue factory is invoked in the topology code ns.DefaultValue.Bind("Queue", "DropTailQueue") ns.DefaultValue.Bind("OnOffApplicationPacketSize", "210") ns.DefaultValue.Bind("OnOffApplicationDataRate", "448kb/s") ns.CommandLine.Parse(sys.argv) ## Here, we will explicitly create four nodes. In more sophisticated ## topologies, we could configure a node factory. n0 = n1 = n2 = n3 = ... ns.InternetNode() ns.InternetNode() ns.InternetNode() ns.InternetNode()
37
examples/ directory
examples/ contains other scripts with similar themes
$ ls csma-broadcast.cc csma-multicast.cc csma-one-subnet.cc csma-packet-socket.cc mixed-global-routing.cc simple-alternate-routing.cc simple-error-model.cc simple-global-routing.cc simple-point-to-point-olsr.cc simple-point-to-point.cc tcp-large-transfer-errors.cc tcp-large-transfer.cc tcp-nonlistening-server.cc tcp-small-transfer-oneloss.cc tcp-small-transfer.cc udp-echo.cc waf wscript
38
Outline
Introduction to ns-3 Reading ns-3 code Tweaking ns-3 code Extending ns-3 code
39
41
42
Object aggregation is planned to be the main way to create new Node types (rather than subclassing Node)
ns-3 tutorial March 2008 44
{
Ptr<MobilityModel> senderMobility = 0; Ptr<MobilityModel> receiverMobility = 0; ... senderMobility = sender->GetNode ()-> GetObject<MobilityModel> ();
46
The attribute system provides a more convenient API to the user to do these things
ns-3 tutorial March 2008 48
49
Attribute
ns-3 tutorial March 2008
Value
52
Users can get Ptrs to instances also, and Ptrs to trace sources, in the same way
ns-3 tutorial March 2008 53
CreateObject<> ();
CreateObject<> is a wrapper for operator new. ns3::Object objects must be created on the heap using CreateObject<> (), which returns a smart pointer; e.g.
Ptr<Node> rxNode = CreateObject<Node> ();
54
Create<> ();
What is Create<> ()? Create<> provides some smart pointer help for objects that use ns3::Ptr<> but that do not inherit from Object. Principally, class ns3::Packet
Ptr<Packet> p = Create<Packet> (data,size);
55
Non-default constructors
The attribute system allows you to also pass them through the CreateObject<> constructor. This provides a generic non-default constructor for users (any combination of parameters), e.g.:
Ptr<WifiPhy> phy = CreateObject<WifiPhy> ( TxGain, Double (1.0));
56
57
58
Also part of Object: smart pointers ns-3 uses reference-counting smart pointers at its APIs to limit memory leaks
Orpassbyvalueorpassbyreferenceto constwhereappropriate
Asmartpointerbehaveslikeanormal pointer (syntax) but does not lose memory when reference count goes to zero Use them like built-in pointers:
Ptr<MyClass> p = CreateObject<MyClass> (); p->method ();
ns-3 tutorial March 2008 59
ns3::Object
Attribute namespace
60
Tracing model
Tracing is a structured form of simulation output
tracing format should be relatively static across simulator releases
Crude tracing
#include <iostream> ... int main () { ... std::cout << "The value of x is " << x << std::endl; ... }
ns-3 tutorial March 2008 62
63
64
65
configurable by user
66
Tracing overview
Simulator provides a set of pre-configured trace sources
Users may edit the core to add their own
68
Highest-level of tracing
Highest-level: Use built-in trace sources and sinks and hook a trace file to them
// Also configure some tcpdump traces; each interface will be traced // The output files will be named // simple-point-to-point.pcap-<nodeId>-<interfaceId> // and can be read by the "tcpdump -r" command (use "-tt" option to
69
Mid-level of tracing
Mid-level: Customize trace source/sink behavior using the tracing namespace
void PcapTrace::TraceAllIp (void) { NodeList::Connect ("/nodes/*/ipv4/(tx|rx)",
70
71
Lowest-level of tracing
Low-level: Add trace sources to the tracing namespace
Config::Connect ("/NodeList/.../Source", MakeCallback (&ConfigTest::ChangeNotification, this));
72
Statistics
Avoid large trace files Full statistics support planned for later in 2008 Reuse tracing framework One similar approach: ns-2-measure project
http://info.iet.unipi.it/~cng/ns2measure/ StaticStatobjectthatcollectssamplesofvariables based on explicit function calls inserted into the code Graphical front end, and framework for replicating simulation runs
73
CSMA (LAN)
WiFi (Infrastructure )
WiFi (Infrastructure )
Hierarchical mobility 1) AdHoc movement in backbone 2) Local movement relative to Access Point
74
75
The Helper approach Is not generic Does not try to allow code reuse Provides simple 'syntactical sugar' to make simulation scripts look nicer and easier to read for network researchers Each function applies a single operation on a''setofsameobjects
76
Helper Objects
NodeContainer: vector of Ptr<Node> NetDeviceContainer: vector of Ptr<NetDevice> InternetStackHelper WifiHelper MobilityHelper OlsrHelper ... Each model provides a helper class
77
setup backbone
NodeContainer backbone; backbone.Create (20); MobilityHelper mobility; mobility.SetPositionAllocator (GridPositionAllocator, MinX, Double (-100), ...); mobility.SetMobilityModel (RandomDirectionMobilityModel) mobility.Layout (backbone
WifiHelper wifi;
wifi.SetMac (AdhocWifiMac); wifi.SetPhy (WifiPhy, TxGain, Double (10)); wifi.SetRemoteStationManager (ConstantRateWifiManager, DataMode, String (wifia-54mb)) Ptr<WifiChannel> channel = ...; NetDeviceContainer backboneDev = wifi.Build (backbone, channel);
78
mobility.Layout (subnet);
subnet.Add (backbone.Get (i)); Ptr<WifiChannel> subnetChannel = ...; NetDeviceContainer subnetDev =
79
80
81
82
83
Frameworks
Observation: Many of the operations executed by the helper class are repetitively executed, in slightly different ways
// // // // // Create Nodes Add NetDevice and Channel Add Protocol Stack Add Applications Add Mobility
ns-3 tutorial March 2008 84
Frameworks
Idea: Can we write the same flow of operations once, but delegate them to a Manager? The Manager implements the functions The functions are virtual Users wishing to specialize them can override them as needed
ns-3 tutorial March 2008 85
Frameworks
This design pattern is called Inversion Of Control This provides more reusable scenario/topology scripts than ones based on the Helper classes walk through mixed-wireless-topology.cc and src/topology/
ns-3 tutorial March 2008 86
Outline
Introduction to ns-3 Reading ns-3 code Tweaking ns-3 code Extending ns-3 code
87
88
Aside: C++ templates templates allow a programmer to write one version of code that is applicable over multiple types templates are declared, defined and used Declaration:
template <typename T> T Add (T first, T second); T Add (T first, T second);
89
{
return first + second; }
Usage:
int x, y, z; z = Add<int> (x, y);
90
Definition:
template <typename T> void MyStack<T>::Push (T data) { ... }
Usage:
MyStack<int> stack; stack.Push (x); y = stack.Pop ();
ns-3 tutorial March 2008 91
92
ns-3 callbacks
Class template Callback<> implements the functor design pattern Callbacks are like function pointers, but more type-safe
static double CbOne (double a, double b) {} ^ | | | ^ ---| | ^ ------|
94
95
2) API review
Provide sample header file for API review gather feedback from the ns-developers list
97
98
6) Plumb into other modules, if needed 7) Post for review on developers list 8) Resolve comments and merge
100
101
Validation
Can you trust ns-3 simulations?
Can you trust any simulation? Onus is on the researcher to verify results
ns-3 strategies:
Open source benefits Validation of models on testbeds Reuse of code Unit tests Event driven validation tests
ns-3 tutorial March 2008 102
real machine
ns-3 ns-3
virtual machine
ns-3
virtual machine
real machine
real machine
Testbed
Summary
ns-3 is an emerging simulator to replace ns-2 Consider ns-3 if you are interested in:
Open source and collaboration More faithful representations of real computers and the Internet Integration with testbeds A powerful low-level API Python scripting
105
106
Resources
Web site:
http://www.nsnam.org
Mailing list:
http://mailman.isi.edu/mailman/listinfo/ns-developers
Tutorial:
http://www.nsnam.org/docs/tutorial/tutorial.html
Code server:
http://code.nsnam.org
Wiki:
http://www.nsnam.org/wiki/index.php/Main_Page
ns-3 tutorial March 2008 107