SlideShare a Scribd company logo
1 of 107
Download to read offline
ns-3 tutorial



Presenter: Tom Henderson
  University of Washington

   Simutools Conference
       March, 2008




      ns-3 tutorial March 2008   1
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)


                ns-3 tutorial March 2008      2
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



               ns-3 tutorial March 2008   4
Outline

•   Introduction to ns-3
•   Reading ns-3 code
•   Tweaking ns-3 code
•   Extending ns-3 code




                  ns-3 tutorial March 2008   5
What is ns (or ns-2)?

• ns is a discrete-event network simulator for
  Internet systems
   – protocol design, multiple levels of abstraction
   – written in multiple languages (C++/OTcl)
• ns has a companion network animator
  called nam
   – hence, has been called the nsnam project

  ns-3 is a research-oriented, discrete event simulator

                        ns-3 tutorial March 2008          6
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 tutorial March 2008       7
ns-3 models




 Project focus has been on the software core, to date

                      ns-3 tutorial March 2008          8
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
ns-3 relationship to ns-2
ns-3 is not an extension of ns-2
• does not have an OTcl API
   – C++ wrapped by Python
• synthesis of yans, ns-2, GTNetS simulators, and
  new software
   – example ns-2 models so far: random
     variables, error models, OLSR
• guts of simulator are completely replaced
• new visualizers are in works


                  ns-3 tutorial March 2008     10
ns-3 status (March 2008)
ns-3 is in a pre-alpha state
• monthly development releases
• APIs being finalized
• emphasis has been on setting the architecture
• new users should expect rough edges
• many opportunities to work on the core models




                  ns-3 tutorial March 2008        11
ns-3 status (March 2008)

What others are already using ns-3 for:
• wifi-based simulations of OLSR and other
  MANET routing
• MANET routing (SMF and unicast protocols)
• OntoNet: Scalable Knowledge Based
  Networking" by Joe Kopena and Boon Thau Loo
  (UPenn)



                 ns-3 tutorial March 2008   12
ns-3 roadmap (2008)
near term (through June)
• finalize and release simulation core
  (April/May)
   – core APIs
• ns-3.1 complete release (June timeframe)
   – add Internet and Device models
   – add validation framework
   – some higher-level topology/scenario
     APIs
                ns-3 tutorial March 2008   13
ns-3 roadmap (2008)
 planned for later this year
• emulation modes
• statistics
• support for real code
• additional ns-2 porting/integration
• distributed simulation
• visualization



                 ns-3 tutorial March 2008   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-tu
    3-tutorial.tar.gz
• Tutorial slides:
  – PPT:
    http://www.nsnam.org/tutorials/simutools08/ns-3-tu
    3-tutorial.ppt
  – PDF:
    http://www.nsnam.org/tutorials/simutools08/ns
    -3-tutorial.pdf ns-3 tutorial March 2008    16
Questions so far?




  ns-3 tutorial March 2008   17
Outline

•   Introduction to ns-3
•   Reading ns-3 code
•   Tweaking ns-3 code
•   Extending ns-3 code




                  ns-3 tutorial March 2008   18
Reading ns-3 code

• Browsing the source code
• Conceptual overview
• Script walkthrough




                ns-3 tutorial March 2008   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)


                   ns-3 tutorial March 2008     20
Browse the source

 tomh@A3803721 ~/home/ns-3-dev
 $ ls
 AUTHORS README          VERSION   examples   samples   tutorial   waf       wscript
 LICENSE RELEASE_NOTES doc         ns3        src       utils      waf.bat




Pause presentation to browse source code
http://www.nsnam.org/tutorials/simutools08/ns-3-tutorial.tar.gz




                                   ns-3 tutorial March 2008                            21
Doxygen documentation

• Most of the ns-3 API is documented with
  Doxygen
  – http://www.stack.nl/~dimitri/doxygen/


Pause presentation to browse Doxygen
http://www.nsnam.org/doxygen/index.html



                  ns-3 tutorial March 2008   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/

    Pause presentation to build with waf

                  ns-3 tutorial March 2008        23
waf key concepts

• For those familiar with autotools:
• configure -> ./waf -d [optimized|debug] configure
• make -> ./waf
• make test -> ./waf check (run unit tests)


• Can run programs through a special waf
  shell; e.g.
   – ./waf --run simple-point-to-point
   – (this gets the library paths right for you)
                     ns-3 tutorial March 2008         24
The basic model

   Application                                        Application
 Application                                        Application
                 Sockets-like
                 API

  Protocol                                           Protocol
                  Packet(s)                           stack
   stack


Node                                               Node

   NetDevice                                          NetDevice
 NetDevice                      Channel             NetDevice
                          Channel



                        ns-3 tutorial March 2008                25
Fundamentals

Key objects in the simulator are Nodes,
 Packets, and Channels

Nodes contain Applications, “stacks”, and
 NetDevices




                ns-3 tutorial March 2008    26
Node basics

A Node is a husk of a computer to which
 applications, stacks, and NICs are added

                           Application
                                  Application
                                           Application



                                                  “DTN”



               ns-3 tutorial March 2008                   27
NetDevices and Channels

NetDevices are strongly bound to Channels
 of a matching type

               WifiChannel




                                            WifiNetDevice



Nodes are architected for multiple interfaces
                 ns-3 tutorial March 2008                   28
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 device-
  independent sublayer in Linux
  i.e., Linux Packet Sockets



                 ns-3 tutorial March 2008   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


                   ns-3 tutorial March 2008   31
example: UDP header
class UdpHeader : public Header
{
public:
    void SetDestination (uint16_t port);
    ...
    void Serialize (Buffer::Iterator start) const;
    uint32_t Deserialize (Buffer::Iterator start);
private:
    uint16_t m_sourcePort;
    uint16_t m_destinationPort;
    uint16_t m_payloadSize;
    uint16_t m_initialChecksum;
}
                      ns-3 tutorial March 2008       32
example: UDP header
void
UdpHeader::Serialize (Buffer::Iterator start) const
{
    Buffer::Iterator i = start;
    i.WriteHtonU16 (m_sourcePort);
    i.WriteHtonU16 (m_destinationPort);
    i.WriteHtonU16 (m_payloadSize + GetSerializedSize ());
    i.WriteU16 (0);
    if (m_calcChecksum)
     {
       uint16_t checksum = Ipv4ChecksumCalculate (...);
       i.WriteU16 (checksum);
     }
}
                          ns-3 tutorial March 2008           33
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
Sample script walkthrough

              WiFi (AdHoc network)
              Backbone


CSMA (LAN)

                                                      Hierarchical
                                                      mobility
         WiFi                           WiFi          1) AdHoc
         (Infra-                        (Infra-       movement in
         structure                      structure     backbone
         )                              )             2) Local
                                                      movement
                                                      relative to Access
                                                      Point
                     Applications: UDP flow,
                     Routing: OLSR on backbone

                           ns-3 tutorial March 2008                   35
Sample script walkthrough


Walk through mixed-wireless.cc




               ns-3 tutorial March 2008   36
(aside) similar looking code in Python

import sys
import ns3 as ns


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 =   ns.InternetNode()
n1 =   ns.InternetNode()
n2 =   ns.InternetNode()
n3 =   ns.InternetNode()
...

                                 ns-3 tutorial March 2008                37
examples/ directory

• examples/ contains other scripts with similar themes
$ ls
csma-broadcast.cc                 simple-point-to-point.cc
csma-multicast.cc                 tcp-large-transfer-errors.cc
csma-one-subnet.cc                tcp-large-transfer.cc
csma-packet-socket.cc             tcp-nonlistening-server.cc
mixed-global-routing.cc           tcp-small-transfer-oneloss.cc
simple-alternate-routing.cc       tcp-small-transfer.cc
simple-error-model.cc             udp-echo.cc
simple-global-routing.cc          waf
simple-point-to-point-olsr.cc     wscript




                          ns-3 tutorial March 2008                38
Outline

•   Introduction to ns-3
•   Reading ns-3 code
•   Tweaking ns-3 code
•   Extending ns-3 code




                  ns-3 tutorial March 2008   39
ns-3 logging
• ns-3 has a built-in logging facility to stderr
• Features:
  – can be driven from shell environment
    variables
  – Multiple log levels like syslog
  – Function and call argument tracing
• Intended for debugging, but can be
  abused to provide tracing
  – we do not guarantee that format is unchanging

                  ns-3 tutorial March 2008         40
ns-3 logging example

•   NS_LOG_UNCOND();
•   NS_LOG environment variable
•   per-source-file logging
•   log levels
•   example scripts




                 ns-3 tutorial March 2008   41
attributes and tracing

• Next, we would like to talk about attributes
  (default values, settable and gettable
  values) and tracing
• To understand this, we'll introduce the ns-
  3 Object system




                 ns-3 tutorial March 2008    42
Object metadata system

• ns-3 is, at heart, a C++ object system
• ns-3 objects that inherit from base class
  ns3::Object get several additional features
  – dynamic run-time object aggregation
  – an attribute system
  – smart-pointer memory management

    Disclaimer: This is not all main-line ns-3 code-- parts are in
          a proposal in the mathieu/ns-3-param repository

                          ns-3 tutorial March 2008                   43
Object aggregation use case

• You can aggregate objects to one another
  at run-time
  – Avoids the need to modify a base class to
    provide pointers to all possible connected
    objects
• Object aggregation is planned to be the
  main way to create new Node types
  (rather than subclassing Node)

                  ns-3 tutorial March 2008       44
Object aggregation example

void
WifiChannel::Send (Ptr<WifiPhy> sender, Ptr<const
  Packet> packet, ...)
{
    Ptr<MobilityModel> senderMobility = 0;
    Ptr<MobilityModel> receiverMobility = 0;
    ...
    senderMobility = sender->GetNode ()->
     GetObject<MobilityModel> ();


                                         class Node does not need to know
}                                        about MobilityModel
                      ns-3 tutorial March 2008                        45
Use cases for attributes

• An Attribute represents a value in our
  system
• An Attribute can be connected to an
  underlying variable or function
  – e.g. TcpSocket::m_cwnd;
  – or a trace source




                 ns-3 tutorial March 2008   46
Use cases for attributes (cont.)

• What would users like to do?
  – Know what are all the attributes that affect the
    simulation at run time
  – Set a default initial value for a variable
  – Set or get the current value of a variable
  – Initialize the value of a variable when a
    constructor is called
• The attribute system is a unified way of
  handling these functions
                   ns-3 tutorial March 2008        47
How to handle attributes

• The traditional C++ way:
  – export attributes as part of a class's public API
  – walk pointer chains (and iterators, when
    needed) to find what you need
  – use static variables for defaults
• The attribute system provides a more
  convenient API to the user to do these
  things

                   ns-3 tutorial March 2008        48
The traditional C++ way
class Foo
{
public:
  void SetVar1 (uint32_t value);
  uint32_t GetVar1 (void);
  static void SetInitialVar1(uint32_t value);
  void SetVar2 (uint32_t value);
  uint32_t GetVar2 (void);
  static void SetInitialVar2(uint32_t value);
  ...
private:
  uint32_t m_var1; // document var1
  uint32_t m_var2; // document var2
  static uint32_t m_initial_var1;
  static uint32_t m_initial_var2;
}

Foo::Foo() : m_var1(Foo::m_initial_var1), m_var2(Foo::m_initial_var2)
{
}

to modify an instance of Foo, get the pointer somehow, and use the public accessor functions
to modify the default values, modify the statics
Default values may be available in a separate framework (e.g. ns-2 Bind())


                                           ns-3 tutorial March 2008                            49
Navigating the attributes

• Attributes are exported into a string-based
  namespace, with filesystem-like paths
  – namespace supports regular expressions
• Attributes also can be used without the
  paths
  – e.g. “WifiPhy::TxGain”
• A Config class allows users to manipulate
  the attributes
                 ns-3 tutorial March 2008     50
Navigating the attributes using paths

• Examples:
  – Nodes with NodeIds 1, 3, 4, 5, 8, 9, 10, 11:
     “/NodeList/[3-5]|[8-11]|1”
  – UdpL4Protocol object instance aggregated to
    matching nodes:
     “/$UdpL4Protocol”
  – EndPoints which match the SrcPort=1025
    specification:
     “/EndPoints/*:SrcPort=1025”

                     ns-3 tutorial March 2008      51
What users will do

• e.g.: Set a default initial value for a
  variable
• (Note: this replaces DefaultValue::Bind())
  Config::Set (“WifiPhy::TxGain”, Double (1.0));
• Syntax also supports string values:
  Config::Set (“WifiPhy::TxGain”, “1.0”);


                        Attribute           Value

                 ns-3 tutorial March 2008           52
What users will see

• Set or get the current value of a variable
  – Here, one needs the path in the namespace to
    the right instance of the object
  Config::SetAttribute(“/NodeList/5/DeviceList/3/Phy
    /TxGain”, Double(1.0));
  Double d =
    Config::GetAttribute(“/NodeList/5/NetDevice/3/Phy
    /TxGain”);

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




                    ns-3 tutorial March 2008   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);




                 ns-3 tutorial March 2008    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));



                    ns-3 tutorial March 2008   56
How is all this implemented (overview)
class Foo P public Object
{
public:
  static TypeId GetTypeId (void);
private:
  uint32_t m_var1; // document var1
  uint32_t m_var2; // document var2
}

Foo::Foo() {
}

TypeId Foo::GetTypeId (void)
{
  static TypeId tid = TypeId(“Foo”);
  .SetParent (<ooParent>
  .SetGroupName (“FooDefaults”)
  .AddConstructor<Foo> ();
  .AddAttribute (“m_var1”, “document var1”,
    UInteger(3),
    MakeUIntegerAccessor (&Foo::m_var1),
    MakeUIntegerChecker<uint32_t> ())
  .AddAttribute (“m_var2”, “”, ...)
  return tid;
}




                                       ns-3 tutorial March 2008   57
A real TypeId example
TypeId
RandomWalk2dMobilityModel::GetTypeId (void)
{
  static TypeId tid = TypeId ("RandomWalkMobilityModel")
    .SetParent<MobilityModel> ()
    .SetGroupName ("Mobility")
    .AddConstructor<RandomWalk2dMobilityModel> ()
    .AddAttribute ("bounds",
                   "Bounds of the area to cruise.",
                   Rectangle (0.0, 0.0, 100.0, 100.0),
                   MakeRectangleAccessor (&RandomWalk2dMobilityModel::m_bounds),
                   MakeRectangleChecker ())
    .AddAttribute ("time",
                   "Change current direction and speed after moving for this delay.",
                   Seconds (1.0),
                   MakeTimeAccessor (&RandomWalk2dMobilityModel::m_modeTime),
                   MakeTimeChecker ())
    .AddAttribute ("distance",
                   "Change current direction and speed after moving for this distance.",
                   Seconds (1.0),
                   MakeTimeAccessor (&RandomWalk2dMobilityModel::m_modeTime),
                   MakeTimeChecker ())




                                 ns-3 tutorial March 2008                             58
Also part of Object: smart pointers

• ns-3 uses reference-counting smart
  pointers at its APIs to limit memory leaks
   – Or “pass by value” or “pass by reference to
     const” where appropriate
• A “smart pointer” behaves like a normal
  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
Statements you should understand now

  Ptr<Ipv4AddressAllocator> ipAddrs = CreateObject<Ipv4AddressAllocator> ();




C++ Smart Pointer                          ns3::Object

 Config::SetDefault (“OnOffApplication::DataRate”, String(“448kb/s”));

 Config::SetDefault (“/NodeList/*/DeviceList/*/Phy/TxGain”, Double(10.0));




                     Attribute namespace




                             ns-3 tutorial March 2008                        60
Tracing model

• Tracing is a structured form of simulation output
   – tracing format should be relatively static across simulator
     releases
• Example (from ns-2):
+ 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 610
r 1.84471 2 1 cbr 210 ------- 1 3.0 1.0 195 600
r 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
• Needs vary widely

                          ns-3 tutorial March 2008                 61
Crude tracing

#include <iostream>
...
int main ()
{
  ...
  std::cout << "The value of x is " << x <<
  std::endl;
  ...
}

                ns-3 tutorial March 2008   62
slightly less crude

#include <iostream>
...
int main ()
{
  ...
  NS_LOG_UNCOND ("The value of x is " << x);
  ...
}


                ns-3 tutorial March 2008   63
Simple ns-3 tracing

• these are wrapper functions/classes
• see examples/mixed-wireless.cc
#include "ns3/ascii-trace.h"



 AsciiTrace asciitrace ("mixed-wireless.tr");
 asciitrace.TraceAllQueues ();
 asciitrace.TraceAllNetDeviceRx ();




                   ns-3 tutorial March 2008     64
Simple ns-3 tracing (pcap version)

• these are wrapper functions/classes
• see examples/mixed-wireless.cc
#include "ns3/pcap-trace.h"



 PcapTrace pcaptrace ("mixed-wireless.pcap");
 pcaptrace.TraceAllIp ();




                   ns-3 tutorial March 2008     65
ns-3 tracing model (revisit)

• Fundamental #1: decouple trace sources
  from trace sinks
• Fundamental #2: prefer standard trace
  outputs for built-in traces
                   Trace source

   Trace source
                                                  Trace sink


                  Trace source
                                                   configurable by
 unchanging                                        user

                       ns-3 tutorial March 2008                      66
Tracing overview

• Simulator provides a set of pre-configured
  trace sources
  – Users may edit the core to add their own
• Users provide trace sinks and attach to the
  trace source
  – Simulator core provides a few examples for
    common cases
• Multiple trace sources can connect to a
  trace sink
                  ns-3 tutorial March 2008       67
Multiple levels of tracing

• Highest-level: Use built-in trace sources
  and sinks and hook a trace file to them
• Mid-level: Customize trace source/sink
  behavior using the tracing namespace
• Low-level: Add trace sources to the
  tracing namespace
  – Or expose trace source explicitly


                  ns-3 tutorial March 2008    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
 // display timestamps correctly)
 PcapTrace pcaptrace ("simple-point-to-point.pcap");
 pcaptrace.TraceAllIp ();




                            ns-3 tutorial March 2008                    69
Mid-level of tracing

• Mid-level: Customize trace source/sink
  behavior using the tracing namespace
void                                          Regular expression editing
PcapTrace::TraceAllIp (void)
{
    NodeList::Connect ("/nodes/*/ipv4/(tx|rx)",
                      MakeCallback (&PcapTrace::LogIp, this));
}
                                   Hook in a different trace sink




                               ns-3 tutorial March 2008                    70
Asciitrace: under the hood

void
AsciiTrace::TraceAllQueues (void)
{
    Packet::EnableMetadata ();
    NodeList::Connect ("/nodes/*/devices/*/queue/enqueue",
                        MakeCallback (&AsciiTrace::LogDevQueueEnqueue, this));
    NodeList::Connect ("/nodes/*/devices/*/queue/dequeue",
                        MakeCallback (&AsciiTrace::LogDevQueueDequeue, this));
    NodeList::Connect ("/nodes/*/devices/*/queue/drop",
                        MakeCallback (&AsciiTrace::LogDevQueueDrop, this));
}




                                  ns-3 tutorial March 2008                       71
Lowest-level of tracing

• Low-level: Add trace sources to the
  tracing namespace

 Config::Connect ("/NodeList/.../Source",
                 MakeCallback (&ConfigTest::ChangeNotification, this));




                           ns-3 tutorial March 2008                       72
Statistics                        Disclaimer: not yet part of ns-3


•   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/
    – Static “Stat” object that collects samples of variables
      based on explicit function calls inserted into the code
    – Graphical front end, and framework for replicating
      simulation runs


                        ns-3 tutorial March 2008                     73
Revisit our script

              WiFi (AdHoc network)
              Backbone


CSMA (LAN)

                                                       Hierarchical
                                                       mobility
         WiFi                            WiFi          1) AdHoc
         (Infra-                         (Infra-       movement in
         structure                       structure     backbone
         )                               )             2) Local
                                                       movement
                                                       relative to Access
                                                       Point
                     Applications: TCP flow,
                     Routing: OLSR routing

                            ns-3 tutorial March 2008                   74
Design patterns for topology scripts

Design approaches
• Use simple helper functions with attributes
• Use reusable “frameworks”



   Note: This area of our API is under discussion; feedback wanted




                         ns-3 tutorial March 2008                    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 ''set of same objects”


                ns-3 tutorial March 2008   76
Helper Objects

•   NodeContainer: vector of Ptr<Node>
•   NetDeviceContainer: vector of Ptr<NetDevice>
•   InternetStackHelper
•   WifiHelper
•   MobilityHelper
•   OlsrHelper
•   ... Each model provides a helper class


                    ns-3 tutorial March 2008       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);


                            ns-3 tutorial March 2008               78
setup wifi subnets
for (uint32_t I = 0; I < 20; i++)
   NodeContainer subnet;
   subnet.Create (29);
   subnets.push_back (subnet);
   mobility.PushReferenceModel (backbone.Get (i));
   mobility.SetMobilityModel (...)
   mobility.SetPositionAllocator (...);
   mobility.Layout (subnet);
   subnet.Add (backbone.Get (i));
   Ptr<WifiChannel> subnetChannel = ...;
   NetDeviceContainer subnetDev =
     wifi.Build (subnet, subnetChannel);
   subnetDevs.push_back (subnetDev);



                           ns-3 tutorial March 2008   79
setup ip over backbone and subnets
IpNetworkAddressAllocator network;
network.SetMask (“192.168.0..0”, “255.255.0.0”);
InternetStackHelper ip;
ip.SetAddressAllocator (network.GetNext ());
ip.Setup (backboneDev);
for (uint32_t I = 0; I < 20; i++)
   NetDeviceContainer subnetDev = subnetDevs[i];
   ip.SetAddressAllocator (network.GetNext ());
   ip.Setup (subnetDev);




                           ns-3 tutorial March 2008   80
setup olsr on backbone

OlsrHelper olsr;
olsr.Enable (backbone);




                   ns-3 tutorial March 2008   81
setup traffic sinks everywhere

TrafficSinkHelper sink;
// listen on port 1026 for protocol udp
sink.EnableUdp (1026);
sink.Setup (NodeList::Begin (), NodeList::End ());




                          ns-3 tutorial March 2008   82
setup trace sources
OnOffApplicationHelper source;
source.SetUdpDestination (“168.192.4.10”, 1026);
NodeContainer one = subnets[2].Get ();
source.Setup (one);




                         ns-3 tutorial March 2008   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




                  ns-3 tutorial March 2008   87
How do simulator objects fit together?

• ns-3 objects are C++ objects
  – can be subclassed
• ns-3 Objects support aggregation

   ns-3 models are composed of hooking C++ classes together
     in the traditional way, and also with object aggregation




                       ns-3 tutorial March 2008                 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);

• might eventually become
• int Add (int first, int second);


                   ns-3 tutorial March 2008          89
Aside: C++ templates

• Definition:
 template <typename T>
 T Add (T first, T second)
 {
     return first + second;
 }

• Usage:
 int x, y, z;
 z = Add<int> (x, y);



                    ns-3 tutorial March 2008   90
Classes may also be templatized

• Declaration:
 template <typename T>
 class MyStack
 {
    void Push (T data);
    T Pop (void);
 };

• 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
Scheduler and callbacks

• Let’s look at samples/main-simulator.cc
• Schedules a single event, then exits

int main (int argc, char *argv[])
{
  MyModel model;

    Simulator::Schedule (Seconds (10.0), &random_function, &model);

    Simulator::Run ();

    Simulator::Destroy ();
}


                             ns-3 tutorial March 2008                 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) {}
           ^                ^                  ^
           |         ---|            ------|
           |         |               |
Callback<double, double, double> one;
• Bind a function with a matching signature to a callback
one = MakeCallback (&CbOne);
double returnOne = one (10.0, 20.0);

                         ns-3 tutorial March 2008           93
Path of a packet (send)
                  Note: This architecture is under additional work




               ns-3 tutorial March 2008                       94
Path of a packet (receive)




               ns-3 tutorial March 2008   95
current ns-3 routing model

classes Ipv4RoutingProtocol, Ipv4Route
• Each routing protocol maintains its own
  RIB --> no common FIB
• Routing protocols are registered with
  AddRoutingProtocol (Ptr<> protocol,
   int16_t priority)
• Routes are looked up by querying each
  protocol for a route
  – Ipv4L3Protocol::Lookup()
                ns-3 tutorial March 2008    96
Writing new ns-3 models

1) Define your requirements
  – reusability
  – dependencies
  – functionality
2) API review
  – Provide sample header file for API review
  – gather feedback from the ns-developers list


                    ns-3 tutorial March 2008      97
Writing new ns-3 models

3) Create a non-functional skeleton
  – review coding style
  – decide which compilation unit it resides in
  – add to waf
  – build with body ifdeffed out
  – copyright and headers
  – initial doxygen


                  ns-3 tutorial March 2008        98
Writing new ns-3 models

4) Build a skeleton
  – header include guards
  – namespace ns3
  – constructor, empty function prototypes
  – key variables
  – Object/TypeId code
  – write small test program
  – start a unit test

                  ns-3 tutorial March 2008   99
Writing new ns-3 models

5) Build core functions and unit tests
  – use of logging, and asserts
6) Plumb into other modules, if needed
7) Post for review on developers list
8) Resolve comments and merge




                  ns-3 tutorial March 2008   100
Porting from ns-2

• Objects can be ported from ns-2 (or other
  simulators)
• Make sure licensing is compatible
• Example:
  – ns-2: queue/errmodel.{cc,h}
  – ns-3: src/common/error-model.{cc,h}



                 ns-3 tutorial March 2008   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
Walk through examples (time permitting)

• Beyond simple simulation scenarios
• Add a new type of MAC+PHY:
• subclass a NetDevice and a Channel
• Add new types of transport layers:
• subclass Node and Socket
• subclass Ipv4 class to implement per-node Ipv4 forwarding table
  and Ipv4
• interface configuration
• for example, the Linux TCP stack could be easily integrated into a
  new type of node, LinuxNode with a LinuxTcpSocket
• Add a new type of traffic generation and analysis:
• subclass Application
                            ns-3 tutorial March 2008                   103
• • use Socket API
ns-3 goals for emulation


real machine

                                              ns-3                 ns-3


   virtual                virtual            real                  real
  machine                machine            machine               machine
               ns-3



                                                        Testbed




1) ns-3 interconnects virtual              2) testbeds interconnect ns-3
   machines                                   stacks

                           ns-3 tutorial March 2008                         104
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
• ns-3 needs you!



                     ns-3 tutorial March 2008            105
Proposed Google Summer of Code
projects
•   Performance Evaluation and Optimization
•   Linux Kernel Network Stack Integration
•   Parallel Simulations
•   GUI Development
•   Real World Code Integration




                 ns-3 tutorial March 2008   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

More Related Content

What's hot

Introduction to Network Function Virtualization (NFV)
Introduction to Network Function Virtualization (NFV)Introduction to Network Function Virtualization (NFV)
Introduction to Network Function Virtualization (NFV)rjain51
 
Troubleshooting Network and Network Utilities
Troubleshooting Network and Network UtilitiesTroubleshooting Network and Network Utilities
Troubleshooting Network and Network UtilitiesRubal Sagwal
 
ngn overview , next generation network
ngn overview , next generation networkngn overview , next generation network
ngn overview , next generation networkTushar Kumar
 
Wired and Wireless Examples in ns2
Wired and Wireless Examples in ns2Wired and Wireless Examples in ns2
Wired and Wireless Examples in ns2Pradeep Kumar TS
 
5G Network Architecture Options
5G Network Architecture Options5G Network Architecture Options
5G Network Architecture Options3G4G
 
SNMP(Simple Network Management Protocol)
SNMP(Simple Network Management Protocol)SNMP(Simple Network Management Protocol)
SNMP(Simple Network Management Protocol)Mohammad Awais Javaid
 
Network Monitoring System
Network Monitoring SystemNetwork Monitoring System
Network Monitoring SystemRofiq Fauzi
 
Network protocols
Network protocolsNetwork protocols
Network protocolsAbiud Orina
 
netfilter and iptables
netfilter and iptablesnetfilter and iptables
netfilter and iptablesKernel TLV
 
IPv6 Transition & Deployment, including IPv6-only in cellular and broadband
IPv6 Transition & Deployment, including IPv6-only in cellular and broadbandIPv6 Transition & Deployment, including IPv6-only in cellular and broadband
IPv6 Transition & Deployment, including IPv6-only in cellular and broadbandAPNIC
 
Computer networks network layer,routing
Computer networks network layer,routingComputer networks network layer,routing
Computer networks network layer,routingDeepak John
 

What's hot (20)

Network devices ppt
Network devices   pptNetwork devices   ppt
Network devices ppt
 
Introduction to Network Function Virtualization (NFV)
Introduction to Network Function Virtualization (NFV)Introduction to Network Function Virtualization (NFV)
Introduction to Network Function Virtualization (NFV)
 
Ngn
NgnNgn
Ngn
 
Troubleshooting Network and Network Utilities
Troubleshooting Network and Network UtilitiesTroubleshooting Network and Network Utilities
Troubleshooting Network and Network Utilities
 
ngn overview , next generation network
ngn overview , next generation networkngn overview , next generation network
ngn overview , next generation network
 
Wired and Wireless Examples in ns2
Wired and Wireless Examples in ns2Wired and Wireless Examples in ns2
Wired and Wireless Examples in ns2
 
5G Network Architecture Options
5G Network Architecture Options5G Network Architecture Options
5G Network Architecture Options
 
Ds practical file
Ds practical fileDs practical file
Ds practical file
 
5G Network Slicing
5G Network Slicing5G Network Slicing
5G Network Slicing
 
Lan network
Lan networkLan network
Lan network
 
Packet Switching
Packet SwitchingPacket Switching
Packet Switching
 
Introduction to ns3
Introduction to ns3Introduction to ns3
Introduction to ns3
 
Link state protocols.ppt
Link state protocols.pptLink state protocols.ppt
Link state protocols.ppt
 
SNMP(Simple Network Management Protocol)
SNMP(Simple Network Management Protocol)SNMP(Simple Network Management Protocol)
SNMP(Simple Network Management Protocol)
 
Network Monitoring System
Network Monitoring SystemNetwork Monitoring System
Network Monitoring System
 
Network protocols
Network protocolsNetwork protocols
Network protocols
 
netfilter and iptables
netfilter and iptablesnetfilter and iptables
netfilter and iptables
 
CCNA training report
CCNA training reportCCNA training report
CCNA training report
 
IPv6 Transition & Deployment, including IPv6-only in cellular and broadband
IPv6 Transition & Deployment, including IPv6-only in cellular and broadbandIPv6 Transition & Deployment, including IPv6-only in cellular and broadband
IPv6 Transition & Deployment, including IPv6-only in cellular and broadband
 
Computer networks network layer,routing
Computer networks network layer,routingComputer networks network layer,routing
Computer networks network layer,routing
 

Viewers also liked

1 session installation
1 session installation1 session installation
1 session installationRahul Hada
 
Socio-technical System
Socio-technical SystemSocio-technical System
Socio-technical SystemRahul Hada
 
Network Simulation NS3
Network Simulation NS3Network Simulation NS3
Network Simulation NS3baddi youssef
 
ns-3: History and Future
ns-3: History and Futurens-3: History and Future
ns-3: History and Futuremathieu_lacage
 
Fundamental of Shell Programming
Fundamental of Shell ProgrammingFundamental of Shell Programming
Fundamental of Shell ProgrammingRahul Hada
 
Socket Programming using Java
Socket Programming using JavaSocket Programming using Java
Socket Programming using JavaRahul Hada
 
Mobile Network Layer
Mobile Network LayerMobile Network Layer
Mobile Network LayerRahul Hada
 
Routing protocols in Ad-hoc Networks- A Simulation Study
Routing protocols in Ad-hoc Networks- A Simulation StudyRouting protocols in Ad-hoc Networks- A Simulation Study
Routing protocols in Ad-hoc Networks- A Simulation StudyIOSR Journals
 
CCNxCon2012: Session 6: Simulation Platform for Content Centric Networks Prot...
CCNxCon2012: Session 6: Simulation Platform for Content Centric Networks Prot...CCNxCon2012: Session 6: Simulation Platform for Content Centric Networks Prot...
CCNxCon2012: Session 6: Simulation Platform for Content Centric Networks Prot...PARC, a Xerox company
 
Xamarin.Mac Seminar
Xamarin.Mac SeminarXamarin.Mac Seminar
Xamarin.Mac SeminarXamarin
 
Measuring and Comparing the Reliability of the Structured Walkthrough Evaluat...
Measuring and Comparing the Reliability of the Structured Walkthrough Evaluat...Measuring and Comparing the Reliability of the Structured Walkthrough Evaluat...
Measuring and Comparing the Reliability of the Structured Walkthrough Evaluat...chrisbailey000
 
IEEE NS2 & NS3 PROJECT TITLE 2015-16
IEEE NS2 & NS3  PROJECT TITLE 2015-16IEEE NS2 & NS3  PROJECT TITLE 2015-16
IEEE NS2 & NS3 PROJECT TITLE 2015-16Spiro Vellore
 
Script login form php
Script login form phpScript login form php
Script login form phpHanief Rpl
 
Final Year Project Report Example
Final Year Project Report ExampleFinal Year Project Report Example
Final Year Project Report ExampleMuhd Mu'izuddin
 

Viewers also liked (20)

1 session installation
1 session installation1 session installation
1 session installation
 
Socio-technical System
Socio-technical SystemSocio-technical System
Socio-technical System
 
Network Simulation NS3
Network Simulation NS3Network Simulation NS3
Network Simulation NS3
 
ns-3: History and Future
ns-3: History and Futurens-3: History and Future
ns-3: History and Future
 
Fundamental of Shell Programming
Fundamental of Shell ProgrammingFundamental of Shell Programming
Fundamental of Shell Programming
 
Ns 2 Network Simulator An Introduction
Ns 2 Network Simulator An IntroductionNs 2 Network Simulator An Introduction
Ns 2 Network Simulator An Introduction
 
Inheritance
InheritanceInheritance
Inheritance
 
Socket Programming using Java
Socket Programming using JavaSocket Programming using Java
Socket Programming using Java
 
Mobile Network Layer
Mobile Network LayerMobile Network Layer
Mobile Network Layer
 
Routing protocols in Ad-hoc Networks- A Simulation Study
Routing protocols in Ad-hoc Networks- A Simulation StudyRouting protocols in Ad-hoc Networks- A Simulation Study
Routing protocols in Ad-hoc Networks- A Simulation Study
 
CCNxCon2012: Session 6: Simulation Platform for Content Centric Networks Prot...
CCNxCon2012: Session 6: Simulation Platform for Content Centric Networks Prot...CCNxCon2012: Session 6: Simulation Platform for Content Centric Networks Prot...
CCNxCon2012: Session 6: Simulation Platform for Content Centric Networks Prot...
 
NS3 Tech Talk
NS3 Tech TalkNS3 Tech Talk
NS3 Tech Talk
 
Xamarin.Mac Seminar
Xamarin.Mac SeminarXamarin.Mac Seminar
Xamarin.Mac Seminar
 
Measuring and Comparing the Reliability of the Structured Walkthrough Evaluat...
Measuring and Comparing the Reliability of the Structured Walkthrough Evaluat...Measuring and Comparing the Reliability of the Structured Walkthrough Evaluat...
Measuring and Comparing the Reliability of the Structured Walkthrough Evaluat...
 
Named data networking. Basic Principle
Named data networking. Basic PrincipleNamed data networking. Basic Principle
Named data networking. Basic Principle
 
Introduction to Qualnet
Introduction to Qualnet Introduction to Qualnet
Introduction to Qualnet
 
Network simulation software
Network simulation softwareNetwork simulation software
Network simulation software
 
IEEE NS2 & NS3 PROJECT TITLE 2015-16
IEEE NS2 & NS3  PROJECT TITLE 2015-16IEEE NS2 & NS3  PROJECT TITLE 2015-16
IEEE NS2 & NS3 PROJECT TITLE 2015-16
 
Script login form php
Script login form phpScript login form php
Script login form php
 
Final Year Project Report Example
Final Year Project Report ExampleFinal Year Project Report Example
Final Year Project Report Example
 

Similar to Tutorial ns 3-tutorial-slides

Plenzogan technology
Plenzogan technologyPlenzogan technology
Plenzogan technologyplenzogan
 
Paper9250 implementation of an i pv6 stack for ns-3
Paper9250 implementation of an i pv6 stack for ns-3Paper9250 implementation of an i pv6 stack for ns-3
Paper9250 implementation of an i pv6 stack for ns-3Suhail Ahmed Chandio
 
Spring sim 2010-riley
Spring sim 2010-rileySpring sim 2010-riley
Spring sim 2010-rileySopna Sumāto
 
neutron_icehouse_update
neutron_icehouse_updateneutron_icehouse_update
neutron_icehouse_updateAkihiro Motoki
 
WiMAX implementation in ns3
WiMAX implementation in ns3WiMAX implementation in ns3
WiMAX implementation in ns3Mustafa Khaleel
 
Introduction to Openstack Network
Introduction to Openstack NetworkIntroduction to Openstack Network
Introduction to Openstack Networksalv_orlando
 
Differences of Deep Learning Frameworks
Differences of Deep Learning FrameworksDifferences of Deep Learning Frameworks
Differences of Deep Learning FrameworksSeiya Tokui
 
An introduction to_ns_nam_and_o_tcl_scripting
An introduction to_ns_nam_and_o_tcl_scriptingAn introduction to_ns_nam_and_o_tcl_scripting
An introduction to_ns_nam_and_o_tcl_scriptingDani Aristiyawan
 
Network Analyzer and Report Generation Tool for NS-2 using TCL Script
Network Analyzer and Report Generation Tool for NS-2 using TCL ScriptNetwork Analyzer and Report Generation Tool for NS-2 using TCL Script
Network Analyzer and Report Generation Tool for NS-2 using TCL ScriptIRJET Journal
 
history_of_linux lec 7.pptx
history_of_linux lec 7.pptxhistory_of_linux lec 7.pptx
history_of_linux lec 7.pptxtouseeqzulfiqar1
 
Princeton Dec 2022 Meetup_ NiFi + Flink + Pulsar
Princeton Dec 2022 Meetup_ NiFi + Flink + PulsarPrinceton Dec 2022 Meetup_ NiFi + Flink + Pulsar
Princeton Dec 2022 Meetup_ NiFi + Flink + PulsarTimothy Spann
 
The road ahead for scientific computing with Python
The road ahead for scientific computing with PythonThe road ahead for scientific computing with Python
The road ahead for scientific computing with PythonRalf Gommers
 

Similar to Tutorial ns 3-tutorial-slides (20)

Plenzogan technology
Plenzogan technologyPlenzogan technology
Plenzogan technology
 
Paper9250 implementation of an i pv6 stack for ns-3
Paper9250 implementation of an i pv6 stack for ns-3Paper9250 implementation of an i pv6 stack for ns-3
Paper9250 implementation of an i pv6 stack for ns-3
 
Spring sim 2010-riley
Spring sim 2010-rileySpring sim 2010-riley
Spring sim 2010-riley
 
Chapter 6 os
Chapter 6 osChapter 6 os
Chapter 6 os
 
neutron_icehouse_update
neutron_icehouse_updateneutron_icehouse_update
neutron_icehouse_update
 
WiMAX implementation in ns3
WiMAX implementation in ns3WiMAX implementation in ns3
WiMAX implementation in ns3
 
Introduction to Openstack Network
Introduction to Openstack NetworkIntroduction to Openstack Network
Introduction to Openstack Network
 
Differences of Deep Learning Frameworks
Differences of Deep Learning FrameworksDifferences of Deep Learning Frameworks
Differences of Deep Learning Frameworks
 
An introduction to_ns_nam_and_o_tcl_scripting
An introduction to_ns_nam_and_o_tcl_scriptingAn introduction to_ns_nam_and_o_tcl_scripting
An introduction to_ns_nam_and_o_tcl_scripting
 
Network Analyzer and Report Generation Tool for NS-2 using TCL Script
Network Analyzer and Report Generation Tool for NS-2 using TCL ScriptNetwork Analyzer and Report Generation Tool for NS-2 using TCL Script
Network Analyzer and Report Generation Tool for NS-2 using TCL Script
 
Ch04 threads
Ch04 threadsCh04 threads
Ch04 threads
 
Mina2
Mina2Mina2
Mina2
 
history_of_linux lec 7.pptx
history_of_linux lec 7.pptxhistory_of_linux lec 7.pptx
history_of_linux lec 7.pptx
 
cv
cvcv
cv
 
cv
cvcv
cv
 
An Introduction to OMNeT++ 5.4
An Introduction to OMNeT++ 5.4An Introduction to OMNeT++ 5.4
An Introduction to OMNeT++ 5.4
 
TechTalk: Connext DDS 5.2.
TechTalk: Connext DDS 5.2.TechTalk: Connext DDS 5.2.
TechTalk: Connext DDS 5.2.
 
Princeton Dec 2022 Meetup_ NiFi + Flink + Pulsar
Princeton Dec 2022 Meetup_ NiFi + Flink + PulsarPrinceton Dec 2022 Meetup_ NiFi + Flink + Pulsar
Princeton Dec 2022 Meetup_ NiFi + Flink + Pulsar
 
4 g module devt using python
4 g module devt using python4 g module devt using python
4 g module devt using python
 
The road ahead for scientific computing with Python
The road ahead for scientific computing with PythonThe road ahead for scientific computing with Python
The road ahead for scientific computing with Python
 

Recently uploaded

Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 

Recently uploaded (20)

Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 

Tutorial ns 3-tutorial-slides

  • 1. ns-3 tutorial Presenter: Tom Henderson University of Washington Simutools Conference March, 2008 ns-3 tutorial March 2008 1
  • 2. 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) ns-3 tutorial March 2008 2
  • 3. 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
  • 4. Assumptions • Some familiarity with C++ programming language • Some familiarity with Unix Network Programming (e.g., sockets) • Some familiarity with discrete-event simulators ns-3 tutorial March 2008 4
  • 5. Outline • Introduction to ns-3 • Reading ns-3 code • Tweaking ns-3 code • Extending ns-3 code ns-3 tutorial March 2008 5
  • 6. What is ns (or ns-2)? • ns is a discrete-event network simulator for Internet systems – protocol design, multiple levels of abstraction – written in multiple languages (C++/OTcl) • ns has a companion network animator called nam – hence, has been called the nsnam project ns-3 is a research-oriented, discrete event simulator ns-3 tutorial March 2008 6
  • 7. 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 tutorial March 2008 7
  • 8. ns-3 models Project focus has been on the software core, to date ns-3 tutorial March 2008 8
  • 9. 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
  • 10. ns-3 relationship to ns-2 ns-3 is not an extension of ns-2 • does not have an OTcl API – C++ wrapped by Python • synthesis of yans, ns-2, GTNetS simulators, and new software – example ns-2 models so far: random variables, error models, OLSR • guts of simulator are completely replaced • new visualizers are in works ns-3 tutorial March 2008 10
  • 11. ns-3 status (March 2008) ns-3 is in a pre-alpha state • monthly development releases • APIs being finalized • emphasis has been on setting the architecture • new users should expect rough edges • many opportunities to work on the core models ns-3 tutorial March 2008 11
  • 12. ns-3 status (March 2008) What others are already using ns-3 for: • wifi-based simulations of OLSR and other MANET routing • MANET routing (SMF and unicast protocols) • OntoNet: Scalable Knowledge Based Networking" by Joe Kopena and Boon Thau Loo (UPenn) ns-3 tutorial March 2008 12
  • 13. ns-3 roadmap (2008) near term (through June) • finalize and release simulation core (April/May) – core APIs • ns-3.1 complete release (June timeframe) – add Internet and Device models – add validation framework – some higher-level topology/scenario APIs ns-3 tutorial March 2008 13
  • 14. ns-3 roadmap (2008) planned for later this year • emulation modes • statistics • support for real code • additional ns-2 porting/integration • distributed simulation • visualization ns-3 tutorial March 2008 14
  • 15. 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
  • 16. Links to materials • Today's code – http://www.nsnam.org/tutorials/simutools08/ns-3-tu 3-tutorial.tar.gz • Tutorial slides: – PPT: http://www.nsnam.org/tutorials/simutools08/ns-3-tu 3-tutorial.ppt – PDF: http://www.nsnam.org/tutorials/simutools08/ns -3-tutorial.pdf ns-3 tutorial March 2008 16
  • 17. Questions so far? ns-3 tutorial March 2008 17
  • 18. Outline • Introduction to ns-3 • Reading ns-3 code • Tweaking ns-3 code • Extending ns-3 code ns-3 tutorial March 2008 18
  • 19. Reading ns-3 code • Browsing the source code • Conceptual overview • Script walkthrough ns-3 tutorial March 2008 19
  • 20. 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) ns-3 tutorial March 2008 20
  • 21. Browse the source tomh@A3803721 ~/home/ns-3-dev $ ls AUTHORS README VERSION examples samples tutorial waf wscript LICENSE RELEASE_NOTES doc ns3 src utils waf.bat Pause presentation to browse source code http://www.nsnam.org/tutorials/simutools08/ns-3-tutorial.tar.gz ns-3 tutorial March 2008 21
  • 22. Doxygen documentation • Most of the ns-3 API is documented with Doxygen – http://www.stack.nl/~dimitri/doxygen/ Pause presentation to browse Doxygen http://www.nsnam.org/doxygen/index.html ns-3 tutorial March 2008 22
  • 23. 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/ Pause presentation to build with waf ns-3 tutorial March 2008 23
  • 24. waf key concepts • For those familiar with autotools: • configure -> ./waf -d [optimized|debug] configure • make -> ./waf • make test -> ./waf check (run unit tests) • Can run programs through a special waf shell; e.g. – ./waf --run simple-point-to-point – (this gets the library paths right for you) ns-3 tutorial March 2008 24
  • 25. The basic model Application Application Application Application Sockets-like API Protocol Protocol Packet(s) stack stack Node Node NetDevice NetDevice NetDevice Channel NetDevice Channel ns-3 tutorial March 2008 25
  • 26. Fundamentals Key objects in the simulator are Nodes, Packets, and Channels Nodes contain Applications, “stacks”, and NetDevices ns-3 tutorial March 2008 26
  • 27. Node basics A Node is a husk of a computer to which applications, stacks, and NICs are added Application Application Application “DTN” ns-3 tutorial March 2008 27
  • 28. NetDevices and Channels NetDevices are strongly bound to Channels of a matching type WifiChannel WifiNetDevice Nodes are architected for multiple interfaces ns-3 tutorial March 2008 28
  • 29. 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 device- independent sublayer in Linux i.e., Linux Packet Sockets ns-3 tutorial March 2008 29
  • 30. 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
  • 31. 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 ns-3 tutorial March 2008 31
  • 32. example: UDP header class UdpHeader : public Header { public: void SetDestination (uint16_t port); ... void Serialize (Buffer::Iterator start) const; uint32_t Deserialize (Buffer::Iterator start); private: uint16_t m_sourcePort; uint16_t m_destinationPort; uint16_t m_payloadSize; uint16_t m_initialChecksum; } ns-3 tutorial March 2008 32
  • 33. example: UDP header void UdpHeader::Serialize (Buffer::Iterator start) const { Buffer::Iterator i = start; i.WriteHtonU16 (m_sourcePort); i.WriteHtonU16 (m_destinationPort); i.WriteHtonU16 (m_payloadSize + GetSerializedSize ()); i.WriteU16 (0); if (m_calcChecksum) { uint16_t checksum = Ipv4ChecksumCalculate (...); i.WriteU16 (checksum); } } ns-3 tutorial March 2008 33
  • 34. 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
  • 35. Sample script walkthrough WiFi (AdHoc network) Backbone CSMA (LAN) Hierarchical mobility WiFi WiFi 1) AdHoc (Infra- (Infra- movement in structure structure backbone ) ) 2) Local movement relative to Access Point Applications: UDP flow, Routing: OLSR on backbone ns-3 tutorial March 2008 35
  • 36. Sample script walkthrough Walk through mixed-wireless.cc ns-3 tutorial March 2008 36
  • 37. (aside) similar looking code in Python import sys import ns3 as ns 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 = ns.InternetNode() n1 = ns.InternetNode() n2 = ns.InternetNode() n3 = ns.InternetNode() ... ns-3 tutorial March 2008 37
  • 38. examples/ directory • examples/ contains other scripts with similar themes $ ls csma-broadcast.cc simple-point-to-point.cc csma-multicast.cc tcp-large-transfer-errors.cc csma-one-subnet.cc tcp-large-transfer.cc csma-packet-socket.cc tcp-nonlistening-server.cc mixed-global-routing.cc tcp-small-transfer-oneloss.cc simple-alternate-routing.cc tcp-small-transfer.cc simple-error-model.cc udp-echo.cc simple-global-routing.cc waf simple-point-to-point-olsr.cc wscript ns-3 tutorial March 2008 38
  • 39. Outline • Introduction to ns-3 • Reading ns-3 code • Tweaking ns-3 code • Extending ns-3 code ns-3 tutorial March 2008 39
  • 40. ns-3 logging • ns-3 has a built-in logging facility to stderr • Features: – can be driven from shell environment variables – Multiple log levels like syslog – Function and call argument tracing • Intended for debugging, but can be abused to provide tracing – we do not guarantee that format is unchanging ns-3 tutorial March 2008 40
  • 41. ns-3 logging example • NS_LOG_UNCOND(); • NS_LOG environment variable • per-source-file logging • log levels • example scripts ns-3 tutorial March 2008 41
  • 42. attributes and tracing • Next, we would like to talk about attributes (default values, settable and gettable values) and tracing • To understand this, we'll introduce the ns- 3 Object system ns-3 tutorial March 2008 42
  • 43. Object metadata system • ns-3 is, at heart, a C++ object system • ns-3 objects that inherit from base class ns3::Object get several additional features – dynamic run-time object aggregation – an attribute system – smart-pointer memory management Disclaimer: This is not all main-line ns-3 code-- parts are in a proposal in the mathieu/ns-3-param repository ns-3 tutorial March 2008 43
  • 44. Object aggregation use case • You can aggregate objects to one another at run-time – Avoids the need to modify a base class to provide pointers to all possible connected objects • Object aggregation is planned to be the main way to create new Node types (rather than subclassing Node) ns-3 tutorial March 2008 44
  • 45. Object aggregation example void WifiChannel::Send (Ptr<WifiPhy> sender, Ptr<const Packet> packet, ...) { Ptr<MobilityModel> senderMobility = 0; Ptr<MobilityModel> receiverMobility = 0; ... senderMobility = sender->GetNode ()-> GetObject<MobilityModel> (); class Node does not need to know } about MobilityModel ns-3 tutorial March 2008 45
  • 46. Use cases for attributes • An Attribute represents a value in our system • An Attribute can be connected to an underlying variable or function – e.g. TcpSocket::m_cwnd; – or a trace source ns-3 tutorial March 2008 46
  • 47. Use cases for attributes (cont.) • What would users like to do? – Know what are all the attributes that affect the simulation at run time – Set a default initial value for a variable – Set or get the current value of a variable – Initialize the value of a variable when a constructor is called • The attribute system is a unified way of handling these functions ns-3 tutorial March 2008 47
  • 48. How to handle attributes • The traditional C++ way: – export attributes as part of a class's public API – walk pointer chains (and iterators, when needed) to find what you need – use static variables for defaults • The attribute system provides a more convenient API to the user to do these things ns-3 tutorial March 2008 48
  • 49. The traditional C++ way class Foo { public: void SetVar1 (uint32_t value); uint32_t GetVar1 (void); static void SetInitialVar1(uint32_t value); void SetVar2 (uint32_t value); uint32_t GetVar2 (void); static void SetInitialVar2(uint32_t value); ... private: uint32_t m_var1; // document var1 uint32_t m_var2; // document var2 static uint32_t m_initial_var1; static uint32_t m_initial_var2; } Foo::Foo() : m_var1(Foo::m_initial_var1), m_var2(Foo::m_initial_var2) { } to modify an instance of Foo, get the pointer somehow, and use the public accessor functions to modify the default values, modify the statics Default values may be available in a separate framework (e.g. ns-2 Bind()) ns-3 tutorial March 2008 49
  • 50. Navigating the attributes • Attributes are exported into a string-based namespace, with filesystem-like paths – namespace supports regular expressions • Attributes also can be used without the paths – e.g. “WifiPhy::TxGain” • A Config class allows users to manipulate the attributes ns-3 tutorial March 2008 50
  • 51. Navigating the attributes using paths • Examples: – Nodes with NodeIds 1, 3, 4, 5, 8, 9, 10, 11: “/NodeList/[3-5]|[8-11]|1” – UdpL4Protocol object instance aggregated to matching nodes: “/$UdpL4Protocol” – EndPoints which match the SrcPort=1025 specification: “/EndPoints/*:SrcPort=1025” ns-3 tutorial March 2008 51
  • 52. What users will do • e.g.: Set a default initial value for a variable • (Note: this replaces DefaultValue::Bind()) Config::Set (“WifiPhy::TxGain”, Double (1.0)); • Syntax also supports string values: Config::Set (“WifiPhy::TxGain”, “1.0”); Attribute Value ns-3 tutorial March 2008 52
  • 53. What users will see • Set or get the current value of a variable – Here, one needs the path in the namespace to the right instance of the object Config::SetAttribute(“/NodeList/5/DeviceList/3/Phy /TxGain”, Double(1.0)); Double d = Config::GetAttribute(“/NodeList/5/NetDevice/3/Phy /TxGain”); • Users can get Ptrs to instances also, and Ptrs to trace sources, in the same way ns-3 tutorial March 2008 53
  • 54. 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> (); ns-3 tutorial March 2008 54
  • 55. 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); ns-3 tutorial March 2008 55
  • 56. 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)); ns-3 tutorial March 2008 56
  • 57. How is all this implemented (overview) class Foo P public Object { public: static TypeId GetTypeId (void); private: uint32_t m_var1; // document var1 uint32_t m_var2; // document var2 } Foo::Foo() { } TypeId Foo::GetTypeId (void) { static TypeId tid = TypeId(“Foo”); .SetParent (<ooParent> .SetGroupName (“FooDefaults”) .AddConstructor<Foo> (); .AddAttribute (“m_var1”, “document var1”, UInteger(3), MakeUIntegerAccessor (&Foo::m_var1), MakeUIntegerChecker<uint32_t> ()) .AddAttribute (“m_var2”, “”, ...) return tid; } ns-3 tutorial March 2008 57
  • 58. A real TypeId example TypeId RandomWalk2dMobilityModel::GetTypeId (void) { static TypeId tid = TypeId ("RandomWalkMobilityModel") .SetParent<MobilityModel> () .SetGroupName ("Mobility") .AddConstructor<RandomWalk2dMobilityModel> () .AddAttribute ("bounds", "Bounds of the area to cruise.", Rectangle (0.0, 0.0, 100.0, 100.0), MakeRectangleAccessor (&RandomWalk2dMobilityModel::m_bounds), MakeRectangleChecker ()) .AddAttribute ("time", "Change current direction and speed after moving for this delay.", Seconds (1.0), MakeTimeAccessor (&RandomWalk2dMobilityModel::m_modeTime), MakeTimeChecker ()) .AddAttribute ("distance", "Change current direction and speed after moving for this distance.", Seconds (1.0), MakeTimeAccessor (&RandomWalk2dMobilityModel::m_modeTime), MakeTimeChecker ()) ns-3 tutorial March 2008 58
  • 59. Also part of Object: smart pointers • ns-3 uses reference-counting smart pointers at its APIs to limit memory leaks – Or “pass by value” or “pass by reference to const” where appropriate • A “smart pointer” behaves like a normal 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
  • 60. Statements you should understand now Ptr<Ipv4AddressAllocator> ipAddrs = CreateObject<Ipv4AddressAllocator> (); C++ Smart Pointer ns3::Object Config::SetDefault (“OnOffApplication::DataRate”, String(“448kb/s”)); Config::SetDefault (“/NodeList/*/DeviceList/*/Phy/TxGain”, Double(10.0)); Attribute namespace ns-3 tutorial March 2008 60
  • 61. Tracing model • Tracing is a structured form of simulation output – tracing format should be relatively static across simulator releases • Example (from ns-2): + 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 610 r 1.84471 2 1 cbr 210 ------- 1 3.0 1.0 195 600 r 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 • Needs vary widely ns-3 tutorial March 2008 61
  • 62. Crude tracing #include <iostream> ... int main () { ... std::cout << "The value of x is " << x << std::endl; ... } ns-3 tutorial March 2008 62
  • 63. slightly less crude #include <iostream> ... int main () { ... NS_LOG_UNCOND ("The value of x is " << x); ... } ns-3 tutorial March 2008 63
  • 64. Simple ns-3 tracing • these are wrapper functions/classes • see examples/mixed-wireless.cc #include "ns3/ascii-trace.h" AsciiTrace asciitrace ("mixed-wireless.tr"); asciitrace.TraceAllQueues (); asciitrace.TraceAllNetDeviceRx (); ns-3 tutorial March 2008 64
  • 65. Simple ns-3 tracing (pcap version) • these are wrapper functions/classes • see examples/mixed-wireless.cc #include "ns3/pcap-trace.h" PcapTrace pcaptrace ("mixed-wireless.pcap"); pcaptrace.TraceAllIp (); ns-3 tutorial March 2008 65
  • 66. ns-3 tracing model (revisit) • Fundamental #1: decouple trace sources from trace sinks • Fundamental #2: prefer standard trace outputs for built-in traces Trace source Trace source Trace sink Trace source configurable by unchanging user ns-3 tutorial March 2008 66
  • 67. Tracing overview • Simulator provides a set of pre-configured trace sources – Users may edit the core to add their own • Users provide trace sinks and attach to the trace source – Simulator core provides a few examples for common cases • Multiple trace sources can connect to a trace sink ns-3 tutorial March 2008 67
  • 68. Multiple levels of tracing • Highest-level: Use built-in trace sources and sinks and hook a trace file to them • Mid-level: Customize trace source/sink behavior using the tracing namespace • Low-level: Add trace sources to the tracing namespace – Or expose trace source explicitly ns-3 tutorial March 2008 68
  • 69. 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 // display timestamps correctly) PcapTrace pcaptrace ("simple-point-to-point.pcap"); pcaptrace.TraceAllIp (); ns-3 tutorial March 2008 69
  • 70. Mid-level of tracing • Mid-level: Customize trace source/sink behavior using the tracing namespace void Regular expression editing PcapTrace::TraceAllIp (void) { NodeList::Connect ("/nodes/*/ipv4/(tx|rx)", MakeCallback (&PcapTrace::LogIp, this)); } Hook in a different trace sink ns-3 tutorial March 2008 70
  • 71. Asciitrace: under the hood void AsciiTrace::TraceAllQueues (void) { Packet::EnableMetadata (); NodeList::Connect ("/nodes/*/devices/*/queue/enqueue", MakeCallback (&AsciiTrace::LogDevQueueEnqueue, this)); NodeList::Connect ("/nodes/*/devices/*/queue/dequeue", MakeCallback (&AsciiTrace::LogDevQueueDequeue, this)); NodeList::Connect ("/nodes/*/devices/*/queue/drop", MakeCallback (&AsciiTrace::LogDevQueueDrop, this)); } ns-3 tutorial March 2008 71
  • 72. Lowest-level of tracing • Low-level: Add trace sources to the tracing namespace Config::Connect ("/NodeList/.../Source", MakeCallback (&ConfigTest::ChangeNotification, this)); ns-3 tutorial March 2008 72
  • 73. Statistics Disclaimer: not yet part of ns-3 • 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/ – Static “Stat” object that collects samples of variables based on explicit function calls inserted into the code – Graphical front end, and framework for replicating simulation runs ns-3 tutorial March 2008 73
  • 74. Revisit our script WiFi (AdHoc network) Backbone CSMA (LAN) Hierarchical mobility WiFi WiFi 1) AdHoc (Infra- (Infra- movement in structure structure backbone ) ) 2) Local movement relative to Access Point Applications: TCP flow, Routing: OLSR routing ns-3 tutorial March 2008 74
  • 75. Design patterns for topology scripts Design approaches • Use simple helper functions with attributes • Use reusable “frameworks” Note: This area of our API is under discussion; feedback wanted ns-3 tutorial March 2008 75
  • 76. 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 ''set of same objects” ns-3 tutorial March 2008 76
  • 77. Helper Objects • NodeContainer: vector of Ptr<Node> • NetDeviceContainer: vector of Ptr<NetDevice> • InternetStackHelper • WifiHelper • MobilityHelper • OlsrHelper • ... Each model provides a helper class ns-3 tutorial March 2008 77
  • 78. 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); ns-3 tutorial March 2008 78
  • 79. setup wifi subnets for (uint32_t I = 0; I < 20; i++) NodeContainer subnet; subnet.Create (29); subnets.push_back (subnet); mobility.PushReferenceModel (backbone.Get (i)); mobility.SetMobilityModel (...) mobility.SetPositionAllocator (...); mobility.Layout (subnet); subnet.Add (backbone.Get (i)); Ptr<WifiChannel> subnetChannel = ...; NetDeviceContainer subnetDev = wifi.Build (subnet, subnetChannel); subnetDevs.push_back (subnetDev); ns-3 tutorial March 2008 79
  • 80. setup ip over backbone and subnets IpNetworkAddressAllocator network; network.SetMask (“192.168.0..0”, “255.255.0.0”); InternetStackHelper ip; ip.SetAddressAllocator (network.GetNext ()); ip.Setup (backboneDev); for (uint32_t I = 0; I < 20; i++) NetDeviceContainer subnetDev = subnetDevs[i]; ip.SetAddressAllocator (network.GetNext ()); ip.Setup (subnetDev); ns-3 tutorial March 2008 80
  • 81. setup olsr on backbone OlsrHelper olsr; olsr.Enable (backbone); ns-3 tutorial March 2008 81
  • 82. setup traffic sinks everywhere TrafficSinkHelper sink; // listen on port 1026 for protocol udp sink.EnableUdp (1026); sink.Setup (NodeList::Begin (), NodeList::End ()); ns-3 tutorial March 2008 82
  • 83. setup trace sources OnOffApplicationHelper source; source.SetUdpDestination (“168.192.4.10”, 1026); NodeContainer one = subnets[2].Get (); source.Setup (one); ns-3 tutorial March 2008 83
  • 84. 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
  • 85. 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
  • 86. 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
  • 87. Outline • Introduction to ns-3 • Reading ns-3 code • Tweaking ns-3 code • Extending ns-3 code ns-3 tutorial March 2008 87
  • 88. How do simulator objects fit together? • ns-3 objects are C++ objects – can be subclassed • ns-3 Objects support aggregation ns-3 models are composed of hooking C++ classes together in the traditional way, and also with object aggregation ns-3 tutorial March 2008 88
  • 89. 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); • might eventually become • int Add (int first, int second); ns-3 tutorial March 2008 89
  • 90. Aside: C++ templates • Definition: template <typename T> T Add (T first, T second) { return first + second; } • Usage: int x, y, z; z = Add<int> (x, y); ns-3 tutorial March 2008 90
  • 91. Classes may also be templatized • Declaration: template <typename T> class MyStack { void Push (T data); T Pop (void); }; • 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. Scheduler and callbacks • Let’s look at samples/main-simulator.cc • Schedules a single event, then exits int main (int argc, char *argv[]) { MyModel model; Simulator::Schedule (Seconds (10.0), &random_function, &model); Simulator::Run (); Simulator::Destroy (); } ns-3 tutorial March 2008 92
  • 93. 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) {} ^ ^ ^ | ---| ------| | | | Callback<double, double, double> one; • Bind a function with a matching signature to a callback one = MakeCallback (&CbOne); double returnOne = one (10.0, 20.0); ns-3 tutorial March 2008 93
  • 94. Path of a packet (send) Note: This architecture is under additional work ns-3 tutorial March 2008 94
  • 95. Path of a packet (receive) ns-3 tutorial March 2008 95
  • 96. current ns-3 routing model classes Ipv4RoutingProtocol, Ipv4Route • Each routing protocol maintains its own RIB --> no common FIB • Routing protocols are registered with AddRoutingProtocol (Ptr<> protocol, int16_t priority) • Routes are looked up by querying each protocol for a route – Ipv4L3Protocol::Lookup() ns-3 tutorial March 2008 96
  • 97. Writing new ns-3 models 1) Define your requirements – reusability – dependencies – functionality 2) API review – Provide sample header file for API review – gather feedback from the ns-developers list ns-3 tutorial March 2008 97
  • 98. Writing new ns-3 models 3) Create a non-functional skeleton – review coding style – decide which compilation unit it resides in – add to waf – build with body ifdeffed out – copyright and headers – initial doxygen ns-3 tutorial March 2008 98
  • 99. Writing new ns-3 models 4) Build a skeleton – header include guards – namespace ns3 – constructor, empty function prototypes – key variables – Object/TypeId code – write small test program – start a unit test ns-3 tutorial March 2008 99
  • 100. Writing new ns-3 models 5) Build core functions and unit tests – use of logging, and asserts 6) Plumb into other modules, if needed 7) Post for review on developers list 8) Resolve comments and merge ns-3 tutorial March 2008 100
  • 101. Porting from ns-2 • Objects can be ported from ns-2 (or other simulators) • Make sure licensing is compatible • Example: – ns-2: queue/errmodel.{cc,h} – ns-3: src/common/error-model.{cc,h} ns-3 tutorial March 2008 101
  • 102. 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
  • 103. Walk through examples (time permitting) • Beyond simple simulation scenarios • Add a new type of MAC+PHY: • subclass a NetDevice and a Channel • Add new types of transport layers: • subclass Node and Socket • subclass Ipv4 class to implement per-node Ipv4 forwarding table and Ipv4 • interface configuration • for example, the Linux TCP stack could be easily integrated into a new type of node, LinuxNode with a LinuxTcpSocket • Add a new type of traffic generation and analysis: • subclass Application ns-3 tutorial March 2008 103 • • use Socket API
  • 104. ns-3 goals for emulation real machine ns-3 ns-3 virtual virtual real real machine machine machine machine ns-3 Testbed 1) ns-3 interconnects virtual 2) testbeds interconnect ns-3 machines stacks ns-3 tutorial March 2008 104
  • 105. 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 • ns-3 needs you! ns-3 tutorial March 2008 105
  • 106. Proposed Google Summer of Code projects • Performance Evaluation and Optimization • Linux Kernel Network Stack Integration • Parallel Simulations • GUI Development • Real World Code Integration ns-3 tutorial March 2008 106
  • 107. 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