104
Technion, Department of Electrical Engineering Networked Software Systems Laboratory Project Book Wireless Sensor Network for Tracking the Congestion in INTERNET Network Routers Part 2

Table of Figures - nssl.eew.technion.ac.ilnssl.eew.technion.ac.il/files/Projects/2008Winter/Wireles…  · Web viewLoad Balancing Algorithm9. NS-2 Tcl ... supplied here and this

  • Upload
    vandung

  • View
    213

  • Download
    0

Embed Size (px)

Citation preview

Technion, Department of Electrical EngineeringNetworked Software Systems Laboratory

Project Book

Wireless Sensor Network for Tracking the

Congestion in INTERNET Network Routers

Part 2

Students: Yuri Kipnis 311913289Nir Bar-Or 041956558

Supervisor: Mark Shifrin

Semester: Spring 2009Date: September, 2009

The Technion Electrical Engineering Networked Software Systems Laboratory

Table of ContentTable of Content.........................................................................................2Table of Figures..........................................................................................4Abbreviations.............................................................................................5Introduction................................................................................................6

Development Environment.....................................................................7NS-2....................................................................................................7FEDORA-9, Sulphur..........................................................................7Matlab.................................................................................................7TCL....................................................................................................7

Theoretical Background.........................................................................8Load Balancing Algorithm.....................................................................9

NS-2 Tcl commands.........................................................................16Trace files.............................................................................................18

Simulation Design....................................................................................19Files Structure.......................................................................................19Global Variables...................................................................................20Data Structures.....................................................................................21Routers network procedures.................................................................22

LoadDistribution module:................................................................22ParseTraceLine.................................................................................22ResetFlowsDS..................................................................................22ResetDropsDS..................................................................................22ProduceShortestPathTree.................................................................22CountBottleNeck..............................................................................23ChangeFlowPath..............................................................................23CanRemove......................................................................................23GetPath.............................................................................................24GetSourcesList.................................................................................24NewSPTPath....................................................................................24IsDestination.....................................................................................24RecursiveDFS...................................................................................25GetDropsOn......................................................................................25GetSentOn........................................................................................25CanImprove......................................................................................25LoadDistributionAlgorithm..............................................................26Bellmann-Ford_SPT module:...........................................................26RunBellmanFord..............................................................................26InitGraph..........................................................................................26

2

The Technion Electrical Engineering Networked Software Systems Laboratory

RelaxEdges.......................................................................................26BuildShortestPathTree......................................................................27SetNetworkRoutingMap module:.....................................................27BuildRoutes_ROUTERS..................................................................27ScheduleNetworkSimulation............................................................27TestLoadDistribution module:.........................................................27TestSPT............................................................................................27TestFlowsDS....................................................................................27TestDropsDS....................................................................................28TestLoadMap....................................................................................28TestPrintNewFlow............................................................................28

Simulations...........................................................................................29Conclusions......................................................................................44

Summary..................................................................................................46What is Next?...........................................................................................47

Appendix A – Simulation code............................................................48References................................................................................................74

Books....................................................................................................74Websites...............................................................................................74

3

The Technion Electrical Engineering Networked Software Systems Laboratory

Table of Figures

Figure 1 – The first simulation’s topology...............................................29Figure 2 - packet loss rate, CWND and average CWND for flow 0->5. .30Figure 3 - packet loss rate, CWND and average CWND for flow 1->5. .31Figure 4 - packet loss rate, CWND and average CWND for flow 2->5. .31Figure 5 - packet loss rate, CWND and average CWND for flow 3->5. .32Figure 6 - packet loss rate, CWND and average CWND for flow 4->5. .32Figure 7 - The second simulation's topology............................................34Figure 8 - packet loss rate, CWND and average CWND for flow 0->3. .36Figure 9 - packet loss rate, CWND and average CWND for flow 0->4. .36Figure 10 - packet loss rate, CWND and average CWND for flow 1->2 37Figure 11 - packet loss rate, CWND and average CWND for flow 2->5 37Figure 12 - packet loss rate, CWND and average CWND for flow 6->7 38Figure 13 - packet loss rate, CWND and average CWND for flow 4->9 38Figure 14 - packet loss rate, CWND and average CWND for flow 5->4 39Figure 15 - The third simulation's topology.............................................40Figure 16 - packet loss rate, CWND and average CWND for flow 0->3 41Figure 17 - packet loss rate, CWND and average CWND for flow 0->4 42Figure 18 - packet loss rate, CWND and average CWND for flow 5->3 42Figure 19 - packet loss rate, CWND and average CWND for flow 5->4 43

4

The Technion Electrical Engineering Networked Software Systems Laboratory

Abbreviations

NS-2 - Network simulator used in this project

Tcl - script language used in this project

WSN - Wireless Sensor Network

BFA - Bellman-Ford Algorithm

SPT - Shortest Path Tree

CS - Wireless Sensor Network Central Station

RT – Routing Table

5

The Technion Electrical Engineering Networked Software Systems Laboratory

Introduction

In today's world where information is priceless and the always-going chase after information availability is surrounding us, the efficiency and cost of the networks take a crucial part in the network design and feasibility.

Our solution: building a system that will allow us to test the WSN idea on all types of network structure, routing protocols, any number of sensors and/or routers and even different algorithms of load distribution (will be referred in this article as load-distribution-algorithm) and do all that in our computer without the need of building anything.

The first part of our project was to build a platform that enable us to generate any type of router network that is well connected, routed and we can control its data traffic. In the second part of the project we have added the platform the ability to run a load-balancing algorithm that will decide about the modification to be made in the network in order to ease the load on specific link and by that improve the network’s performance. We also added an output processing mechanism so a user could parse the files more easily. Also many trials have been made and several algorithms have been implemented, tested and disposed for not giving the results.

By the end of the project we had a strong, reliable platform and an implemented and debugged load-balancing algorithm that we have tested, processed its output and concluded its results.

Our tests just hit the tip of the iceberg, more profound researches can be made with the tools that we have supplied here and this system should be used in the future by anyone who wants to test a certain aspect in the network world.

The following chapters will elaborate more about the technical aspect of the project and our findings.

6

The Technion Electrical Engineering Networked Software Systems Laboratory

Development Environment

NS-2NS or Network Simulator is a discrete event network simulator, meaning that the sequence is divided to chronological time units and each time unit will hold one or more events that will be performed.

NS is an open source model implemented mainly in C++ and provides a simulation interface through O-Tcl/TCL script languages. NS also has plentiful online documentation and those are the reasons for its wide use in academia.

FEDORA-9, SulphurFedora is a general porpuse operating system built on top of a linux kernel, developed by community-supported Fedora-Project sponsored by Red Hat.Fedora9, codenamed Sulphur, was released in 13/5/2008 and presents a windows-like interface.

MatlabMatlab is a numerical computing environment and fourth generation programming language. Developed by The MathWorks, MATLAB allows matrix manipulation, plotting of functions and data, implementation of algorithms, creation of user interfaces, and interfacing with programs in other languages (Wikipedia definition).

TCLTool Command Language is a very powerful and easy to learn scripting language, often referred to as a programing language. TCL is widely used for scripted applications, GUI (Tcl/Tk), testing and file processing.TCL is also used as the API for NS.

7

The Technion Electrical Engineering Networked Software Systems Laboratory

Theoretical Background

In computer networking, load balancing is a method to distribute workload (i.d. number of packets being sent/received) evenly across the network in order to get optimal resource utilization, maximum throughput, minimal response time and minimal overload.

We have tried to prove/refute this idea by using widely known techniques and algorithm to simulate the problem and it solutions.

We have set a specific definition for how to know what is a link’s load and it reasonable values. We also used the Bellman-Ford algorithm to find the shortest links (in terms of “short” being “with a low value of load”) and developed and implemented our own algorithm to decide which Bellman-Ford suggestions to take into account and alter the routing table to match our decisions.

The Bellman-Ford algorithm computes single-source shortest paths to multiple destinations in a weighted graph. Though the complete Bellman-Ford algorithm can also deal with negative weighted edges we have not dealt with that issue assuming there can be no negative load on an edge.

In the course of our calculations we are constructing a Shortest Path Tree. A Shortest Path Tree is a graph, based on a weighted graph, constructed so that the distance between each node and the root is minimal. It also obeys all other tree graph definitions (no two paths from u to v, etc.).

8

The Technion Electrical Engineering Networked Software Systems Laboratory

Load Balancing Algorithm

In our days, there is no generic load balancing algorithm for networks that can run in polynomial time. Moreover, there is no mechanism that allows gathering of load information from the whole network. At first part of this project the WSN platform simulation has been built, this platform allows gathering the load information in real time and transferring this information to the network stations. At this way every station has a picture of load in the whole network and can use this for its own purposes.At this time point each station can run load balancing algorithm to improve the streaming of TCP packets from itself to all destination stations.

The main idea of our load balancing algorithm is:1. Counting the shortest path from source to destination by Bellman-

Ford algorithm for SPT.2. For each path in the SPT: if the last node is a destination of the root

in routing table then calculate the load on current path and on the new path.

3. Update this path by changing an old one by new one; add new edges, move edges that are not used by other flows that don’t contain the first station of old path. We need this separation to avoid cutting of another flows that use some part of the old path.

The metric in our algorithm is a number of packets that enters to the station queue.

The maximal path defined as a path that has edge with biggest number of packets that enters the station queue.

This algorithm runs for all the stations in the network periodically.

9

The Technion Electrical Engineering Networked Software Systems Laboratory

Algorithm:

For each node do:1. Create SPT for node2. newFlow list <- empty3. Go pre-order on the SPT, for each newPath do:

3.1Is the last node in new path is a destination in RT of first node?3.1.1 No, return 3.1.2 Yes

3.1.2.1 Calculate currPath between first node of newPath and the last node of newPath

3.1.2.2 Get all flows that use currPath and have destination identical to newPath last node

3.1.2.3 Calculate the bottleneck of all this flow on old path3.1.2.4 Is the current bottleneck on newPath plus

calculated bottleneck lower than the total bottleneck on oldPath? 3.1.2.5.1 No, return3.1.2.5.2 Yes, add edges of newPath, remove

edges that are not used in other flows that don’t contain first node of newFlow.

4. Go to 1

10

The Technion Electrical Engineering Networked Software Systems Laboratory

Example:

Assume that the network topology is looks like the following one:

At the first iteration the Load Balancing Algorithm will run on node 0. Two changes will be performed:

Change from 0 1 2 4 to 0 5 4:

11

The Technion Electrical Engineering Networked Software Systems Laboratory

Change from 0 1 2 3 to 0 5 3

After that the algorithm will run on node 1. Two additional changes will be performed:

Change from 1 2 4 to 1 4

12

The Technion Electrical Engineering Networked Software Systems Laboratory

Change from 1 2 3 to 1 3

When algorithm runs on nodes 2, 3, 4 any changes will not be performed.Finally the algorithm runs on node 5. Two additional changes are performed:

Change from 5 1 2 4 to 5 4

13

The Technion Electrical Engineering Networked Software Systems Laboratory

Change from 5 1 2 3 to 5 3

At this stage the first iteration has been finished.

At the second iteration, the algorithm will perform two changes on node 0:

Change from 0 5 4 to 0 4

14

The Technion Electrical Engineering Networked Software Systems Laboratory

Change from 0 5 3 to 0 3

At this example, algorithm has reached the shortest path between all of network nodes. No additional changes will be performed by the Load Balancing Algorithm.

15

The Technion Electrical Engineering Networked Software Systems Laboratory

NS-2 Tcl commands

Array commands:

array unset – Delete arraySyntax: array unset arrayName ?pattern?

array names – Returns a list containing the names of all of the elements in the arraySynax: array names arrayName ?mode? ?pattern?

info exists - Returns 1 if the variable named varName exists in the current context, 0 otherwise.Syntax: info exists varName

List commands:

list - Create a listSyntax: list ?arg arg ...?

lindex – Retrieve an element from a listSyntax: lindex list ?index...?

llength – Count the number of elements in a listSyntax: llength list

lreplace - Replace elements in a list with new elementsSyntax: lreplace list first last ?element element ...?

lappend - Append list elements onto a variableSyntax: lappend varName ?value value value ...?

lassign - Assign list elements to variablesSyntax: lassign list varName ?varName ...?

lrange – Return one or more adjacent elements from a listSyntax: lrange list first last

linsert - Insert elements into a listSyntax: linsert list index element ?element element ...?

16

The Technion Electrical Engineering Networked Software Systems Laboratory

Link commands:

link – crates new link between two nodesSintax: link nodeID1 nodeID2

trace-callback – adds a procedure to trace notify, this procedure will be invoked on the trace eventSintax: link trace-callback procedure_ name trace cwnd_ - performs tracing of CWND for tcp agentSintax: tcp_agent trace cwnd_

Other:

split – Split a string into a proper Tcl listSyntax: split string ?splitChars?

source – Evaluate a file or resource as a Tcl scriptSyntax: source fileName

17

The Technion Electrical Engineering Networked Software Systems Laboratory

Trace files

In this simulation we have used number of trace files for tracing network flow and storing simulation results.

traceAll.tr – contains trace information about all messages that has been sent in router network. The entries in this file are built by the standard convention of NS-2 trace file format.

qmonitor.tr – contains information about messages that has been captured by sensor monitors and by the central station.

cwnd.tr – This file contains information about the CWND size in TCP protocol of links in Routers Network. This information gathered by CWND trace object that will be described later. All of changes in CWND size for all network links are included in the order of size changes occurrences. Line format: Time From N/A To N/A “cwnd_” CWNDsize

packetLossRate.tr – This file contains information about packet loss rate in the Routers Network. There are two measure parameters are included: 1. Number of dropped packets from the queue out of arrived packets to the queue in 100 ms and the average percentage of packets dropped at last 100 ms. Line format: FromTo IterationNumber Dropped/Arrived PercentageValue

output.dat – This file contains information about changes in routing tables. It is a stdout stream of the simulation.Line format: User-friendly textual format

18

The Technion Electrical Engineering Networked Software Systems Laboratory

Simulation Design

Files StructureThis simulation contains 5 modules - script code files. Each one has its own responsibility for one of the simulation module. Follow the “Simulation Procedures” section for full description of modules’ functions.

1. SimulationScript2.tcl – This module has two main responsibilities: building the simulation infrastructure – routers and WSN networks and definition of simulation scheduler. This file widely described in the first part of the project and its procedures and data structures are not described in this part (except special cases).

2. LoadDistribution.tcl – This module responsible for load balancing algorithm. This maintenance the auxiliary data structures and manipulates the routing tables in stations of Routers Network.

3. Bellmann-Ford_SPT.tcl – This module responsible for

implementation of Bellman-Ford algorithm for building the shortest path tree. This algorithm is used for load balancing in Load Distribution module.

4. SetNetworkRoutingMap.tcl – This module is responsible for configuring the Routers Network topology and creating of initial routing tables.

5. TestLoadDistribution.tcl – This module is responsible for gathering information by representation of data structures in this simulation, tracing and debugging during development process.

19

The Technion Electrical Engineering Networked Software Systems Laboratory

Global Variables

There are widely used global data structures and global configuration parameters in this simulation. All of these are used for data management during the simulation.

Variable Name Descriptionns_ instance of the simulation objecttrace_cwnd channelID of cwnd.trtrace_drop channelID of packetLossRate.trnewFlow Auxiliary list that contains nodes

ID of stations that belongs to some flow.

firstTime Auxiliary Boolean variable sized array. Contains true for flows that already has been checked by load balancing algorithm.

old_network_path This list contains node IDs of existed path in the flow order. This is the path that the load balancing algorithm is trying to change to new_SPT_path.

new_SPT_path This list contains node IDs of existed path in the flow order. This is the path that the load balancing algorithm is trying route instead of old_network_path.

listOfSources Auxiliary list that contains sources stations for router in Routers Network

firstTime Auxiliary list is used for pre-order trip on the SPT

auxPath An auxiliary list that represents a path between two nodes, the last node is the destination node of flow in the network.

20

The Technion Electrical Engineering Networked Software Systems Laboratory

Data Structures

SPT – tree data structure. This data structure contains the Shortest Path Tree that has been generated by Bellman-Ford algorithm.

1. SPT(“root”) – contains the nodeID in the tree root. Note: “root” – is a string.

2. SPT(nodeID) – contains a list of the following format: {PREV_ID, NEXT_ID1, NEXT_ID2, …}PREV_ID – The ID of the parent, -1 for rootNEXT_ID – The ID of child. If there is more than one child, several NEXT_IDs will appear. At the leaf nodes there will be no NEXT_ID fields, these nodes will have only PREV_ID field.

loadMap - Array that contains the load between two stations that are connected by link in Routers Network according to gathered (by WSN) information. The array index has the following format: (from,to).

dropsDS and flowsDS – The first one contains dropped from the queue packets per link, the second one contains number of arrived to the queue packets except acks.The arrays, the index of each element in these array has the following format: (sourceID,destinationID,immidiateSourceID,immidiateDestinationID)sourceID – nodeID of the flow source.destinationID – nodeID of the flow destination.immidiateSourceID – nodeID of the link source.immidiateDestinationID – nodeID of the link destination.

21

The Technion Electrical Engineering Networked Software Systems Laboratory

Routers network procedures

The simulation implementation contains procedures that implement the load balancing algorithm. There are, also, number of test and output procedures.

LoadDistribution module:

ParseTraceLineParameters: trace_line – the communication trace event

information Return: NoneDescription: This procedure fills the flowsDS and dropsDS

according to the communication trace information.NS-2 tools: This uses: link trace-callback command

ResetFlowsDSParameters: NoneReturn: Empty flowsDSDescription: Resets the flowsDS data structure

ResetDropsDSParameters: NoneReturn: Empty dropsDSDescription: Resets the dropsDS data structure

ProduceShortestPathTreeParameters: sourceIndex – the nodeID of station in Routers

NetworkReturn: NoneDescription: Creates SPT for sourceIndex station. This procedure

uses methods of Bellman-Ford_SPT method.

22

The Technion Electrical Engineering Networked Software Systems Laboratory

CountBottleNeckParameters: flow – flow in Router NetworkReturn: flowBottleNeck – the bottleneck of the flowDescription: This procedure counts the flow bottleneck

ChangeFlowPathParameters: old_network_path – an existed flow in the Routers

Network that going to be changednew_SPT_path – the flow that going to change the currentFlow

Return: NoneDescription: This procedures changes flows from currentFlow to

newFlow

CanRemoveParameters: curr – the nodeID of head in the path

from – the node ID of station in the pathdst – the destination node ID in the path

Return: true – if the link can be removed, false - otherwiseDescription: This procedure recognizes other flows that use the link

that going to be deleted. It checks these flows to stay available after this deleting.

23

The Technion Electrical Engineering Networked Software Systems Laboratory

GetPathParameters: from – node ID of the head station

dst – node ID of the destination stationReturn: auxPath – the path between ‘from’ and ‘dst’ nodes,

whet the ‘dst’ is a destination of some flow in the network.

Description: This procedure gets the path between two nodes, when the second one is a destination node of some flow in the network.

GetSourcesListParameters: from – the node of station in the network

dst – the node ID of destination station in the networkReturn: listOfSources - the list that contains all sources node

IDs of stations that contain node ‘from’ in its’ path and the have destination node - ‘dst’.

Description: Gets all sources of flows that contain path ‘from’ – ‘dst’ and the destination of flows is ‘dst’.

NewSPTPathParameters: old_network_path – an existed flow in the Routers

Network that going to be changednew_SPT_path – the flow that going to change the currentFlow

Return: NoneDescription: This procedure changes an old_network_path by the

new_SPT_path if this change will improve the network flow.

IsDestinationParameters: from – nodeID in the network

dst - nodeID in the networkReturn: True – if the ‘dst’ is the destination node in the ‘from’

node routing table.Description: This procedure checks the routing table of ‘from’ and

searching in this table for destination ‘dst’

24

The Technion Electrical Engineering Networked Software Systems Laboratory

RecursiveDFSParameters: currentNodeID – the node ID of the node currently

visited by DFS.indexInNodeList – the index of child in the list of nodes children.

Return: NoneDescription: This procedure goes over all available paths in the SPT

by pre-order and tries to improve existed flows in the Routers Network by flows from SPT.

GetDropsOnParameters: src – node ID of station

dst – node ID of stationReturn: dropped – number of dropped packets on the flow

between from and to stationsDescription: This procedure counts the number of dropped packets

on the flow. It is uses dropsDS data structure

GetSentOnParameters: src – node ID of station

dst – node ID of stationReturn: arrived – number of arrived packets on the flow

between from and to stationsDescription: This procedure checks the number of sent packets

between the source of the flow and the first node in this flow. is uses flowsDS data structure

CanImproveParameters: old_network_path – an existed flow in the Routers

Network that going to be changednew_SPT_path – the flow that going to change the currentFlow

Return: true – if a new_SPT_path should to came instead of old_network_path in the Routers Network, false - otherwise

Description: This procedure compeer the worst bottleneck of flows

25

The Technion Electrical Engineering Networked Software Systems Laboratory

that contain the old_network_path in it and the worst bottleneck of flows if it will contain new_SPT_path in it.

LoadDistributionAlgorithmParameters: nodeID – the node ID of station in Routers NetworkReturn: NoneDescription: This procedure runs the load balancing algorithm for

nodeID station

Bellmann-Ford_SPT module:

RunBellmanFordParameters: src – The node which will be the root of the entire tree.Return: The function itself doesn’t have a return value but

instead it constructs a global variable named shortest_paths_array. This is variable is used later on by BuildShortestPathTree to construct the SPT.

Description: Runs the Bellman-Ford algorithm on the src node according to the data stored in the global variables node_ROUTER and loadMap.

InitGraphParameters: src - The index of the root node in the tree.Return: NoneDescription: Initializes the shortest_paths_array as the first stage in

the Bellman-Ford algorithm. Sets all loads in the tree to INFINITY and all the predecessors to NA

RelaxEdgesParameters: src – The index of the root node in the tree.Return: NoneDescription: Performs this check for each edge:

For each edge uv, if the distance to u.distance + uv.distance < v.distance than v.distance = u.distance + uv.distance and v.predecessor = uThis is performed |V| times (where |V| is the number of

26

The Technion Electrical Engineering Networked Software Systems Laboratory

routers in the network)

BuildShortestPathTreeParameters: src – Then index of the root node in the tree.Return: NoneDescription: Constructs the SPT from the shortest_paths_array. The

detailed structure of SPT is elaborated above.

SetNetworkRoutingMap module:

BuildRoutes_ROUTERSParameters: Type – the simulation typeReturn: NoneDescription: This procedure responsible for building routing tables

in Routers Network.

ScheduleNetworkSimulationParameters: Type – simulation typeReturn: NoneDescription: This procedure responsible for definition of active

flows in Routers Network.

TestLoadDistribution module:

TestSPTParameters: NoneReturn: NoneDescription: Prints SPT to stdout

TestFlowsDSParameters: NoneReturn: NoneDescription: Prints flowsDS to stdout

27

The Technion Electrical Engineering Networked Software Systems Laboratory

TestDropsDSParameters: NoneReturn: NoneDescription: Prints dropsDS to stdout

TestLoadMapParameters: NoneReturn: NoneDescription: Prints loadMap to stdout

TestPrintNewFlowParameters: NoneReturn: NoneDescription: Prints newFlow to stdout

28

The Technion Electrical Engineering Networked Software Systems Laboratory

Simulations

A lot of simulations have been run by using load balancing algorithm.This algorithm was examined by simulation with different topology, number of nodes, different flows, by service tempo of network hardware and size of queue in network device. Important note: the order of LBA running during iteration is the increasing order of nodes indexes.We will represent here two simulations, we will compare between results of simulation that use the algorithm to one that doesn’t do it.

Simulation 1:The purpose of this simulation is demonstration of the load balancing algorithm principles. At this simulation we use queue size - 4, service tempo – 0.5 Mb.Topology:

29

The Technion Electrical Engineering Networked Software Systems Laboratory

Figure 1 – The first simulation’s topology

Results:In this simulation we can observe that after the convention of LBA, each station will be connected to station 5 directly. At the following table all the changes that have been performed during simulation are mentioned:

1: Change from 0 1 2 3 4 5 to 0 51: Change from 1 2 3 4 5 to 1 51: Change from 2 3 4 5 to 2 51: Change from 3 4 5 to 3 1 52: Change from 3 1 5 to 3 5

We achieved the convention after two iterations. There are no more paths to improve.

30

The Technion Electrical Engineering Networked Software Systems Laboratory

There is correlation between load balancing and the packet loss rate. When the load balancing is optimal the packet loss rate is minimal. When the load balancing is bad the packet loss rate grows.On the following graphs we can compare between packet loss rate, CWND and average CWND when the simulation uses the LBA and without using it for different TCP links.

Flow 0 5:

Figure 2 - packet loss rate, CWND and average CWND for flow 0->5

31

The Technion Electrical Engineering Networked Software Systems Laboratory

Flow 1 5:

Figure 3 - packet loss rate, CWND and average CWND for flow 1->5

Flow 2 5:

Figure 4 - packet loss rate, CWND and average CWND for flow 2->5

32

The Technion Electrical Engineering Networked Software Systems Laboratory

Flow 3 5:

Figure 5 - packet loss rate, CWND and average CWND for flow 3->5

Flow 4 5:

Figure 6 - packet loss rate, CWND and average CWND for flow 4->5

33

The Technion Electrical Engineering Networked Software Systems Laboratory

For all flows we can see the same trend in LBA graphs: 1. The packet loss rate becomes smaller after two iterations – the

percentage of dropped packets becomes fewer.2. The average CWND becomes greater after two iterations – there

more packets can be sent on the flows.According to these graphs we succeed to improve the network flow in this topology.

34

The Technion Electrical Engineering Networked Software Systems Laboratory

Simulation 2:

The purpose of this simulation is demonstration of dynamic changes in the network that caused by the load balancing algorithm. We also will see that not all flows can be benefit from this algorithm. At this simulation we use queue size - 4, service tempo – 0.5 Mb.Topology:

Figure 7 - The second simulation's topology

35

The Technion Electrical Engineering Networked Software Systems Laboratory

Results:This is more complicated topology. In this topology we don’t observe that the LBA will choose direct connections as the shortest paths, because there are other flows go over these direct connections. Moreover there are many changes are performed during each iteration, these changes create new topology and cause for changes at the next iteration, in order to get preferred topology.

The following list represents a part of changes that have been done during the simulation:

2: Change from 2 5 to 2 6 52: Change from 2 5 3 to 2 32: Change from 4 7 5 to 4 52: Change from 5 3 to 5 0 32: Change from 6 2 to 6 4 22: Change from 6 1 7 to 6 9 72: Change from 7 9 2 to 7 23: Change from 0 3 8 to 0 83: Change from 0 3 to 0 8 33: Change from 2 6 5 to 2 53: Change from 3 5 to 3 9 53: Change from 5 0 3 to 5 33: Change from 6 9 7 to 6 1 74: Change from 0 8 3 to 0 34: Change from 0 8 to 0 3 84: Change from 3 9 5 to 3 54: Change from 4 5 to 4 7 54: Change from 5 4 to 5 8 44: Change from 5 3 to 5 0 34: Change from 6 1 7 to 6 9 74: Change from 8 3 to 8 6 3

This simulation also shows that there is correlation between load balancing and the packet loss rate. Contrary to the previous simulation, in this simulation we can see that there are links that have been loaded by the LBA in order to perform balancing with other flows. It increased the packet loss rate on loaded links (for example: flow 6 - 7), but decreased the packet loss rate on other flows (for example: flow 4 - 9).Here we will represent a part of flows graphs that have been generated during this simulation.

36

The Technion Electrical Engineering Networked Software Systems Laboratory

Flow 0 3:

Figure 8 - packet loss rate, CWND and average CWND for flow 0->3

Flow 0 4:

Figure 9 - packet loss rate, CWND and average CWND for flow 0->4

37

The Technion Electrical Engineering Networked Software Systems Laboratory

Flow 1 2:

Figure 10 - packet loss rate, CWND and average CWND for flow 1->2

Flow 2 5:

Figure 11 - packet loss rate, CWND and average CWND for flow 2->5

38

The Technion Electrical Engineering Networked Software Systems Laboratory

Flow 6 7:

Figure 12 - packet loss rate, CWND and average CWND for flow 6->7

Flow 4 9:

Figure 13 - packet loss rate, CWND and average CWND for flow 4->9

39

The Technion Electrical Engineering Networked Software Systems Laboratory

Flow 5 4:

Figure 14 - packet loss rate, CWND and average CWND for flow 5->4

40

The Technion Electrical Engineering Networked Software Systems Laboratory

Simulation 3:

The purpose of this simulation is demonstration of a network with reach resources that will not benefit from this algorithm by decreasing the packet loss factor but it will benefit from the aspect of CWND window size – number of packets that can be send ”simultaneously”. At this simulation we use queue size - 60, service tempo – 5 Mb.

Topology:

Figure 15 - The third simulation's topology

Results:

The following list represents a part of changes that have been done during the simulation:

1: Change from 0 1 2 4 to 0 5 41: Change from 0 1 2 3 to 0 5 31: Change from 1 2 4 to 1 41: Change from 1 2 3 to 1 31: Change from 5 1 2 4 to 5 41: Change from 5 1 2 3 to 5 3

41

The Technion Electrical Engineering Networked Software Systems Laboratory

2: Change from 0 5 4 to 0 42: Change from 0 5 3 to 0 3

This topology has been changed to direct links during 2 simulations.

At this simulation we observe to network traffic without dropped packets, this will cause the big CWND and a good performance. At this case the load balancing algorithm will change the topology but will not change the number of dropped packets, it is a very low parameter anyway.

Flow 0 3:

Figure 16 - packet loss rate, CWND and average CWND for flow 0->3

42

The Technion Electrical Engineering Networked Software Systems Laboratory

Flow 0 4:

Figure 17 - packet loss rate, CWND and average CWND for flow 0->4

Flow 5 3:

Figure 18 - packet loss rate, CWND and average CWND for flow 5->3

43

The Technion Electrical Engineering Networked Software Systems Laboratory

Flow 5 4:

Figure 19 - packet loss rate, CWND and average CWND for flow 5->4

In this simulation we can see that the packet loss factor is irrelevant. On the other hand we see that the CWND window grows faster on the graphs where the algorithm has been used. In the simulation without algorithm the link between nodes 1 and 2 has been used by 4 flows. Every flow used just a part of it, so the growth of CWND is slow relatively. In the simulation with LBA every flow has got a separate link after 2 iterations, so every flow can send more packets to its destination. As a result the CWND grows faster and the number of sent packets is greater.

44

The Technion Electrical Engineering Networked Software Systems Laboratory

Conclusions

A reach analysis was performed on different simulations that included various sets of network parameters like queue size, service tempo, duration and topology. There are number of conclusions that we have done:

1. Load balancing algorithm increases the network performance in networks with relatively rare number of flows. The improvement depends on network resources, like queue size and service tempo. If there is no lack of resources in network, the percentage of lost packets is very small anyway. At this case there will no dramatic improvement. But when the resources are limited, the network will benefit a lot from the Load Balancing Algorithm.

2. Load balancing algorithm increases the network performance in networks with limitations in queue size and service tempo. The improvement will be relevant for rare flow networks and for rich flow networks as well.

3. Load balancing algorithm increases the performance in part of flows in complicated networks that have a big number of flows and common links for different flows. This algorithm decreases a performance for other flows in complicated networks. This is caused by the fact that the algorithm wants to balance the load between different links. At this way the links that has been loaded at the start point of algorithm running will over it’s load to other – not loaded links. This will give a benefit to initially loaded links. On the other hand, there are not loaded links at the start point of algorithm running. Those will get load from initially loaded links as a result of algorithm. We can conclude that as mach free resources (links) the network has, as bigger will be the network benefit from Load Balancing Algorithm.

4. Networks with relatively big parameters of queue size and service tempo that not suffers from the resources lack will not benefit from this algorithm in aspect of packet loss rate but in aspect of flow capacity. Even, if there are no dropped packets on link, the link is shared by number of network flows. As less the number of flows will be, as more packets will be send on particular flow. At this

45

The Technion Electrical Engineering Networked Software Systems Laboratory

way the CWND will grows faster and the flow capacity will be bigger.

5. According to both parts of the project we can conclude that the congestion control in wired network is possible through wireless network. Moreover, it can be done by in depended network like WSN by using special algorithms for improvement the network performance.

46

The Technion Electrical Engineering Networked Software Systems Laboratory

Summary

The goal of this project was to analyze an idea of allowing congestion control in wired network by signaling from wireless network.

We have already analyzed the reached results and discussed the conclusions. As a result of our work, we can conclude that the congestion control in wired network is available by using wireless sensor network that runs load balancing algorithm. Actually, the load balancing algorithm can be used by routers trough web services or to be an integrated part of the router driver. Moreover, there can be defined a new well defined protocol based on the Load Balancing Algorithm that allows updating of routing tables in the network “on the fly”.

There are number of added outputs from this project. The main output, second to the project’s goal, is that we have established a system that allow any developer to implement a specific network, load balancing algorithm and, if needed, specific output processing and test it and by that free the developer from any programming! This project is basically a platform for future researches investigating networks and routing algorithms.

Additionally, the papers written for this project should be used as a database for any developer planning on using NS2. In the course of this project we have tried a lot of different communication types and dug into the core of the monitoring and tracing mechanisms in NS2. A researcher that has set his mind not to modify and deal with the C++ code behind NS2 will find our documentations and articles very helpful.A word of caution: Different versions of NS and NAM provide different results and mechanisms. To effectively use our code and tips make sure you use the same versions as appear in these documents.

47

The Technion Electrical Engineering Networked Software Systems Laboratory

What is Next?

There are number of available directions for future research: Using of satellite communication instead of wireless

communication between WSN stations and central station. Investigation of the new algorithms for improving the network

performance.

Though this project is done it is well documented in order to ease other developers and researchers to pick up where we left. Using the documentation both in the book and in the files one should be able to use and edit the project and its modules.

So, next is defined only by the readers of this book.

Good luck!

48

The Technion Electrical Engineering Networked Software Systems Laboratory

Appendix A – Simulation code

LoadDestriution.tcl

######################################### Buils the load map according to trace######################################## proc ParseTraceLine { trace_line } {

global traceElement flowsDS dropsDS test_drop ns_ drop_trace

# we are interested in dequeue operations onlyset status [lindex $trace_line 0]set from [lindex $trace_line 2]set to [lindex $trace_line 3]set src [lindex $trace_line 8]set dst [lindex $trace_line 9]set packet_type [lindex $trace_line 4]set packet_load [lindex $trace_line 5]

#get the router id from "from" and "to"set sh_src [lindex [split $src '.'] 0]set sh_dst [lindex [split $dst '.'] 0]set sh_from [lindex [split $from '.'] 0]set sh_to [lindex [split $to '.'] 0]

# We want to count only arrival and dropped packetsif {$status == "d" && $packet_type != "ack"} {

if { [info exists dropsDS($sh_src,$sh_dst,$sh_from,$sh_to)] } {set temp_load $dropsDS($sh_src,$sh_dst,$sh_from,$sh_to)

} else {set temp_load 0

}

set dropsDS($sh_src,$sh_dst,$sh_from,$sh_to) [expr 1 + $temp_load] return

}

if {$status == "+" && $packet_type != "ack"} {# count new load for immidiate link: $from -> $to in index $src -> $dstif { [info exists flowsDS($sh_src,$sh_dst,$sh_from,$sh_to)] } {

set temp_load $flowsDS($sh_src,$sh_dst,$sh_from,$sh_to)} else {

set temp_load 0}

#set nowtime [$ns_ now]#puts "DEBUG $nowtime : $sh_src,$sh_dst,$sh_from,$sh_to"

# We are counting the number of packetsset flowsDS($sh_src,$sh_dst,$sh_from,$sh_to) [expr 1 + $temp_load]

} else {return

}

}

############################# Reset flows data stucture############################ proc ResetFlowsDS {} {

global flowsDS

if {[info exists flowsDS]} {array unset flowsDS

}}

####################################### Reset dropped packets data stucture

49

The Technion Electrical Engineering Networked Software Systems Laboratory

###################################### proc ResetDropsDS {} {

global dropsDS

if {[info exists dropsDS]} {array unset dropsDS

}}

#################################################### Returns the shortest path tree for selected node################################################### proc ProduceShortestPathTree { sourceIndex } {

global SPT loadMap

# Bellman-Ford algorithmRunBellmanFord $sourceIndex BuildShortestPathTree $sourceIndex

}

######################################################################################## Counts the bottle neck of flow in flowsDS that starts with index - subFlowStartIndex#######################################################################################proc CountBottleNeck { flow } {

global flowsDS NUM_OF_ROUTERS

set src [lindex $flow 0]set dst [lindex $flow 1]set from [lindex $flow 2]set to [lindex $flow 3]

set fromInd 0set toInd 1

set flowBottleNeck 0set tmpBottleNeck 0

while {$toInd < [llength $flow]} { set from [lindex $flow $fromInd]set to [lindex $flow $toInd]

# We have to count all sub flows! There is no meaning what is the flow sourcefor {set src 0} {$src < $NUM_OF_ROUTERS} {incr src} {

if {[info exists flowsDS($src,$dst,$from,$to)]} {set tmpBottleNeck [expr $tmpBottleNeck + $flowsDS($src,$dst,$from,$to)]

}}

if {$tmpBottleNeck > $flowBottleNeck} {set flowBottleNeck $tmpBottleNeck

}

incr fromIndincr toInd

}

return $flowBottleNeck}

###################################################### Remove entries of current flow from routing tables # Create new entries of new flow in routing tables ##################################################### proc ChangeFlowPath { } {

global ns_ node_ROUTER new_SPT_path old_network_path

set nowtime [$ns_ now]puts "$nowtime: Change from $old_network_path to $new_SPT_path"

set currLen [llength $old_network_path]set newLen [llength $new_SPT_path]set nullAgent_ [new Agent/Null]

50

The Technion Electrical Engineering Networked Software Systems Laboratory

#remove first edge of sub-pathset dst [lindex $old_network_path [expr [llength $old_network_path] - 1] ]$node_ROUTER([lindex $old_network_path 0]) delete-route [$node_ROUTER($dst) set address_] $nullAgent_

# puts "remove: [lindex $old_network_path 0] $dst"

# remove current sub-path if there are no others that use itfor {set i 1} {$i < [expr $currLen - 1]} {incr i} {

set from [lindex $old_network_path $i]if { [CanRemove [lindex $old_network_path 0] $from $dst] == true } {

# puts "remove: $from $dst" $node_ROUTER($from) delete-route [$node_ROUTER($dst) set address_] $nullAgent_

}}

# config new sub-pathfor {set i 0} {$i < [expr $newLen - 1]} {incr i} {

set from [lindex $new_SPT_path $i]set to [lindex $new_SPT_path [expr $i + 1]]

# puts "add: $from $to $dst"[$node_ROUTER($from) get-module "Manual"] add-route [$node_ROUTER($dst) set address_] [[$ns_

link $node_ROUTER($from) $node_ROUTER($to)] head] }

}

#We can remove link IAOF each node that use this link use 'from' beforeproc CanRemove { curr from dst} {

global flowsDS auxPath

#TestFlowsDSforeach flow [array names flowsDS] {

set sep_flow [split $flow ',']

if { [lindex $sep_flow 2] == $from && [lindex $sep_flow 1] == $dst } {set auxPath {}GetPath [lindex $sep_flow 0] [lindex $sep_flow 1]set auxPath [linsert $auxPath [llength $auxPath] [lindex $sep_flow 1]]

#puts "DEBUG: $auxPath"set currBeforeFrom falseforeach node $auxPath {

if { $node == $from && $node != $curr && $currBeforeFrom == false} {return false

} else {if { $node == $curr } {

set currBeforeFrom true}

}}

}}

return true}

proc GetPath { from dst } {global flowsDS auxPath

set flag falseset src -1foreach curr_el [array names flowsDS] {

set sep_el [split $curr_el ','] if { [lindex $sep_el 2] == $from && [lindex $sep_el 1] == $dst } {

if { $flag == false } {set src [lindex $sep_el 0]set flag true

}

if { [lindex $sep_el 0] == $src } {set auxPath [linsert $auxPath [llength $auxPath] [lindex $sep_el 2]]GetPath [lindex $sep_el 3] $dst

}

51

The Technion Electrical Engineering Networked Software Systems Laboratory

}}

}

########################################################################################################## Returns list of sources that contain path from -> dst, dst is the destination of the flow source->dst######################################################################################################### proc GetSourcesList { from dst } {

global NUM_OF_ROUTERS flowsDS listOfSources

set listOfSources {}

foreach flow [array names flowsDS] {set sep_flow [split $flow ',']

if { [lindex $sep_flow 2] == $from && [lindex $sep_flow 1] == $dst} {set flag falseforeach src $listOfSources {

if { [lindex $sep_flow 0] == $src } {set flag true

}}

if { $flag == false } {set listOfSources [linsert $listOfSources [llength $listOfSources] [lindex $sep_flow

0]]}

}}

}

############################################################# New path has been detected in SPT - may be we can use it############################################################ proc NewSPTPath { } {

global SPT new_SPT_path old_network_path firstTime

# we have got a new path because ther are no more children in this tree nodeset firstTime($new_SPT_path) false

set cntOfDestanations 0set rootID $SPT("root")set tailID [lrange $new_SPT_path end end]

# The tailID is not a distanation in routing tables of rootIDif { [IsDestination $rootID $tailID] == false } {

return}

set old_network_path {}GetCurrentPath $rootID $tailID# complite the recurtion...set old_network_path [linsert $old_network_path [llength $old_network_path] $tailID]

# puts "DEBUG: $old_network_path"if { [ CanImprove ] == true} {

ChangeFlowPath }

}

######################################################### Is 'dst' is destination in routing tables of 'from'########################################################proc IsDestination { from dst } {

global flowsDS

foreach curr_el [array names flowsDS] {set sep_el [split $curr_el ',']

if { [lindex $sep_el 2] == $from && [lindex $sep_el 1] == $dst } { return true

52

The Technion Electrical Engineering Networked Software Systems Laboratory

}}

return false}

################################################################################################################### Recursive procedure, sets the old_network_path to the list of nodes between 'from' and 'dst' nodes (including)##################################################################################################################proc GetCurrentPath { from dst } {

global flowsDS old_network_path

set flag falseset src -1foreach curr_el [array names flowsDS] {

set sep_el [split $curr_el ','] if { [lindex $sep_el 2] == $from && [lindex $sep_el 1] == $dst } {

if { $flag == false } {set src [lindex $sep_el 0]set flag true

}

if { [lindex $sep_el 0] == $src } {set old_network_path [linsert $old_network_path [llength $old_network_path]

[lindex $sep_el 2]]GetCurrentPath [lindex $sep_el 3] $dst

}}

}}

############################################################################## Go over all paths in tree and run load distribution algorithm fo this path#############################################################################proc RecursiveDFS { currNodeID indexInNodeList } {

global SPT new_SPT_path listOfSubFlows firstTime

# Go deep as u can# ----------------if {[info exists SPT] == 0} {

return}

if {[info exists firstTime($new_SPT_path)] == 0 && [llength $new_SPT_path] > 1} {NewSPTPath

}

if { [info exists SPT($currNodeID)] && [llength $SPT($currNodeID)] > 1} {

set nodeList $SPT($currNodeID)set cnt 0

while { $indexInNodeList < [llength $nodeList] } {

set nextNodeID [lindex $nodeList $indexInNodeList]set new_SPT_path [linsert $new_SPT_path [llength $new_SPT_path] $nextNodeID]

RecursiveDFS $nextNodeID 1 incr indexInNodeList

}} else {

if {[info exists firstTime($new_SPT_path)] == 0 && [llength $new_SPT_path] > 1} {NewSPTPath

}}

# Try next path#--------------

53

The Technion Electrical Engineering Networked Software Systems Laboratory

# delete the last node from the flowset new_SPT_path [lrange $new_SPT_path 0 end-1]

return}

proc GetDropsOn { from to } {global dropsDS

set dropped 0foreach curr_el [array names dropsDS] {

set sep_el [split $curr_el ','] if { [lindex $sep_el 0] == $from && [lindex $sep_el 1] == $to } {

set dropped [expr $dropped + $dropsDS($curr_el)]}

}

return $dropped}

proc GetSentOn { from to } {global flowsDS

set arrived 0foreach curr_el [array names flowsDS] {

set sep_el [split $curr_el ','] if { [lindex $sep_el 0] == $from && [lindex $sep_el 1] == $to && [lindex $sep_el 2] == $from} {

set arrived $flowsDS($curr_el)break

}}

return $arrived}

##################################################################################################### Returns true if the original bottleneck can be reduced by moving floeToMove to the sugestedPath# Compares (pathToMove - flowToMove) VS (sugestedPath + flowToMove)####################################################################################################proc CanImprove { } {

global loadMap flowsDS new_SPT_path old_network_path listOfSources

set from [lindex $old_network_path 0]set dst [lindex $old_network_path 1]

# The sugessted path from SPT is the already existsif { $old_network_path == $new_SPT_path } {

return false}

GetSourcesList $from $dst

set tmpBN 0set oldBN 0set newBN 0# Count the bottle neck on the old path set cnt 0while {$cnt < [expr [llength $old_network_path] - 1]} {

set from [lindex $old_network_path $cnt]set to [lindex $old_network_path [expr $cnt + 1]]

if {[info exists loadMap($from->$to)]} {set tmpBN $loadMap($from->$to)

} else {puts "Error on CanImprove procedure - old path BN, loadMap definition"

}

if {$tmpBN > $oldBN} {set oldBN $tmpBN

}

incr cnt

54

The Technion Electrical Engineering Networked Software Systems Laboratory

}

# We assume that the estimated load is a sent number of packets on the old pathset estimatedAdditionalLoad 0set from [lindex $old_network_path 0]set to [lindex $old_network_path 1]foreach src $listOfSources {

if {[info exists flowsDS($src,$dst,$from,$to)]} {set estimatedAdditionalLoad [expr $estimatedAdditionalLoad + $flowsDS($src,$dst,$from,

$to)]}

}

# Count the bottle neck on the new path after the new path will be added set cnt 0while {$cnt < [expr [llength $new_SPT_path] - 1]} {

set from [lindex $new_SPT_path $cnt]set to [lindex $new_SPT_path [expr $cnt + 1]]

if {[info exists loadMap($from->$to)]} {set tmpBN [expr $loadMap($from->$to) + $estimatedAdditionalLoad]

} else {puts "Error on CanImprove procedure - new path BN, loadMap definition"

}

if {$tmpBN > $newBN} {set newBN $tmpBN

}

incr cnt}

if { $oldBN > $newBN } {return true

}

return false}

############################################## Implements the load distribution algorithm#############################################proc LoadDistributionAlgorithm { nodeID } {

global new_SPT_path NUM_OF_ROUTERS SPT firstTime

# Build shortest path tree - SPT# ProduceShortestPathTree $nodeID

# set new_SPT_path {}

# Run recursive algorithm of load distribution in network# if {[info exists SPT]} {# set new_SPT_path [linsert $new_SPT_path 0 $SPT("root")]# }

# if {[info exists firstTime]} {# unset firstTime# }

# RecursiveDFS $nodeID 1

if { $nodeID == [expr $NUM_OF_ROUTERS - 1] } {ResetFlowsDSResetDropsDSResetLoadMap

}}

55

The Technion Electrical Engineering Networked Software Systems Laboratory

Bellman-Ford_SPT.tcl

set _INFINITY 9999999set _NA -1

##################################################################### proc RunBellmanFord

###################################################################### Runs the bellman-Ford algorithm on the src requested according to the data in ## node_ROUTER and loadMap

#####################################################################proc RunBellmanFord { src } {

InitGraph $src RelaxEdges $src

}##################################################################### proc InitGraph

###################################################################### Initialize the shortest_paths_array as the first stage in the Bellman-Ford #####################################################################proc InitGraph { src } {global node_ROUTER loadMap shortest_paths_array _INFINITY _NA

foreach curr_router [array names node_ROUTER] {

if { $curr_router == $src } { continue }

set shortest_paths_array($src,$curr_router,load) $_INFINITYset shortest_paths_array($src,$curr_router,predecessor) $_NA

}set shortest_paths_array($src,$src,load) 0set shortest_paths_array($src,$src,predecessor) $_NA

}##################################################################### proc RelaxEdges

###################################################################### Checking each edge uv if the distance to u plus this edge is smaller than the distance to ## v, if it is than we change the predecessor of v to u and update the new weight. #####################################################################proc RelaxEdges { src } {global node_ROUTER loadMap shortest_paths_array

foreach curr_router [array names node_ROUTER] { if { $curr_router == $src } { continue }

foreach edge [array names loadMap] { # making the edge as a list set edge_as_list [split $edge {}] # taking the src of this edge

set from [lrange $edge_as_list 0 [expr [lsearch $edge_as_list -] - 1]]# taking the destination of the edge

set to [lrange $edge_as_list [expr [lsearch $edge_as_list >] + 1] end]# calculating the distance with the new edge

set tmp_dist [expr $shortest_paths_array($src,$from,load) + $loadMap($edge)]# if the new distance is better than the old oneif { $tmp_dist < $shortest_paths_array($src,$to,load) } {

set shortest_paths_array($src,$to,load) $tmp_dist set shortest_paths_array($src,$to,predecessor) $from

} } }}##################################################################### proc BuildShortestPathTree

#

56

The Technion Electrical Engineering Networked Software Systems Laboratory

##################################################################### This procedure takes the shortest_paths_tree and constructs the Shortest Path Tree ## from it.

## SPT structure:

## ^^^^^^^^^^^^^^

## SPT("root") - Will return the nodeID of the router we ran the Bellman-Ford on. Please ## note that "root" is a string not a variable. ## After receiving the ID of the root we can start traversing in the tree. ## SPT(nodeID) - Will return a list {PREV_ID, NEXT_ID1, NEXT_ID2,....} ## PREV_ID - Will be _NA at the root only and will always contain a value. ## NEXT_ID - Will contain the ID of the son of the node. If there are more than one son ## than we will have several NEXT_IDs. At the leaf nodes there will be NO NEXT_ID ## value. Therefore leaf nodes will have only PREV_ID. #####################################################################proc BuildShortestPathTree { src } {global shortest_paths_array SPT node_ROUTER _NA

if {[info exists SPT]} { unset SPT }

set SPT("root") $srcforeach curr_router [array names node_ROUTER] {

if { $curr_router == $src } { continue }

set prev $shortest_paths_array($src,$curr_router,predecessor)

#puts "$src->$curr_router, prev=$prev"

if { $prev == $_NA } { ;#only the src should have predecessor = _NAputs "Error Accord.... Aborting!"exit

}if { [lsearch [array names SPT] $curr_router] > -1 } { ;# if curr_router is already in the SPT

if { [lrange $SPT($curr_router) 0 0] == $_NA } {set SPT($curr_router) [lreplace $SPT($curr_router) 0 0 $prev] ;# set his

predecessor#puts "$curr_router exists in SPT, SPT($curr_router)=$SPT($curr_router)"

}} else { ;# if curr_router isn't in the SPT

set SPT($curr_router) [list $prev]#puts "$curr_router doesn't exists in SPT, SPT($curr_router)=$SPT($curr_router)"

}if { [lsearch [array names SPT] $prev] > -1 } { ;# if the predecessor is already in the SPT

#add curr_router to its NEXT_ID listif { [lsearch $SPT($prev) $curr_router] == -1 } {

#puts "$prev already in SPT, $curr_router isn't in his SPT"#puts "before: $SPT($prev)"

lappend SPT($prev) $curr_router #puts "after: $SPT($prev)"

}} else { ;# if the predecessor isn't in the SPT

# insert the predecessor to the list with prev=_NA and NEXT_ID = curr_routerset SPT($prev) [list $_NA $curr_router]

}}

}

57

The Technion Electrical Engineering Networked Software Systems Laboratory

SetNetworkRoutingMap.tcl

##################################################### proc BuildRoutes_ROUTERS ###################################################### Builds manual routing tables for routers network #####################################################

proc BuildRoutes_ROUTERS { simulation_number } {if { $simulation_number == 1 } {

BuildRoutes_ROUTERS_1} else {

if { $simulation_number == 2 } {BuildRoutes_ROUTERS_2

} else { if { $simulation_number == 3 } {

BuildRoutes_ROUTERS_3}

}}

}

proc ScheduleNetworkSimulation { simulation_number } {if { $simulation_number == 1 } {

ScheduleNetworkSimulation_1} else {

if { $simulation_number == 2 } {ScheduleNetworkSimulation_2

} else { if { $simulation_number == 3 } {

ScheduleNetworkSimulation_3}

}}

}

proc BuildRoutes_ROUTERS_1 {} {global ns_ node_ROUTER NUM_OF_ROUTERS

# default routes for for acks population[$node_ROUTER(5) get-module "Manual"] add-route [$node_ROUTER(0) set address_] [[$ns_ link

$node_ROUTER(5) $node_ROUTER(0)] head][$node_ROUTER(5) get-module "Manual"] add-route [$node_ROUTER(1) set address_] [[$ns_ link

$node_ROUTER(5) $node_ROUTER(1)] head][$node_ROUTER(5) get-module "Manual"] add-route [$node_ROUTER(2) set address_] [[$ns_ link

$node_ROUTER(5) $node_ROUTER(2)] head][$node_ROUTER(5) get-module "Manual"] add-route [$node_ROUTER(3) set address_] [[$ns_ link

$node_ROUTER(5) $node_ROUTER(3)] head][$node_ROUTER(5) get-module "Manual"] add-route [$node_ROUTER(4) set address_] [[$ns_ link

$node_ROUTER(5) $node_ROUTER(4)] head]

# routes:#0-->5: 0->1->2->3->4->5#1-->5: 1->2->3->4->5#2-->5: 2->3->4->5#3-->5: 3->4->5#4-->5: 4->5

[$node_ROUTER(0) get-module "Manual"] add-route [$node_ROUTER(5) set address_] [[$ns_ link $node_ROUTER(0) $node_ROUTER(1)] head]

[$node_ROUTER(1) get-module "Manual"] add-route [$node_ROUTER(5) set address_] [[$ns_ link $node_ROUTER(1) $node_ROUTER(2)] head]

[$node_ROUTER(2) get-module "Manual"] add-route [$node_ROUTER(5) set address_] [[$ns_ link $node_ROUTER(2) $node_ROUTER(3)] head]

[$node_ROUTER(3) get-module "Manual"] add-route [$node_ROUTER(5) set address_] [[$ns_ link $node_ROUTER(3) $node_ROUTER(4)] head]

[$node_ROUTER(4) get-module "Manual"] add-route [$node_ROUTER(5) set address_] [[$ns_ link $node_ROUTER(4) $node_ROUTER(5)] head]}

proc BuildRoutes_ROUTERS_2 {} {

58

The Technion Electrical Engineering Networked Software Systems Laboratory

global ns_ node_ROUTER NUM_OF_ROUTERS

# default routes in circle for acks population[$node_ROUTER(3) get-module "Manual"] add-route [$node_ROUTER(0) set address_] [[$ns_ link

$node_ROUTER(3) $node_ROUTER(0)] head][$node_ROUTER(4) get-module "Manual"] add-route [$node_ROUTER(0) set address_] [[$ns_ link

$node_ROUTER(4) $node_ROUTER(0)] head]

[$node_ROUTER(3) get-module "Manual"] add-route [$node_ROUTER(5) set address_] [[$ns_ link $node_ROUTER(3) $node_ROUTER(5)] head]

[$node_ROUTER(4) get-module "Manual"] add-route [$node_ROUTER(5) set address_] [[$ns_ link $node_ROUTER(4) $node_ROUTER(5)] head]

# for {set i 0} {$i < $NUM_OF_ROUTERS} {incr i} {# [$node_ROUTER($i) get-module "Manual"] add-route-to-adj-node -default $node_ROUTER([expr ($i+1) % $NUM_OF_ROUTERS]) # }

# routes:#0-->3: 0->1->2->3#0-->4: 0->1->2->4#5-->3: 5->1->2->3#5-->4: 5->1->2->4

[$node_ROUTER(0) get-module "Manual"] add-route [$node_ROUTER(3) set address_] [[$ns_ link $node_ROUTER(0) $node_ROUTER(1)] head]

[$node_ROUTER(0) get-module "Manual"] add-route [$node_ROUTER(4) set address_] [[$ns_ link $node_ROUTER(0) $node_ROUTER(1)] head]

[$node_ROUTER(5) get-module "Manual"] add-route [$node_ROUTER(3) set address_] [[$ns_ link $node_ROUTER(5) $node_ROUTER(1)] head]

[$node_ROUTER(5) get-module "Manual"] add-route [$node_ROUTER(4) set address_] [[$ns_ link $node_ROUTER(5) $node_ROUTER(1)] head]

[$node_ROUTER(1) get-module "Manual"] add-route [$node_ROUTER(3) set address_] [[$ns_ link $node_ROUTER(1) $node_ROUTER(2)] head]

[$node_ROUTER(1) get-module "Manual"] add-route [$node_ROUTER(4) set address_] [[$ns_ link $node_ROUTER(1) $node_ROUTER(2)] head]

[$node_ROUTER(2) get-module "Manual"] add-route [$node_ROUTER(3) set address_] [[$ns_ link $node_ROUTER(2) $node_ROUTER(3)] head]

[$node_ROUTER(2) get-module "Manual"] add-route [$node_ROUTER(4) set address_] [[$ns_ link $node_ROUTER(2) $node_ROUTER(4)] head]

}

proc BuildRoutes_ROUTERS_3 {} {global ns_ node_ROUTER NUM_OF_ROUTERS

# default routes for for acks population

# 6->0->3->7# 0->1->2->3# 4->1->3

# 0->2->3->8# 1->6->7->2# 4->1->2->5->8->9

[$node_ROUTER(6) get-module "Manual"] add-route [$node_ROUTER(7) set address_] [[$ns_ link $node_ROUTER(6) $node_ROUTER(0)] head]

[$node_ROUTER(0) get-module "Manual"] add-route [$node_ROUTER(7) set address_] [[$ns_ link $node_ROUTER(0) $node_ROUTER(3)] head]

[$node_ROUTER(3) get-module "Manual"] add-route [$node_ROUTER(7) set address_] [[$ns_ link $node_ROUTER(3) $node_ROUTER(7)] head]

[$node_ROUTER(7) get-module "Manual"] add-route [$node_ROUTER(6) set address_] [[$ns_ link $node_ROUTER(7) $node_ROUTER(6)] head]

[$node_ROUTER(0) get-module "Manual"] add-route [$node_ROUTER(3) set address_] [[$ns_ link $node_ROUTER(0) $node_ROUTER(1)] head]

[$node_ROUTER(1) get-module "Manual"] add-route [$node_ROUTER(3) set address_] [[$ns_ link $node_ROUTER(1) $node_ROUTER(2)] head]

59

The Technion Electrical Engineering Networked Software Systems Laboratory

[$node_ROUTER(2) get-module "Manual"] add-route [$node_ROUTER(3) set address_] [[$ns_ link $node_ROUTER(2) $node_ROUTER(3)] head]

[$node_ROUTER(3) get-module "Manual"] add-route [$node_ROUTER(0) set address_] [[$ns_ link $node_ROUTER(3) $node_ROUTER(0)] head]

[$node_ROUTER(4) get-module "Manual"] add-route [$node_ROUTER(3) set address_] [[$ns_ link $node_ROUTER(4) $node_ROUTER(1)] head]

[$node_ROUTER(1) get-module "Manual"] add-route [$node_ROUTER(3) set address_] [[$ns_ link $node_ROUTER(4) $node_ROUTER(1)] head]

[$node_ROUTER(3) get-module "Manual"] add-route [$node_ROUTER(4) set address_] [[$ns_ link $node_ROUTER(3) $node_ROUTER(4)] head]

[$node_ROUTER(0) get-module "Manual"] add-route [$node_ROUTER(8) set address_] [[$ns_ link $node_ROUTER(0) $node_ROUTER(2)] head]

[$node_ROUTER(2) get-module "Manual"] add-route [$node_ROUTER(8) set address_] [[$ns_ link $node_ROUTER(2) $node_ROUTER(3)] head]

[$node_ROUTER(3) get-module "Manual"] add-route [$node_ROUTER(8) set address_] [[$ns_ link $node_ROUTER(3) $node_ROUTER(8)] head]

[$node_ROUTER(8) get-module "Manual"] add-route [$node_ROUTER(0) set address_] [[$ns_ link $node_ROUTER(8) $node_ROUTER(0)] head]

[$node_ROUTER(1) get-module "Manual"] add-route [$node_ROUTER(2) set address_] [[$ns_ link $node_ROUTER(1) $node_ROUTER(6)] head]

[$node_ROUTER(6) get-module "Manual"] add-route [$node_ROUTER(2) set address_] [[$ns_ link $node_ROUTER(6) $node_ROUTER(7)] head]

[$node_ROUTER(7) get-module "Manual"] add-route [$node_ROUTER(2) set address_] [[$ns_ link $node_ROUTER(7) $node_ROUTER(2)] head]

[$node_ROUTER(2) get-module "Manual"] add-route [$node_ROUTER(1) set address_] [[$ns_ link $node_ROUTER(2) $node_ROUTER(1)] head]

[$node_ROUTER(4) get-module "Manual"] add-route [$node_ROUTER(9) set address_] [[$ns_ link $node_ROUTER(4) $node_ROUTER(1)] head]

[$node_ROUTER(1) get-module "Manual"] add-route [$node_ROUTER(9) set address_] [[$ns_ link $node_ROUTER(1) $node_ROUTER(2)] head]

[$node_ROUTER(2) get-module "Manual"] add-route [$node_ROUTER(9) set address_] [[$ns_ link $node_ROUTER(2) $node_ROUTER(3)] head]

[$node_ROUTER(3) get-module "Manual"] add-route [$node_ROUTER(9) set address_] [[$ns_ link $node_ROUTER(3) $node_ROUTER(8)] head]

[$node_ROUTER(8) get-module "Manual"] add-route [$node_ROUTER(9) set address_] [[$ns_ link $node_ROUTER(8) $node_ROUTER(9)] head]

[$node_ROUTER(9) get-module "Manual"] add-route [$node_ROUTER(4) set address_] [[$ns_ link $node_ROUTER(9) $node_ROUTER(4)] head]

# routes:#0-->5: 0->1->2->3->4->5#1-->5: 1->2->3->4->5#2-->5: 2->3->4->5#3-->5: 3->4->5#4-->5: 4->5

[$node_ROUTER(0) get-module "Manual"] add-route [$node_ROUTER(5) set address_] [[$ns_ link $node_ROUTER(0) $node_ROUTER(1)] head]

[$node_ROUTER(1) get-module "Manual"] add-route [$node_ROUTER(5) set address_] [[$ns_ link $node_ROUTER(1) $node_ROUTER(2)] head]

[$node_ROUTER(2) get-module "Manual"] add-route [$node_ROUTER(5) set address_] [[$ns_ link $node_ROUTER(2) $node_ROUTER(3)] head]

[$node_ROUTER(3) get-module "Manual"] add-route [$node_ROUTER(5) set address_] [[$ns_ link $node_ROUTER(3) $node_ROUTER(4)] head]

[$node_ROUTER(4) get-module "Manual"] add-route [$node_ROUTER(5) set address_] [[$ns_ link $node_ROUTER(4) $node_ROUTER(5)] head]

[$node_ROUTER(0) get-module "Manual"] add-route [$node_ROUTER(4) set address_] [[$ns_ link $node_ROUTER(0) $node_ROUTER(1)] head]

[$node_ROUTER(5) get-module "Manual"] add-route [$node_ROUTER(3) set address_] [[$ns_ link $node_ROUTER(5) $node_ROUTER(1)] head]

[$node_ROUTER(5) get-module "Manual"] add-route [$node_ROUTER(4) set address_] [[$ns_ link $node_ROUTER(5) $node_ROUTER(1)] head]

60

The Technion Electrical Engineering Networked Software Systems Laboratory

[$node_ROUTER(1) get-module "Manual"] add-route [$node_ROUTER(3) set address_] [[$ns_ link $node_ROUTER(1) $node_ROUTER(2)] head]

[$node_ROUTER(1) get-module "Manual"] add-route [$node_ROUTER(4) set address_] [[$ns_ link $node_ROUTER(1) $node_ROUTER(2)] head]

[$node_ROUTER(2) get-module "Manual"] add-route [$node_ROUTER(3) set address_] [[$ns_ link $node_ROUTER(2) $node_ROUTER(3)] head]

[$node_ROUTER(2) get-module "Manual"] add-route [$node_ROUTER(4) set address_] [[$ns_ link $node_ROUTER(2) $node_ROUTER(4)] head]

for {set i 0} {$i < $NUM_OF_ROUTERS} {incr i} {[$node_ROUTER($i) get-module "Manual"] add-route-to-adj-node -default $node_ROUTER([expr ($i+1)

% $NUM_OF_ROUTERS]) }

}

proc ScheduleNetworkSimulation_1 {} {global ns_ ftp_ROUTER

$ns_ at 0 "$ftp_ROUTER(0->5) start"$ns_ at 0 "$ftp_ROUTER(1->5) start"$ns_ at 0 "$ftp_ROUTER(2->5) start"$ns_ at 0 "$ftp_ROUTER(3->5) start"$ns_ at 0 "$ftp_ROUTER(4->5) start"

}

proc ScheduleNetworkSimulation_2 {} {global ns_ ftp_ROUTER

$ns_ at 0 "$ftp_ROUTER(0->3) start"$ns_ at 0 "$ftp_ROUTER(5->3) start"

$ns_ at 0 "$ftp_ROUTER(0->4) start"$ns_ at 0 "$ftp_ROUTER(5->4) start"

}

proc ScheduleNetworkSimulation_3 {} {global ns_ ftp_ROUTER

$ns_ at 0 "$ftp_ROUTER(6->7) start"$ns_ at 0 "$ftp_ROUTER(0->3) start"$ns_ at 0 "$ftp_ROUTER(4->3) start"$ns_ at 0 "$ftp_ROUTER(0->8) start"$ns_ at 0 "$ftp_ROUTER(1->2) start"$ns_ at 0 "$ftp_ROUTER(4->9) start"

$ns_ at 0 "$ftp_ROUTER(5->3) start"$ns_ at 0 "$ftp_ROUTER(0->4) start"$ns_ at 0 "$ftp_ROUTER(5->4) start"

$ns_ at 0 "$ftp_ROUTER(0->5) start"$ns_ at 0 "$ftp_ROUTER(1->5) start"$ns_ at 0 "$ftp_ROUTER(2->5) start"$ns_ at 0 "$ftp_ROUTER(3->5) start"$ns_ at 0 "$ftp_ROUTER(4->5) start"

}

61

The Technion Electrical Engineering Networked Software Systems Laboratory

testLoadDestribution.tcl

####################################################################################################################################################################################################################################################################### Test and auxiluary procedures######################################################################################################################################################################################################################################################################

proc TestSPT { routerID } {global SPT

foreach curr [array names SPT] {puts "SPT($curr)=$SPT($curr)"

}}

proc TestFlowsDS { } {global NUM_OF_ROUTERS flowsDS

foreach curr [array names flowsDS] {puts "flowsDS($curr)=$flowsDS($curr)"

}}

proc TestDropsDS { } {global NUM_OF_ROUTERS dropsDS

if {[array size dropsDS] > 0} {puts "There are some dropped packets!"

for {set src 0} {$src < $NUM_OF_ROUTERS} {incr src} {for {set dst 0} {$dst < $NUM_OF_ROUTERS} {incr dst} {

for {set from 0} {$from < $NUM_OF_ROUTERS} {incr from} {for {set to 0} {$to < $NUM_OF_ROUTERS} {incr to} {

if {[info exists dropsDS($src,$dst,$from,$to)]} {puts "$src --> $from -> $to --> $dst :

$dropsDS($src,$dst,$from,$to)"}

}}

}}

} else {puts "There are no dropped packets!"

}}

proc TestLoadMap {} {global NUM_OF_ROUTERS loadMap

if {[array size loadMap] > 0} {puts "loadMap has been built properly: "

for {set from 0} {$from < $NUM_OF_ROUTERS} {incr from} {for {set to 0} {$to < $NUM_OF_ROUTERS} {incr to} {

if {[info exists loadMap($from->$to)]} {puts "On link $from -> $to: $loadMap($from->$to)"

}}

}

} else {puts "Error: loadMap has not been built properly."

}

62

The Technion Electrical Engineering Networked Software Systems Laboratory

}

proc TestListOfDestinations { routerID } {global NUM_OF_ROUTERS listOfDestinations

if {[llength $listOfDestinations] > 0} {puts "listOfDestinations has been built properly in length of: [llength $listOfDestinations]"puts $listOfDestinations

} else {puts "Error: listOfDestinations not exists."

}}

proc TestAllSubFlows { headID tailID } {global listOfSubFlows

if { [llength $listOfSubFlows] } {puts "List of sub flows between $headID and $tailID has been buit properly: "puts $listOfSubFlows

} else {puts "Error: listOfSubFlows between $headID and $tailID not exists."

}}

proc TestPrintNewFlow {} {global newFlow

puts "Test print of newFlow: $newFlow"}

63

The Technion Electrical Engineering Networked Software Systems Laboratory

SimulationScript2.tcl

# ======================================================================# ======================================================================# Global Defines# # ======================================================================set SIMULATION_TIME 51# sets an array to hold the load of each queue in the routers networkset array routerQueueLoadset array loadMap# ======================================================================# Wireless Sensor Network# ======================================================================# ======================================================================# WSN Define options# ======================================================================set val(chan) Channel/WirelessChannel ;# channel typeset val(prop) Propagation/TwoRayGround ;# radio-propagation modelset val(netif) Phy/WirelessPhy ;# network interface typeset val(mac) Mac/802_11 ;# MAC typeset val(ifq) Queue/DropTail/PriQueue ;# interface queue typeset val(ll) LL ;# link layer typeset val(ant) Antenna/OmniAntenna ;# antenna modelset val(ifqlen) 50 ;# max packet in ifqset val(nn) 10 ;# number of mobilenodesset val(rp) DSDV ;# routing protocolset val(x) 500 ;# X dimension of the topographyset val(y) 500 ;# Y dimension of the topographyset val(ifqlenMain) 500 ;# max packet in ifq for the main stationset CENTRAL_STATION $val(nn) ;# the index of the base stationset WSN_QUEUE_LIMIT 35

############################################# proc BuildTopology_WSN ############################################## Builds sensors wireless network topology #############################################proc BuildTopology_WSN {} {

global ns_ val node_WSN SERVICE_TEMPO PROPOGATION_TIME QUEUE_TYPE QUEUE_LIMIT qmonCentral qmonSensor CENTRAL_STATION WSN_QUEUE_LIMIT

# set up topography objectset topo [new Topography]

# define grid for wireless stations$topo load_flatgrid $val(x) $val(y)

# Create Godcreate-god $val(nn)

# configure node $ns_ node-config \

-adhocRouting $val(rp) \ -llType $val(ll) \ -macType $val(mac) \ -ifqType $val(ifq) \ -ifqLen $val(ifqlen) \ -antType $val(ant) \ -propType $val(prop) \ -phyType $val(netif) \ -channelType $val(chan) \ -topoInstance $topo \ -agentTrace ON \ -routerTrace ON \ -wiredRouting ON \ -macTrace OFF \ -movementTrace OFF

# Sensor stations nodesfor {set i 0} {$i < $CENTRAL_STATION} {incr i} {

set node_WSN($i) [$ns_ node]

64

The Technion Electrical Engineering Networked Software Systems Laboratory

$node_WSN($i) random-motion 0 ;# disable random motion

}

# Base station node $ns_ node-config -ifqLen $val(ifqlenMain)

set node_WSN($CENTRAL_STATION) [$ns_ node]$node_WSN($CENTRAL_STATION) random-motion 0 ;# disable random motion

# Provide initial (X,Y, for now Z=0) co-ordinates for mobilenodes$node_WSN(0) set X_ 100.0$node_WSN(0) set Y_ 400.0$node_WSN(0) set Z_ 0.0

$node_WSN(1) set X_ 250.0$node_WSN(1) set Y_ 400.0$node_WSN(1) set Z_ 0.0

$node_WSN(2) set X_ 300$CENTRAL_STATION.0$node_WSN(2) set Y_ 250.0$node_WSN(2) set Z_ 0.0

$node_WSN(3) set X_ 175.0$node_WSN(3) set Y_ 200.0$node_WSN(3) set Z_ 0.0

$node_WSN(4) set X_ 50.0$node_WSN(4) set Y_ 250.0$node_WSN(4) set Z_ 0.0

$node_WSN(5) set X_ 175.0$node_WSN(5) set Y_ 325.0$node_WSN(5) set Z_ 0.0

# Connects all the sensors to the base station and create monitor object for each connection for {set i 0} {$i < $CENTRAL_STATION} {incr i} {

$ns_ duplex-link $node_WSN($i) $node_WSN($CENTRAL_STATION) $SERVICE_TEMPO $PROPOGATION_TIME $QUEUE_TYPE

$ns_ queue-limit $node_WSN($i) $node_WSN($CENTRAL_STATION) $WSN_QUEUE_LIMIT$ns_ queue-limit $node_WSN($CENTRAL_STATION) $node_WSN($i) $WSN_QUEUE_LIMITset qmonCentral($i) [$ns_ monitor-queue $node_WSN($i) $node_WSN($CENTRAL_STATION) 0]set qmonSensor($i) [$ns_ monitor-queue $node_WSN($CENTRAL_STATION) $node_WSN($i) 0]

}}

################################################### proc BuildRoutes_WSN #################################################### Builds routes for star topology in WSN network ###################################################proc BuildRoutes_WSN {} {

global node_WSN CENTRAL_STATION

for {set i 0} {$i < $CENTRAL_STATION} {incr i} {[$node_WSN($CENTRAL_STATION) get-module "Manual"] add-route-to-adj-node $node_WSN($i)[$node_WSN($i) get-module "Manual"] add-route-to-adj-node $node_WSN($CENTRAL_STATION)

}}

############################################# proc FTPoverTCP_WSN ############################################## Creates FTP over TCP for sensors network #############################################proc FTPoverTCP_WSN {} {

global ns_ node_WSN val ftp_WSN tcp_WSN CENTRAL_STATION NUM_OF_ROUTERS

# Setup FTP over TCPprevParrivalsSfor {set i 0} {$i <= $CENTRAL_STATION} {incr i} {

# conections from sensors to the Sentral Stationif {$i != $CENTRAL_STATION} {

65

The Technion Electrical Engineering Networked Software Systems Laboratory

set tcp_WSN($i->$CENTRAL_STATION) [new Agent/TCP/Newreno]$tcp_WSN($i->$CENTRAL_STATION) set class_ 2$tcp_WSN($i->$CENTRAL_STATION) set fid_ 1$ns_ attach-agent $node_WSN($i) $tcp_WSN($i->$CENTRAL_STATION)

set ftp_WSN($i->$CENTRAL_STATION) [new Application/FTP]$ftp_WSN($i->$CENTRAL_STATION) attach-agent $tcp_WSN($i-

>$CENTRAL_STATION)$ftp_WSN($i->$CENTRAL_STATION) set type_ FTP

} else {# conections from the Sentral Station to sensors for {set j 0} {$j < $CENTRAL_STATION} {incr j} {

set tcp_WSN($CENTRAL_STATION->$j) [new Agent/TCP/Newreno]$tcp_WSN($CENTRAL_STATION->$j) set class_ 2$tcp_WSN($CENTRAL_STATION->$j) set fid_ 1$ns_ attach-agent $node_WSN($CENTRAL_STATION)

$tcp_WSN($CENTRAL_STATION->$j)

set ftp_WSN($CENTRAL_STATION->$j) [new Application/FTP]$ftp_WSN($CENTRAL_STATION->$j) attach-agent

$tcp_WSN($CENTRAL_STATION->$j)$ftp_WSN($CENTRAL_STATION->$j) set type_ FTP

}}

}

# create reciever for each WSN stationfor {set i 0} {$i <= $CENTRAL_STATION} {incr i} {

if {$i != $CENTRAL_STATION} {set sink($CENTRAL_STATION->$i) [new Agent/TCPSink/DelAck]$ns_ attach-agent $node_WSN($i) $sink($CENTRAL_STATION->$i) $ns_ connect $tcp_WSN($CENTRAL_STATION->$i) $sink($CENTRAL_STATION->$i)

} else {# create recievers for central stationfor {set j 0} {$j < $CENTRAL_STATION} {incr j} {

set sink($j->$CENTRAL_STATION) [new Agent/TCPSink/DelAck]$ns_ attach-agent $node_WSN($CENTRAL_STATION) $sink($j-

>$CENTRAL_STATION) $ns_ connect $tcp_WSN($j->$CENTRAL_STATION) $sink($j-

>$CENTRAL_STATION)}

}}

}

############################### proc CentralMonitor ################################ monitoring of base station ###############################proc CentralMonitor { index } {

global ns_ tracefd qmonCentral routerQueueLoad loadMap ftp_WSN prevParrivalsCS NUM_OF_ROUTERS CENTRAL_STATION

# get queue_monitor parameters set nowtime [$ns_ now] set parrivals [$qmonCentral($index) set parrivals_]

# output queue_monitor parameters to the output fileset packets [expr $parrivals-$prevParrivalsCS($index)]if {$packets < 0} {

set packets 0}set prevParrivalsCS($index) $parrivals

puts $tracefd "MONITOR_ON_CENTRAL_STATION_$index - $nowtime - Arrived packets (new): $parrivals packets"

# here we update the global loadMap by summering all the load on this routerfor {set i 0} {$i < $NUM_OF_ROUTERS} {incr i} {

if {$i == $index} {

66

The Technion Electrical Engineering Networked Software Systems Laboratory

continue}set loadMap($i->$index) $routerQueueLoad($i->$index)set routerQueueLoad($i->$index) 0

}

# send message to the sensor$ftp_WSN($CENTRAL_STATION->$index) producemore 1

}

########################### proc SensorMonitor ############################################################## monitoring of sensors for messages from Central Station #############################################################proc SensorMonitor { index } {

global ns_ loadMap tracefd qmonSensor prevParrivalsS trace_drop NUM_OF_ROUTERS dropsDS

set nowtime [$ns_ now]set parrivals [$qmonSensor($index) set parrivals_]

set packets [expr $parrivals-$prevParrivalsS($index)]if {$packets < 0} {

set packets 0}set prevParrivalsS($index) $parrivals

puts $tracefd "MONITOR_ON_SENSOR_$index - $nowtime - Arrived packets: $packets packets"

#---------------------------------------GetDropsOn [lindex $sep_el 0] [lindex $sep_el 1]----------------------------------

for {set i 0} {$i < $NUM_OF_ROUTERS} {incr i} {set dropped 0foreach curr [array names dropsDS] {

set sep [split $curr ',']set from [lindex $sep 0]set to [lindex $sep 1]

if {$from == $i && $to == $index} {

set d [GetDropsOn $from $to]set a [GetSentOn $from $to]

if {$a != 0} {set dropped_perc [expr ($d * 100)/ $a ]

} else {set dropped_perc 0

}

set nowtime [$ns_ now]puts $trace_drop "$nowtime $from $to $dropped_perc $d $a"

}}

}

LoadDistributionAlgorithm $index }

# ======================================================================# Routers Network# ======================================================================# ======================================================================# Router network define options# ======================================================================set NUM_OF_ROUTERS $val(nn)set SERVICE_TEMPO "0.5Mb"set PROPOGATION_TIME 0.01set QUEUE_TYPE "DropTail"set ROUTER_QUEUE_LIMIT 3

67

The Technion Electrical Engineering Networked Software Systems Laboratory

set array prevParrivals

#################################### proc BuildTopology_ROUTERS ##################################### Builds routers network topology ####################################

proc BuildTopology_ROUTERS {} { global ns_ node_ROUTER SERVICE_TEMPO PROPOGATION_TIME QUEUE_TYPE QUEUE_LIMIT

NUM_OF_ROUTERS qmonRouter ROUTER_QUEUE_LIMIT routerQueueLoad trace_all_fd

# Create a simulator object$ns_ rtproto Manual#$ns_ set-address-format expanded$curr_cwnd$ns_ set-address-format def ;#flat format

# Create nodesfor {set i 0} {$i < $NUM_OF_ROUTERS} {incr i} {

set node_ROUTER($i) [$ns_ node] $node_ROUTER($i) shape box

}

# Connect the nodes (click)for {set i 0} {$i < $NUM_OF_ROUTERS} {incr i} {

for {set j 0} {$j < $NUM_OF_ROUTERS} {incr j} {if {$i != $j} {

$ns_ duplex-link $node_ROUTER($i) $node_ROUTER($j) $SERVICE_TEMPO $PROPOGATION_TIME $QUEUE_TYPE

$ns_ queue-limit $node_ROUTER($i) $node_ROUTER($j) $ROUTER_QUEUE_LIMIT

$ns_ queue-limit $node_ROUTER($j) $node_ROUTER($i) $ROUTER_QUEUE_LIMIT

# create trace callbackset newLink1 [$ns_ link $node_ROUTER($i) $node_ROUTER($j)]set newLink2 [$ns_ link $node_ROUTER($j) $node_ROUTER($i)]$newLink1 trace-callback $ns_ "ParseTraceLine"$newLink2 trace-callback $ns_ "ParseTraceLine"

}}

}

# Set Monitoring on the network (x-->y)for {set i 0} {$i < $NUM_OF_ROUTERS} {incr i} {

for {set j 0} {$j < $NUM_OF_ROUTERS} {incr j} {if {$i == $j} {

continue}# set the monitorset qmonRouter($i->$j) [$ns_ monitor-queue $node_ROUTER($i) $node_ROUTER($j) 0]# set the global load array to 0 = "no load"set routerQueueLoad($i->$j) 0

}}

}

########################################### proc FTPoverTCP_ROUTERS ############################################ Builds FTP over TCP in routers network #curr_cwnd##########################################proc FTPoverTCP_ROUTERS {} {

global ns_ node_ROUTER NUM_OF_ROUTERS tracefd SIMULATION_TIME ftp_ROUTER tcp_ROUTER val trace_cwnd

#Setup a FTP over TCP connectionfor {set i 0} {$i < $NUM_OF_ROUTERS} {incr i} {

# create and attach n senders to i-th routerfor {set j 0} {$j < $NUM_OF_ROUTERS} {incr j} {

if {$i == $j} {continue

}

68

The Technion Electrical Engineering Networked Software Systems Laboratory

set tcp_ROUTER($i->$j) [new Agent/TCP/Newreno]$ns_ attach-agent $node_ROUTER($i) $tcp_ROUTER($i->$j)$tcp_ROUTER($i->$j) set fid_ $i$j$tcp_ROUTER($i->$j) set maxcwnd_ 63

# trace the cwnd of all active flows$tcp_ROUTER($i->$j) trace cwnd_$tcp_ROUTER($i->$j) attach $trace_cwnd

set ftp_ROUTER($i->$j) [new Application/FTP]$ftp_ROUTER($i->$j) attach-agent $tcp_ROUTER($i->$j)$ftp_ROUTER($i->$j) set type_ FTP

set sink($i->$j) [new Agent/TCPSink/DelAck]$ns_ attach-agent $node_ROUTER($i) $sink($i->$j)

}}

# connect senders to recieversfor {set i 0} {$i < $NUM_OF_ROUTERS} {incr i} {

for {set j 0} {$j < $NUM_OF_ROUTERS} {incr j} {if {$i == $j} {

continue}

$ns_ connect $tcp_ROUTER($i->$j) $sink($j->$i)}

}

ScheduleNetworkSimulation 3}

################################################## proc RouterMonitor ################################################### Here we define a que monitor output procedure ##################################################proc RouterMonitor { from to } { global ns_ tracefd qmonRouter tcp_WSN ftp_WSN prevParrivals CENTRAL_STATION routerQueueLoad NUM_OF_ROUTERS

# get queue_monitor parameters set nowtime [$ns_ now] set parrivals [$qmonRouter($from->$to) set parrivals_] set barrivals [$qmonRouter($from->$to) set barrivals_] set pdepartures [$qmonRouter($from->$to) set pdepartures_] set pdrops [$qmonRouter($from->$to) set pdrops_] set bdrops [$qmonRouter($from->$to) set bdrops_]

# send load message if there is anyif {[info exists prevParrivals($from->$to)]} {

set routerLoad [expr $parrivals - $prevParrivals($from->$to)] ;# /delta_T

} else {set routerLoad $parrivals

}

if { $routerLoad > 0 } {set routerQueueLoad($from->$to) $routerLoad

# puts "$nowtime - Send from sensor $to to the base station. ( load($from=>$to) ~ $routerLoad )"

} else {# puts "$nowtime - No traffic on $from=>$to"

}

$ftp_WSN($to->$CENTRAL_STATION) producemore 1

set prevParrivals($from->$to) $parrivals}

69

The Technion Electrical Engineering Networked Software Systems Laboratory

proc SetMonitorSchedulers {} {global ns_ SIMULATION_TIME NUM_OF_ROUTERS

# We want to schedule some queue output statements at x second increments.for {set t 1} {$t < $SIMULATION_TIME} {set t [expr $t + 1]} {

for {set i 0} {$i < $NUM_OF_ROUTERS} {incr i} {for {set j 0} {$j < $NUM_OF_ROUTERS} {incr j} {

if {$i == $j} {continue

}

# activate routers' monitors$ns_ at $t "RouterMonitor $i $j"}

}

# We want to schedule some Central Monitor statements at x second increments.for {set i 0} {$i < $NUM_OF_ROUTERS} {incr i} {

$ns_ at $t "CentralMonitor $i"}

# We want to schedule some sensors' statements at x second increments.for {set i 0} {$i < $NUM_OF_ROUTERS} {incr i} {

$ns_ at $t "SensorMonitor $i"}

}

}

proc ResetLoadMap {} {global loadMap

if {[info exists loadMap]} { unset loadMap

}}

##############################tcpTick_# proc finish ################################Define a 'finish' procedure ###############################proc finish {} { global ns_ tracefd trace_all_fd tcp_ROUTER trace_cwnd trace_drop

$ns_ flush-trace

close $trace_cwnd close $trace_drop close $tracefd close $trace_all_fd

exit 0}

# ====================================================================================================================================# Main Program# ====================================================================================================================================

# =======================================================================# Initialize Global Variables# =======================================================================

proc main {} {

70

The Technion Electrical Engineering Networked Software Systems Laboratory

global ns_ tracefd trace_all_fd loadMap prevParrivalsCS prevParrivalsS NUM_OF_ROUTERS SIMULATION_TIME node_WSN trace_cwnd trace_drop tcp_ROUTER

set ns_ [new Simulator]

# output files# monitoring outputset trace_cwnd [open cwnd.tr w]set trace_drop [open drop.tr w]set tracefd [open qmonitor.tr w]set trace_all_fd [open traceAll.tr w+]

$ns_ trace-all $trace_all_fd

#Routers networkBuildTopology_ROUTERSBuildRoutes_ROUTERS 3FTPoverTCP_ROUTERS

#WSN networkBuildTopology_WSNBuildRoutes_WSNFTPoverTCP_WSN

for {set i 0} {$i < $NUM_OF_ROUTERS} {incr i} {set prevParrivalsCS($i) 0set prevParrivalsS($i) 0

}

SetMonitorSchedulers

# Tell wireless nodes when the simulation endsfor {set i 0} {$i < $NUM_OF_ROUTERS } {incr i} { $ns_ at [expr $SIMULATION_TIME-1] "$node_WSN($i) reset";}

$ns_ at [expr $SIMULATION_TIME] "finish"

ResetFlowsDS

# Run simulation$ns_ run

}

source SetNetworkRoutingMap.tclsource LoadDistribution.tclsource testLoadDistribution.tclsource Bellman-Ford_SPT.tcl

main

# ==========================================================================================

71

The Technion Electrical Engineering Networked Software Systems Laboratory

Matlab code for graphs generation: plotter.m

fid=fopen('Before\cwnd.tr');cwnd_data=textscan(fid,'%f %d %d %d %d %s %f', 'headerlines', 0);fclose(fid);cwnd_data_1 = cell2mat(cwnd_data(1));cwnd_data_2 = cell2mat(cwnd_data(2));cwnd_data_4 = cell2mat(cwnd_data(4));cwnd_data_7 = cell2mat(cwnd_data(7));m = length(cwnd_data_1);

fid=fopen('Before\drop.tr');drop_data=textscan(fid,'%d %d %d %d %d %d', 'headerlines', 0);fclose(fid);drop_data_1 = cell2mat(drop_data(1));drop_data_2 = cell2mat(drop_data(2));drop_data_3 = cell2mat(drop_data(3));drop_data_4 = cell2mat(drop_data(4));drop_data_6 = cell2mat(drop_data(6));

n = length(drop_data_1);

CWND_TIMES = [];CWND = [];

DROP_TIMES = [];DROP = [];

AVG_CWND_TIMES = [];AVG_CWND = [];

src = 5;dst = 4;

i = 1;k = 1;while (i <= m) if (cwnd_data_2(i) == src) & (cwnd_data_4(i) == dst) CWND(k) = cwnd_data_7(i); CWND_TIMES(k) = cwnd_data_1(i); k = k + 1; end; i = i + 1;end;

i = 1k = 1AVG_CWND_TIMES(1) = 0AVG_CWND(1) = 0;DROP_TIMES(1) = 0;DROP(1) = 0;

SIMULATION_TIME = 11while (i <= SIMULATION_TIME) DROP_TIMES(i+1) = i; AVG_CWND_TIMES(i+1) = i; DROP(DROP_TIMES(i+1)+1) = 0;

j = 0; sum = 0; while(cwnd_data_1(k) <= i && k < m ) if (cwnd_data_2(k) == src) & (cwnd_data_4(k) == dst) sum = sum + cwnd_data_7(k); j = j + 1; end; k = k + 1; end;

if (j>0) AVG_CWND(i+1) = sum / j; else

72

The Technion Electrical Engineering Networked Software Systems Laboratory

AVG_CWND(i+1) = 0; end;

i = i + 1;end;

i = 1;while (i <= n) if (drop_data_2(i) == src) && (drop_data_3(i) == dst) DROP(drop_data_1(i)+1) = drop_data_4(i); end; i = i + 1;end;

figure();

subplot(3,2,1);plot(DROP_TIMES, DROP, '--rs', 'MarkerEdgeColor', 'k','MarkerFaceColor', 'g');xlim([1 SIMULATION_TIME-1])title(['Before: Source - ',num2str(src), ' Destination - ', num2str(dst)]);ylabel('Dropped packets [%]');xlabel('Time [sec]=[iteration]');

subplot(3,2,3);plot(CWND_TIMES, CWND, 'b');xlim([1 SIMULATION_TIME-1])ylim([1 70])ylabel('CWND [packets]');xlabel('Time [sec]');

subplot(3,2,5);plot(AVG_CWND_TIMES, AVG_CWND, 'g');xlim([1 SIMULATION_TIME-1])ylim([1 70])ylabel('Average CWND [packets]');xlabel('Time [sec]=[iteration]');

fid=fopen('After\cwnd.tr');cwnd_data=textscan(fid,'%f %d %d %d %d %s %f', 'headerlines', 0);fclose(fid);cwnd_data_1 = cell2mat(cwnd_data(1));cwnd_data_2 = cell2mat(cwnd_data(2));cwnd_data_4 = cell2mat(cwnd_data(4));cwnd_data_7 = cell2mat(cwnd_data(7));m = length(cwnd_data_1);

fid=fopen('After\drop.tr');drop_data=textscan(fid,'%d %d %d %d %d %d', 'headerlines', 0);fclose(fid);drop_data_1 = cell2mat(drop_data(1));drop_data_2 = cell2mat(drop_data(2));drop_data_3 = cell2mat(drop_data(3));drop_data_4 = cell2mat(drop_data(4));drop_data_6 = cell2mat(drop_data(6));

n = length(drop_data_1);

CWND_TIMES = [];CWND = [];

DROP_TIMES = [];DROP = [];

AVG_CWND_TIMES = [];AVG_CWND = [];

i = 1;k = 1;while (i <= m) if (cwnd_data_2(i) == src) & (cwnd_data_4(i) == dst) CWND(k) = cwnd_data_7(i); CWND_TIMES(k) = cwnd_data_1(i); k = k + 1; end;

73

The Technion Electrical Engineering Networked Software Systems Laboratory

i = i + 1;end;

i = 1k = 1AVG_CWND_TIMES(1) = 0AVG_CWND(1) = 0;DROP_TIMES(1) = 0;DROP(1) = 0;

while (i <= SIMULATION_TIME) DROP_TIMES(i+1) = i; AVG_CWND_TIMES(i+1) = i; DROP(DROP_TIMES(i+1)+1) = 0;

j = 0; sum = 0; while(cwnd_data_1(k) <= i && k < m ) if (cwnd_data_2(k) == src) & (cwnd_data_4(k) == dst) sum = sum + cwnd_data_7(k); j = j + 1; end; k = k + 1; end;

if (j>0) AVG_CWND(i+1) = sum / j; else AVG_CWND(i+1) = 0; end;

i = i + 1;end;

i = 1;while (i <= n) if (drop_data_2(i) == src) && (drop_data_3(i) == dst) DROP(drop_data_1(i)+1) = drop_data_4(i); end; i = i + 1;end;

subplot(3,2,2);plot(DROP_TIMES, DROP, '--rs', 'MarkerEdgeColor', 'k','MarkerFaceColor', 'g');xlim([1 SIMULATION_TIME-1])title(['After: Source - ',num2str(src), ' Destination - ', num2str(dst)]);ylabel('Dropped packets [%]');xlabel('Time [sec]=[iteration]');

subplot(3,2,4);plot(CWND_TIMES, CWND, 'b');xlim([1 SIMULATION_TIME-1])ylim([1 70])ylabel('CWND [packets]');xlabel('Time [sec]');

subplot(3,2,6);plot(AVG_CWND_TIMES, AVG_CWND, 'g');xlim([1 SIMULATION_TIME-1])ylim([1 70])ylabel('Average CWND [packets]');xlabel('Time [sec]=[iteration]');

74

The Technion Electrical Engineering Networked Software Systems Laboratory

References

Books

[1] The NS Manual 2008Kevin Fall & Kannan Varadhan

[2] The NS Manual 2009Kevin Fall & Kannan Varadhan

[3] Internet networking course booklet (236341) A/Prof. Reuven Cohen

Websites

[1] http://www.wikipedia.com – useful information about Internet Technologies and Routing Protocols.

[2] http://www.scribd.com/doc/6505211/Introduction-NS2-Simulator - NS-2 simulator introduction.

[3] http://wapedia.mobi/en/ns%28simulator%29#1 – NS-2 simulator manual.

[4] http://nsnam.isi.edu/nsnam/index.php/NS-2_Trace_Formats -NS-2 trace formats.

[5] http://www.winlab.rutgers.edu/~zhibinwu/html/network_simulator_2.html- NS-2 for wireless.

[6] http://www.cse.msu.edu/~wangbo1/ns2/ - contains documentation on basic principles and tools of NS-2 and references for other NS-2 web resources.

[7] http://www.isi.edu/nsnam/ns - Information Sciences Institute, useful information about NS-2.

[8] http://www.nabble.com/Network-Simulator-ns-2-f15582.html- NS-2 forum, contains useful information and solutions.

[9] http://cs-people.bu.edu/guol/bu_ns/buns-faq.html - NS-2 compilation problems and solutions.

[10] http://www.mathworks.com/ - Tutorials and help on Matlab

75