Home  Index

AU-KBC RESEARCH CENTRE

NETWORK SIMULATOR

Simulation is the execution of a system model in time that gives information about a system being investigated. Events occur at discrete points of time. When the number of such events are finite, we call it discrete event. A discrete event Simulator consists of a bunch of events & a central Simulator object that executes these events in order.
The following pieces are most important or essential to any simulation

An abstract framework of events
A data structure to manage events
Functions to generate random variables
facilities to allow objects to interact
NS-2 is an Object-Oriented, discrete event network Simulator developed at UC Berkely. It is written in C++ and OTcl(Object-Oriented Tcl) and primarily uses OTcl as Command and Configuration Language. NS is mailnly used for simulating local and wide area networks. It simulates a wide variety of IP networks.

It implements network protocols such as TCP and UDP, traffic source behaviour such as FTP, Telnat, Web, CBR & VBR. router queue management mechanisms such as Drop Tail, RED and CBQ, routing algorithms such as Dijkstra and more. NS also implements multicasting and some of the MAC layer protocols for LAN protocols for LAN simulations. The NS project is now part of the VINT project that develops tools for Simulation results display, analysis & converters that convert n/w topologies generated by well-known generators to NS formats.

CONCEPT OVERVIEW
OTcl Linkage
Ns is basically written in C++, with an OTcl interpreter as a frontend. It supports a class hierarchy in C++ , called Compiled hierarchy & a similar one within the OTcl interpreter, called interpretor hierarchy. There is a one-one correspondence between classes of these two hierarchies. The root of the hierarchy is Class TclObject. Users create new simulator objects through interpreter that are instantiated within the interpreter. The interpreted hierarchy is automatically established through methods defined in the TclClass. User instantised objects are mirrored through methods defined in Class TclObject
 

Figure 2. Otcl-C++ duality

The Need for dual Languaes
The simulator can be viewed as doing 2 different things. While on one hand detailed simulations of protocols are required, we also need to be able to vary the parameters or configurations & quickly explore the changing scenarios. For the first case we need a system programming language like C++ that efficiently handles bytes, packet headers & implement algorithms efficiently. But for the second case iteration time is more important than the run-time of the part of task. This is accomplished by a scripting language like Tcl. The manual on NS advices users to use
 

OTcl

for configuration, setup & "one-time" stuff
if existing C++ functionality is sufficient for ur requirements
and C++

if u require to process each pkt flow
if need arises to change the behaviour of existing C++ class
General Architecture of NS
Now we know that NS has got in its store many things like event scheduler, Network Components & runs with Tcl(Tool Command Language), OTcl, it would do some good to understand the way they are interlinked. NS developer can be considered working on Tcl, running simulations in Tcl using the simulator objects in OTcl library. The event scheduler & most of the components are implemented in C++ and available to OTcl through an OTcl linkage. This linkage is implemented using tclcl, a glue language. We can say NS is an OO extended Tcl interpreter with network simulator libraries.

Figure 1. user view of ns

As in the diagram, NS is Object-Oriented TCl(OTcl) script interpreter that has a simulation event scheduler and network component object libraries and network setup modules called plumbing modules. The program that runs NS is in OTcl script Language. The basic script sets up & runs a simulation of network. This initiates an event scheduler, sets up network topology using n/w objects and plumbing functions in the library and tells traffic source when to start & stop. When a user wants to make a new object, she can either write a new object from the scratch or make a compound object from the object library & plumb data through it.

A major component of NS besides n/w objects is event Scheduler. For example a packet can be considered as an event with scheduled time and pointer to an object that handles the event. All the network components that need to spend some time handling packets use the event scheduler by issuing an event for a packet. A switching component or a timer use event scheduler. Simulation results are usually got by files called 'Trace files'. When the simulation is over NS produces one or more text based output files that contain simulation data as specified in the input script. It can also be viewed using a nice graphical tool called 'Network Animator' or NAM in short.

A Brief Overview of code
The code to interface with the OTcl interpreter resides in a seperate directory, tclcl. The rest of the simulator code resides in the directory, NS-2.

Class Tcl
It encapsulates the actual instance of the actual interpreter, and provides the methods to access and communicate with that interpreter. The class provides methods for following operations

Obtain a reference to instance of Class Tcl.
Invoking OTcl procedures
passing results to the interpreter
Error reporting & exit
Hash functions within the interpreter
If the above methods provided by the interpreter is not sufficient, then we must acquire the handle to the interpreter and can write our own functions. Tcl::interep returns a handle to the interpretor that is stored within class Tcl.

Class TclObject
TclObject is the base class for most of the other classes in the interpreted and compiled hierarchies. Every object in the Class TclObject is created by the user from within the interpreter. This creates an equivalent shadow object in the compiled hierarchy. The two objects are closely associated with each other. The class TclClass creates a mechanism that performs this shadowing. An example configuration of a TclObject is like this
 

         set srm [new Agent/SRM/Adaptive]

Creation & deletion of Tcl objects are done using new and delete procedures. new[] creates an interpreted TclObject that executes the constructor for the object passing it the arguments provide by user. It also responsible for creating the compiled object. The shadow object gets created by the base class TclObject. The delete object destroys the interpreted object & corresponding shadow object

In most cases, access to compiled member variables is restricted to compiled code, and access to interpreted member variables is likewise confined to access via interpreted code; however, it is possible to establish bi-directional bindings such that both the interpreted member variable and the compiled member variable access the same data, and changing the value of either variable changes the value of the corresponding paired variable to same value. The binding is established by the compiled constructor when that object is instantiated; it is automatically accessible by the interpreted object as an instance variable. It supports five different data types: reals, bandwidth valued variables, time valued variables, integers, and booleans.
 

Command methods establish the instance procedure, cmd[] as a hook to executing methods through the compiled shadow object. The procedure cmd[] invokes the method command[] of the shadow object automatically, passing the arguments to cmd[] as an argument vector to the command[] method. The user can invoke the cmd[] method in one of two ways:

by explicitly invoking the procedure, specifying the desired operation as the first argument.
or implicitly, as if there were an instance procedure of the same name as the desired operation.
Most simulation scripts will use the latter form, hence, we will describe that mode of invocation first.
Class TclClass
This compiled class is pure virtual class. Classes derived from this base class provide two functions

construct interpreted class hierarchy to mirror the compiled class hierarchy
provide methods to provide new Tcl objects
Each such derived class is associated with a particular compiled class in the compiled class hierarchy, and can instantiate new objects in the associated class. As an example, consider a class such as the class RenoTcpClass. It is derived from class TclClass, and is associated with the class RenoTcpAgent. It will instantiate new objects in the class RenoTcpAgent. The compiled class hierarchy for RenoTcpAgent is that it derives from TcpAgent, that in turn derives from Agent, that in turn derives (roughly) from TclObject.
 RenoTcpClass is defined as
        static class RenoTcpClass: public TclClass {
        public:
                RenoTcpClass() : TclClass("Agent/TCP/Reno") {}
                TclObject* create(int argc, const char*const* argv) {
                        return (new RenoTcpAgent());
                }
        } class_reno;

Class TclCommand
This class provides just the mechanism for us to export simple commands to the interpreter, that can then be executed within a global context by the interpreter. There are two functions defined here. ns-random and ns-version. These two functions are initialized by the function init_misc, defined in misc.cc; init_misc is invoked by Tcl_AppInit during startup.
For example, With no argument, ns-random returns an integer, uniformly distributed in the interval .
When specified an argument, it takes that argument as the seed. If this seed value is 0, the command uses a heuristic seed value; otherwise,
it sets the seed for the random number generator to the specified value.

            % ns-random                 # return a random number;
            2078917053
            % ns-random 0               #set the seed heuristically;
            858190129
            % ns-random 23786           #set seed to specified value;
            23786
 

Class EmbeddedTcl permits the development of functionality in either compiled code, or through interpreter code, that is evaluated at initialization. The easiest way to extend is to add OTcl code to either tcl-object.tcl or through scripts in the tcl/lib directory.

This class InstVar defines the methods and mechanisms to bind a C++ member variable in the compiled shadow object to a specified OTcl instance variable in the equivalent interpreted object. The binding is set up such that the value of the variable can be set or accessed either from within the interpreter, or from within the compiled code at all times. There are five instance variable classes: InstVarReal../Tcl/Tcl.cc, InstVarTime../Tcl/Tcl.cc, InstVarBandwidth../Tcl/Tcl.cc, InstVarInt../Tcl/Tcl.cc, and InstVarBool../Tcl/Tcl.cc, corresponding to bindings for real, time, bandwidth, integer, and boolean valued variables respectively.

CONSTITUENTS OF SIMULATOR
The simulator is described by ns-lib.h. It provides a set of interfaces for configuring a simulation and for choosing the type of event scheduler used to drive the simulation. A simulation script generally begins by creating an instance of this class and calling various methods to create nodes, topologies, and configure other aspects of the simulation.

When a new simulation object is created in tcl, the initialization procedure init[] performs the following operations:
 

initialize the packet format (calls create_packetformat)
create a scheduler (defaults to a calendar scheduler)
create a ``null agent'' (a discard sink used in various places)
SCHEDULERS
There are presently four schedulers available in the simulator, each of which is implemented using a different data structures: a simple linked-list, heap, calendar queue (default), and a special type called ``real-time''.

The scheduler runs by selecting the next earliest event, executing it to completion, and returning to execute the next event.Unit of time used by scheduler is seconds. Presently, the simulator is single-threaded, and only one event in execution at any given time. If more than one event are scheduled to execute at the same time, their execution is performed on the first scheduled - first dispatched manner. Simultaneous events are not re-ordered anymore by schedulers (as it was in earlier versions) and all schedulers should yeild the same order of dispatching given the same input.

The four main types of schedulers are

The List Scheduler
The heap Scheduler
The Calender Scheduler
The Real-Time Scheduler
The simulator method provides a number of methods used to setup simulation. They can be clasified as

methods to create & manage topology
methods to perform tracing
helper functions to deal with scheduler
NODES And PACKET FORWARDING
Each simulation requires a single instance of the Simulator to control and operate that simulation. The class provides instance procedures to create and manage the topology, and internally stores references to each element of the topology.
The basic primitive for creating a node is

       set ns [new Simulator]
       $ns node

The instance procedure node constructs a node out of more simple classifier. The Node itself is a standalone class in OTcl. However, most of the components of the node are themselves TclObjects. This simple structure consists of two TclObjects: an address classifer (classifer_) and a port classifier (dmux_). The function of these classifiers is to distribute incoming packets to the correct agent or outgoing link.
All nodes contain at least the following components:
 

an address or id_, monotonically increasing by 1,
a list of neighbors (neighbor_),
a list of agents (agent_),
a node type identifier (nodetype_) and
a routing module
Nodes can be configured by the users themselves using one of the control functions, Address and port number management, routing functions, Agent Management and neighbor tracking functions.
The function of a node when it receives a packet is to examine the packet's fields, usually its destination address, and on occasion, its source address. It should then map the values to an outgoing interface object that is the next downstream recipient of this packet. In this task is performed by a simple classifier object. Multiple classifier objects, each looking at a specific portion of the packet forward the packet through the node. A node uses many different types of classifiers for different purposes.
A classifier provides a way to match a packet against some logical criteria and retrieve a reference to another simulation object based on the match results. Each classifier contains a table of simulation objects indexed by slot number. The job of a classifier is to determine the slot number associated with a received packet and forward that packet to the object referenced by that particular slot.

A node is essentially a collection of classifiers. The simplest node (unicast) contains only one address classifier and one port classifier. When one extends the functionality of the node, more classifiers are added into the base node, for instance, the multicast node. As more function blocks is added, and each of these blocks requires its own classifier(s),it becomes important for the node to provide a uniform interface to organize these classifiers and to bridge these classifiers to the route computation blocks.

LINKS
This is the second aspect of defining the topology.Links are used to connect the nodes and complete the topology. Apart from simple point to point links, it supports a variety of other media, including an emulation of a multi-access LAN using a mesh of simple links, and other true simulation of wireless and broadcast media.
    set ns [new Simulator]
    $ns simplex-link {node0} {node1} {bandwidth} {delay} {queue_type}

The command creates a link from node0 to node1, with specified bandwidth and delay characteristics. The link uses a queue of type queue_type. The procedure also adds a TTL checker to the link. Five instance variables define the link- namely head, queue, link, ttl,drophead.
The instance variables enqT, deqT, drpT, rcvT track the trace elements. Delays represent the time required for a packet to traverse a link. A special form of this object (``dynamic link'') also captures the possibility of a link failure. The amount of time required for a packet to traverse a link is defined to be speed of the link in bits/sec, and is the link delay in seconds. The implementation of link delays is closely associated with the blocking procedures.
 

QUEUE MANAGEMENT and PACKET SCHEDULING
Queues represent locations where packets may be held (or dropped). Packet scheduling refers to the decision process used to choose which packets should be serviced or dropped. Buffer management refers to any particular discipline used to regulate the occupancy of a particular queue. At present, support is included for drop-tail (FIFO) queueing, RED buffer management, CBQ (including a priority and round-robin scheduler), and variants of Fair Queueing including, Fair Queueing (FQ), Stochastic Fair Queueing (SFQ), and Deficit Round-Robin (DRR). In the common case where a delay element is downstream from a queue, the queue may be blocked until it is re-enabled by its downstream neighbor. This is the mechanism by which transmission delay is simulated. In addition, queues may be forcibly blocked or unblocked at arbitrary times by their neighbors (which is used to implement multi-queue aggregate queues with inter-queue flow control). Packet drops are implemented in such a way that queues contain a ``drop destination''; that is, an object that receives all packets dropped by a queue. This can be useful to (for example) keep statistics on dropped packets.
The Queue class is derived from a Connector base class. It provides a base class used by particular types of (derived) queue classes, as well as a call-back function to implement blocking.

AGENTS
Agents represent endpoints where network-layer packets are constructed or consumed, and are used in the implementation of protocols at various layers. The Agent has an implementation partly in OTcl and partly in C++. The C++ internal Agent includes enough internal state to assign various fields to a simulated packets before its sent. The state includes the following
addr-the node address, dst-where pkts are sent to, size, type-the type of the packet, fid-the flow identifier, prio-the IP priority field, flags-packet flags, defttl-default ip TTL. Agent supports packet generation & reception. The common agent mathods are meant to allocate packets,recieving the pkts, specifying timeout methods.

The above described ones are the most basic constituents of NS. NS supports many things like

                Differentiated Services
                LAN specific support
                Mobile Networking in NS
                Satelite Networking in NS
                Radio Propogation Model
                Energy Models
                Debugging & monitoring support.

A SAMPLE SCRIPT
We can write your Tcl scripts in any text editor like joe or emacs. Let this be 'example1.tcl'.
First of all, we need to create a simulator object. This is done with the command
 

                set ns [new Simulator]
 

The second step is opening a file for writing the trace to. It could be a normal trace file or a nam trace file.
 

                set nf [open out.nam w]
                $ns namtrace-all $nf
 

The first line opens the file 'out.nam' for writing and gives it the file handle 'nf'. The second line tells that simulator object that we created above to write all simulation data that is going to be relevant for nam into this file. The following two lines define the two nodes.
 

                set n0 [$ns node]
                set n1 [$ns node]
 

A new node object is created with the command '$ns node'. The above code creates two nodes and assigns them to the handles 'n0' and 'n1'. The next line connects the two nodes.
 
 

                $ns duplex-link $n0 $n1 1Mb 10ms DropTail
 

This line tells the simulator object to connect the nodes n0 and n1 with a duplex link with the bandwidth 1Megabit,
a delay of 10ms and a DropTail queue.

The next step is to add a 'finish' procedure that closes the trace file and starts nam.
 

                proc finish {} {
                        global ns nf
                        $ns flush-trace
                        close $nf
                        exec nam out.nam &
                        exit 0
                }
 

The procedure finish() flushes all the trace data & executes nam. Here again flush-trace is a procedure called on handle ns.

The next line tells the simulator object to execute the 'finish' procedure after 5.0 seconds of simulation time.

                $ns at 5.0 "finish"
 

The last line starts the simulation
 $ns run
 
 

The idea given about NS in this document is very elementry & by no means indepth. For a detailed and exhaustive reference
refer to the NS manual  http://www.isi.edu/nsnam/ns/doc/everything.html