52
Computer Network Laboratory Introduction to NS3 2014.9.23 Dohyung Kim Computer network lab, [email protected]

Dohyung Kim Computer network lab,

Embed Size (px)

DESCRIPTION

Why simulate? Field tests are expensive Experiments can be hard to reproduce Collaboration is not easy

Citation preview

Page 1: Dohyung Kim Computer network lab,

Computer Network Laboratory

Introduction to NS3

2014.9.23

Dohyung Kim

Computer network lab, [email protected]

Page 2: Dohyung Kim Computer network lab,

Computer Network Laboratory

Why simulate? Field tests are expensive

Experiments can be hard to reproduce

Collaboration is not easy

Page 3: Dohyung Kim Computer network lab,

Computer Network Laboratory

What is NS?

NS is a discrete-event network simulator for in-ternet system- Protocol design, prototyping, multiple level of abstrac-

tion NS has a companion network animator called

nam

Has been called the nsnam project

Page 4: Dohyung Kim Computer network lab,

Computer Network Laboratory

NS history (~ns-2)

1995

1997

• Ns-1 (LBNL)

- C++, Tcl - Event driven

• Core Ns-2 develop-ment

- split object architecture - detailed TCP models - scheduler, queuing, links - routing, wireless, satel-lite - nam, topology genera-tor

2000

• Mainly integration of contributed code

- Sensor network MAC and routing - SCTP and XCP - Wireless enhancement

Page 5: Dohyung Kim Computer network lab,

Computer Network Laboratory

Ns-2 impact

Over 50% of ACM and IEEE network simulation papers from 200s0-2004 cite the use of ns-2

* Source: ACM Digital Library and IEEExplore searches

Page 6: Dohyung Kim Computer network lab,

Computer Network Laboratory

Skepticism abounds

“...Tragedy of the Commons...”“...around 50% of the papers appeared to be... bogus...”“Who has ever validated NS2 code?”“To be honest, I'm still not sure whether I will use a simula-tion in a paper.”“...I will have a hard time accepting or advocating the use of NS-2 or any other simulation tool”

* September 2005 archives of the e2e-interest mailing list

“For years, the community had to rely on simulators, which now seem a little dated, and it’s not clear who was convinced to adopt anything new based on ns2 simulations;”

* Nick McKeown, VINI public review, ACM Sigcomm 2006

Page 7: Dohyung Kim Computer network lab,

Computer Network Laboratory

TrendsMany researcher move away from simulation Experiments and testbed start to be preferred in

major conference papers- PlanetLab, OneLab, VINI, Emulab, ORBIT,

WhyNet,..

Yet simulation tools proliferate Ns-2, OMNET++, NetSim, NCTUns, QualNet, OP-

NET, P2PSim, ONE, …

Page 8: Dohyung Kim Computer network lab,

Computer Network Laboratory

NS-3 A discrete event simulator Modular design / Open source Actively developed (contrast to NS-2) Developed in C++ / Python biding available Live visualizer Logging facility for debugging Tracing facility of getting output Direct Code Execution (DCE)

- Can be connected to a real network

Page 9: Dohyung Kim Computer network lab,

Computer Network Laboratory

Discrete Event Simulator Simulation time moves directly from event to

event Schedule events to occur at specific simulation

times A simulation scheduler orders the event execution Simulator execute events one by one Simulation stops at specific time or when events

end

Page 10: Dohyung Kim Computer network lab,

Computer Network Laboratory

NS-3 Component NS-3 simulator

Pre-processing- Traffic / topology generation- Alignment with real systems (sockets, device driver interfaces)

Post-processing- NS-3 output file (trace file) analysis

Throughput, delay, jitter, drop- Various tracing system- Graph

xgraph, gnuplot

Page 11: Dohyung Kim Computer network lab,

Computer Network Laboratory

Installation www.nsnam.org Latest release ns-3.21

- Source download link https://

www.nsnam.org/release/ns-allinone-3.21.tar.bz2

- Documentation download link http://www.nsnam.org/ns-3-21/documentation

Installation manual- http://www.nsnam.org/wiki/Installation

Page 12: Dohyung Kim Computer network lab,

Computer Network Laboratory

How to Install Building

- [user@eins ~/ns-allinone-3.21]# ./build.py

Setting environment - [user@eins~/ns-allinone-3.21/ns-3.21]# ./waf –d opti-

mized configure- [user@com ~/ns-allinone-3.21/ns-3.21]# ./waf -d

debug --enable-examples --enable-tests configure- [user@com ~/ns-allinone-3.21/ns-3.21]# ./waf- [user@com ~/ns-allinone-3.15/ns-3.15]# ./test.py –c

core

Page 13: Dohyung Kim Computer network lab,

Computer Network Laboratory

Workspace /ns-allinone-3.21/ns-3.21/scratch

Run program only in the scratch folder

Run program by the commands below- ./waf --run scratch/example- (or) ./waf --run example

Page 14: Dohyung Kim Computer network lab,

Computer Network Laboratory

NS-3 Basic Model

ApplicationApplication

Protocolstack

Node

NetDeviceNetDevice

ApplicationApplication

Protocolstack

Node

NetDeviceNetDevice

Sockets-like API

Channel

Channel

Packet(s)

Page 15: Dohyung Kim Computer network lab,

Computer Network Laboratory

Core Classes Node

- No specific functionality- Host(end system) in the Internet- Install a net device and a network protocol

Application- A user program that generates some activity to be simu-

lated- UdpEchoServer, UdpEchoClient, OnOffApplication, Bulk-

SendApplication, …

Page 16: Dohyung Kim Computer network lab,

Computer Network Laboratory

Core Classes Channel

- Medium connected by nodes over which data flows- Generally one-to-one mapped with NetDevice- PointToPointchannel, CsmaChannel, WifiChannel, …

NetDevice- Like a specific kind of network cable and a hardware de-

vice- Provides methods for managing connection to Node and

channel- PointToPointNetDevice, CsmaNetDevice, WifiNetDevice,

Page 17: Dohyung Kim Computer network lab,

Computer Network Laboratory

Helper API A set of classes and methods that make common

operation easier than using low level APIs

Consists of- Container objects- Helper classes

Page 18: Dohyung Kim Computer network lab,

Computer Network Laboratory

Container A part of the ns-3 “helper API”

Often simulation will need to do a number of identical actions to group of objects

The helper API makes heavy use of containers of similar objects to which similar to identical opera-tion can be performed

Page 19: Dohyung Kim Computer network lab,

Computer Network Laboratory

Helper classes Each function does a single operation on a “set of

same objects”

Provides simple ‘syntactical sugar’ to make simu-lation scripts look nicer and easier to read for network researchers

Page 20: Dohyung Kim Computer network lab,

Computer Network Laboratory

Container and Helper

Page 21: Dohyung Kim Computer network lab,

Computer Network Laboratory

Container and Helper example

Page 22: Dohyung Kim Computer network lab,

Computer Network Laboratory

Attribute Attributes are exported into a string-based

namespace, with filesystem-like paths- namespace supports regular expressions- Nodes with NodeIds 1, 3, 4, 5, 8, 9, 10, 11:

“/NodeList/[3-5]|[8-11]|1”

Attributes also can be used without the paths- e.g. “ns3::WifiPhy::TxGain”

Page 23: Dohyung Kim Computer network lab,

Computer Network Laboratory

Attribute A Config class allows users to manipulate the at-

tributes- e.g.: Set a default initial value for a variable

Config::Set (“ns3::WifiPhy::TxGain”, DoubleValue (1.0));

- Syntax also supports string values: Config::Set (“WifiPhy::TxGain”, StringValue (“1.0”));

- AttributeValue IntegerValue, UintegerValue, DoubleValue, String-

Value, …

Page 24: Dohyung Kim Computer network lab,

Computer Network Laboratory

Attribute Attribute namespace

- strings are used to describe paths through the names-pace

Refer to doxygen documents

Page 25: Dohyung Kim Computer network lab,

Computer Network Laboratory

NS-3 program structure

Page 26: Dohyung Kim Computer network lab,

Computer Network Laboratory

Simulation procedure

1. Turning on logging

2. Creating network topology

3. Creating application

4. Running simulator

Page 27: Dohyung Kim Computer network lab,

Computer Network Laboratory

Simulation procedure Turning on logging

- Define log component NS_LOG_COMPONENT_DEFINE ( name )

- Enable log component LogComponentEnable ( name, level )

Page 28: Dohyung Kim Computer network lab,

Computer Network Laboratory

Logging Module Output messages from modules Useful when debugging NS_LOG environment variable NS_LOG_FUNCTION level information Verbosity level

- NS_LOG_ERROR — Log error messages;- NS_LOG_WARN — Log warning messages;- NS_LOG _EBUG — Log relatively rare debugging messages;- NS_LOG_INFO — Log informational messages about program progress;- NS_LOG_FUNCTION — Log a message describing each function called;- NS_LOG_LOGIC – Log messages describing logical flow within a function;- NS_LOG_ALL — Log everything.- NS_LOG_UNCOND – Log the associated message unconditionally.

Page 29: Dohyung Kim Computer network lab,

Computer Network Laboratory

Command Line Arguments Change the simulation parameters using command line ar-

guments

First declare the command line parser in main functionCommandLine cmd;cmd.Parse (argc, argv);

Example- ./waf --run "scratch/example1 –PrintHelp”- ./waf –-run “scratch/example1 –

PrintAttributes=ns3::PointToPointNetDevice”- ./waf --run “scratch/example1 -

ns3::PointToPointNetDevice::DataRate=5Mbps –ns3::PointToPointChannel::Delay=2ms”

Page 30: Dohyung Kim Computer network lab,

Computer Network Laboratory

Command Line Arguments When add your own hooks.

- cmd.AddValue in main function

Exampleint main (int argc, char *argv[]){

uint32_t nPackets =1;

CommandLine cmd;cmd.AddValue("nPackets", "Number of packets to echo", nPackets);Cmd.Parse (argc, argv);…echoClient.SetAttribute (“MaxPackets”, UintegerValue (nPackets));

./waf --run “scratch/example1 –nPackets=2”

Page 31: Dohyung Kim Computer network lab,

Computer Network Laboratory

Simulation procedure Creating Network Topology

- Use Topology Helpers

- NodeContainer NodeContainer Ptr<Node> NodeContainer::Create (n) n: # of Nodes

e.g.) NodeContainer nodes;nodes.Create (2);

Page 32: Dohyung Kim Computer network lab,

Computer Network Laboratory

CreateObject<> (); CreateObject<> is a wrapper for operator new.

ns3::Object objects must be created on the heap using CreateObject<> (), which returns a smart pointer; e.g.

Ptr<Node> rxNode = CreateObject<Node> ();

Page 33: Dohyung Kim Computer network lab,

Computer Network Laboratory

Create<> (); Create<> is simply a wrapper around operator

new that correctly handles the reference counting system

For objects deriving from class SimpleRefCount

Ptr<Packet> p = Create<Packet> (data,size);

Page 34: Dohyung Kim Computer network lab,

Computer Network Laboratory

Simulation ProcedurePointToPointHelper

void PointToPointHelper::SetDeviceAttribute (name, value)void PointToPointHelper::SetChannelAttribute (name, value)NetDeviceContainer PointToPointHelper::Install (N-odeContainer c)

NetDeviceContainerNetDeviceContainer Ptr<NetDevice>

PointToPointHelper pointToPoint;pointToPoint.SetDeviceAttribute ("DataRate", StringValue ("5Mbps"));pointToPoint.SetChannelAttribute ("Delay", StringValue ("2ms"));NetDeviceContainer devices;devices = pointToPoint.Install (nodes);

Page 35: Dohyung Kim Computer network lab,

Computer Network Laboratory

Simulation ProcedureUdpEchoServerHelper

UdpEchoServerHelper::UdpEchoServerHelper ( port )ApplicationContainer UdpEchoServerHelper::Install (NodeContainer c )

UdpEchoClientHelperUdpEchoClientHelper::UdpEchoClientHelper ( ip, port )void UdpEchoClientHelper::Setattribute ( name, value )ApplicationContainer UdpEchoClientHelper::Install (NodeContainer c )UdpEchoServerHelper echoServer (9);

ApplicationContainer serverApps = echoServer.Install (nodes.Get (1));serverApps.Start (Seconds (1.0)); serverApps.Stop (Seconds (10.0));

UdpEchoClientHelper echoClient (interfaces.GetAddress (1), 9);echoClient.SetAttribute ("MaxPackets", UintegerValue (1));echoClient.SetAttribute ("Interval", TimeValue (Seconds (1.0)));echoClient.SetAttribute ("PacketSize", UintegerValue (1024));ApplicationContainer clientApps = echoClient.Install (nodes.Get (0));clientApps.Start (Seconds (2.0)); clientApps.Stop (Seconds (10.0));

Page 36: Dohyung Kim Computer network lab,

Computer Network Laboratory

Start Simulator- Simulator::Run ();

Destroy Simulator- Simulator::Destroy ();

Page 37: Dohyung Kim Computer network lab,

Computer Network Laboratory

Simulation Example

UDP EchoClient10.1.1.1

UDP EchoServer

10.1.1.2P2P interface P2P interface

Transmit a packet at 1s

Upon receiving the packet, echo it

Data rate: 5Mbps, Delay: 2ms

Page 38: Dohyung Kim Computer network lab,

Computer Network Laboratory

#include "ns3/core-module.h" #include "ns3/network-module.h" #include "ns3/internet-module.h" #include "ns3/point-to-point-module.h" #include "ns3/applications-module.h"

using namespace ns3; NS_LOG_COMPONENT_DEFINE ("FirstScriptExample"); int main (int argc, char *argv[])

{ LogComponentEnable("UdpEchoClientApplication", LOG_LEVEL_INFO); LogComponentEnable("UdpEchoServerApplication", LOG_LEVEL_INFO); NodeContainer nodes; nodes.Create (2); PointToPointHelper pointToPoint; pointToPoint.SetDeviceAttribute ("DataRate", StringValue ("5Mbps")); pointToPoint.SetChannelAttribute ("Delay", StringValue ("2ms")); NetDeviceContainer devices; devices = pointToPoint.Install (nodes);

• Simple point-to-point link between two nodes and echo a single packet

Page 39: Dohyung Kim Computer network lab,

Computer Network Laboratory

InternetStackHelper stack; stack.Install (nodes); Ipv4AddressHelper address; address.SetBase ("10.1.1.0", "255.255.255.0"); Ipv4InterfaceContainer interfaces = address.Assign (devices); UdpEchoServerHelper echoServer (9); ApplicationContainer serverApps = echoServer.Install (nodes.Get (1)); serverApps.Start (Seconds (1.0)); serverApps.Stop (Seconds (10.0)); UdpEchoClientHelper echoClient (interfaces.GetAddress (1), 9); echoClient.SetAttribute ("MaxPackets", UintegerValue (1)); echoClient.SetAttribute ("Interval", TimeValue (Seconds (1.0))); echoClient.SetAttribute ("PacketSize", UintegerValue (1024)); ApplicationContainer clientApps = echoClient.Install (nodes.Get (0)); clientApps.Start (Seconds (2.0)); clientApps.Stop (Seconds (10.0)); Simulator::Run (); Simulator::Destroy (); return 0; }

Page 40: Dohyung Kim Computer network lab,

Computer Network Laboratory

Simulation Example ../ns-3.20] ./waf --run scratch/example1

OutputAt time 2s client sent 1024 bytes to 10.1.1.2 port 9At time 2.00369s server received 1024 bytes from 10.1.1.1 port

49153At time 2.00369s server sent 1024 bytes to 10.1.1.1 port 49153At time 2.00737s client received 1024 bytes from 10.1.1.2 port 9

Page 41: Dohyung Kim Computer network lab,

Computer Network Laboratory

Tracing System Tracing is a structured form of simulation output

Page 42: Dohyung Kim Computer network lab,

Computer Network Laboratory

ASCII Tracing

Output (myfirst.tr)+ 2 /NodeList/0/DeviceList/0/$ns3::PointToPointNetDevice/TxQueue/Enqueue ns3::PppHeader (Point-to-Point Protocol: IP (0x0021)) ns3::Ipv4Header (tos 0x0 ttl 64 id 0 protocol 17 offset 0 flags [none] length: 1052 10.1.1.1 > 10.1.1.2) ns3::UdpHeader (length: 1032 49153 > 9) Payload (size=1024)- 2 /NodeList/0/DeviceList/0/$ns3::PointToPointNetDevice/TxQueue/Dequeue ns3::PppHeader (Point-to-Point Protocol: IP (0x0021)) ns3::Ipv4Header (tos 0x0 ttl 64 id 0 protocol 17 offset 0 flags [none] length: 1052 10.1.1.1 > 10.1.1.2) ns3::UdpHeader (length: 1032 49153 > 9) Payload (size=1024)

AsciiTraceHelper ascii;pointToPoint.EnableAsciiAll (ascii.CreateFileStream(“myfirst.tr”)); Simulator::Run ();Simulator::Destroy ();return 0;

Page 43: Dohyung Kim Computer network lab,

Computer Network Laboratory

ASCII Tracing00 + <operation – enqueue operation>01 2 <simulation time>02 /NodeList/0/DeviceList/0/$ns3::PointToPointNetDevice/

TxQueue/Enqueue <trace source>03 ns3::PppHeader ( 04 Point-to-Point Protocol: IP (0x0021)) <Link-layer header info>05 ns3::Ipv4Header (06 tos 0x0 ttl 64 id 0 protocol 17 offset 0 flags [none]07 length: 1052 10.1.1.1 > 10.1.1.2) <IP-header header info>08 ns3::UdpHeader (09 length: 1032 49153 > 9) <TCP-header info>10 Payload (size=1024) <payload info>

Page 44: Dohyung Kim Computer network lab,

Computer Network Laboratory 44

PCAP Tracing Generating packet trace file in .pcap format Can read the .pcap file with Wireshark or tcp-

dump http://www.wireshark.org/download.html

ExamplepointToPoint.EnablePcapAll (“myfirst”); //Right before the call to Simula-tor::Run()

Page 45: Dohyung Kim Computer network lab,

Computer Network Laboratory

Tracing src/internet/model/tcp-tahoe.cc src/internet/model/tcp-

tahoe.h

Page 46: Dohyung Kim Computer network lab,

Computer Network Laboratory

TracingCallback FunctionStatic voidCwndChange (uint32_t oldCwnd, uint32_t newCwnd){ NS_LOG_UNCOND (Simulator::Now ().GetSeconds () << “\t” << newCwnd);}

Static voidRxDrop (Ptr<const Packet> p){ NS_LOG_UNCON (“RxDrop at” << Simulator::Now ().GetSeconds ();}

Connect a trace source and trace sink

ns3TcpSocket->TraceConnectWithoutContext (“CongestionWindow”, MakeCallback (&Cwnd-Change));

devices.Get(1)->TraceConnectWithoutContext (“PhyRxDrop”, MakeCallback (&RxDrop));

Page 47: Dohyung Kim Computer network lab,

Computer Network Laboratory

Tracing Example#include <fstream>#include "ns3/core-module.h“#include "ns3/network-module.h“#include "ns3/internet-module.h“#include "ns3/point-to-point-module.h“#include "ns3/applications-module.h“

using namespace ns3;

NS_LOG_COMPONENT_DEFINE ("FifthScriptExample");

class MyApp : public Application {public:

MyApp (); virtual ~MyApp();

void Setup (Ptr<Socket> socket, Address address, uint32_t packetSize, uint32_t nPackets, DataRate dataRate);

private: virtual void StartApplication (void); virtual void StopApplication (void);

void ScheduleTx (void); void SendPacket (void);

Ptr<Socket> m_socket; Address m_peer; uint32_t m_packetSize; uint32_t m_nPackets; DataRate m_dataRate; EventId m_sendEvent; bool m_running; uint32_t m_packetsSent;};

MyApp::MyApp () : m_socket (0), m_peer (), m_packetSize (0), m_nPackets (0), m_dataRate (0), m_sendEvent (), m_running (false), m_packetsSent (0){}

MyApp::~MyApp(){ m_socket = 0;}

voidMyApp::Setup (Ptr<Socket> socket, Address address, uint32_t packetSize, uint32_t nPackets, DataRate dataRate){ m_socket = socket; m_peer = address; m_packetSize = packetSize; m_nPackets = nPackets; m_dataRate = dataRate;}

voidMyApp::StartApplication (void){ m_running = true; m_packetsSent = 0; m_socket->Bind (); m_socket->Connect (m_peer); SendPacket ();}

Create a simple application

Page 48: Dohyung Kim Computer network lab,

Computer Network Laboratory

Tracing Examplevoid MyApp::StopApplication (void){ m_running = false;

if (m_sendEvent.IsRunning ()) { Simulator::Cancel (m_sendEvent); }

if (m_socket) { m_socket->Close (); }}

void MyApp::SendPacket (void){ Ptr<Packet> packet = Create<Packet> (m_packetSize); m_socket->Send (packet);

if (++m_packetsSent < m_nPackets) { ScheduleTx (); }}

void MyApp::ScheduleTx (void){ if (m_running) { Time tNext (Seconds (m_packetSize * 8 /

static_cast<double> (m_dataRate.GetBitRate ()))); m_sendEvent = Simulator::Schedule (tNext,

&MyApp::SendPacket, this); }}

static voidCwndChange (uint32_t oldCwnd, uint32_t newCwnd){ NS_LOG_UNCOND (Simulator::Now ().GetSeconds () << "\t" << newCwnd);}

static voidRxDrop (Ptr<const Packet> p){ NS_LOG_UNCOND ("RxDrop at " << Simulator::Now ().GetSeconds ());}

int main (int argc, char *argv[]){ NodeContainer nodes; nodes.Create (2);

PointToPointHelper pointToPoint; pointToPoint.SetDeviceAttribute ("DataRate", StringValue ("5Mbps")); pointToPoint.SetChannelAttribute ("Delay", StringValue ("2ms"));

NetDeviceContainer devices; devices = pointToPoint.Install (nodes);

Ptr<RateErrorModel> em = CreateObjectWithAttributes<RateErrorModel> ( "RanVar", RandomVariableValue (UniformVariable (0., 1.)), "ErrorRate", DoubleValue (0.00001)); devices.Get (1)->SetAttribute ("ReceiveErrorModel", PointerValue (em));

InternetStackHelper stack; stack.Install (nodes);

Ipv4AddressHelper address; address.SetBase ("10.1.1.0", "255.255.255.252"); Ipv4InterfaceContainer interfaces = address.Assign (devices);

Trace sink

Page 49: Dohyung Kim Computer network lab,

Computer Network Laboratory

Tracing Example uint16_t sinkPort = 8080; Address sinkAddress

(InetSocketAddress(interfaces.GetAddress (1), sinkPort));

PacketSinkHelper packetSinkHelper ("ns3::TcpSocketFactory", InetSocketAddress (Ipv4Address::GetAny (), sinkPort));

ApplicationContainer sinkApps = pack-etSinkHelper.Install (nodes.Get (1));

sinkApps.Start (Seconds (0.)); sinkApps.Stop (Seconds (20.));

Ptr<Socket> ns3TcpSocket =Socket::CreateSocket (nodes.Get (0),

TcpSocketFactory::GetTypeId ()); ns3TcpSocket->TraceConnectWithoutContext ("Congestion-

Window", MakeCallback (&CwndChange));

Ptr<MyApp> app = CreateObject<MyApp> (); app->Setup (ns3TcpSocket, sinkAddress, 1040, 1000,

DataRate ("1Mbps")); nodes.Get (0)->AddApplication (app); app->SetStartTime (Seconds (1.)); app->SetStopTime (Seconds (20.));

devices.Get (1)->TraceConnectWithoutContext("PhyRxDrop", MakeCall-back (&RxDrop));

Simulator::Stop (Seconds(20)); Simulator::Run (); Simulator::Destroy ();

return 0;}

TCP sink application

TCP application

Connect Cwnd trace source and sink

Connect RxDrop trace source and sink

Page 50: Dohyung Kim Computer network lab,

Computer Network Laboratory

First project Simulation Topology

10 senders and 10 receivers 1 UDP flow and 9 TCP flowsSimulation time: 60 secondsUDP sending rate is increased by 1 Mbps on every 5 seconds

100Mbps, 5ms

Page 51: Dohyung Kim Computer network lab,

Computer Network Laboratory

Expected Simulation Result Trace with different queues

- Per-flow TCP Throughput- Congestion window- Routers’ queue size

Queues- DropTail- RED

Page 52: Dohyung Kim Computer network lab,

Computer Network Laboratory

Submission program file (or files)

- .cc (.h) Documents

- Source code with line-by-line comments- Simulation results