740 likes | 1.17k Views
NS-3 Tutorial 및 프로토콜 구현 방법. 한국기술교육대학교 컴퓨터공학부 - 한연희 교수 yhhan@kut.ac.kr 고려대학교 융합소프트웨어 전문대학원 - 최현영 연구교수 neongas@korea.ac.kr. 2011 년도 한국통신학회 단기강좌. NS-3 Introduction. What is NS-3?. NS-3 is a discrete-event network simulator for Internet systems http://www.nsnam.org
E N D
NS-3 Tutorial 및 프로토콜 구현 방법 한국기술교육대학교 컴퓨터공학부 - 한연희 교수 yhhan@kut.ac.kr 고려대학교 융합소프트웨어 전문대학원 - 최현영 연구교수 neongas@korea.ac.kr 2011년도 한국통신학회 단기강좌
NS-3 Introduction NS-3
What is NS-3? • NS-3 is a discrete-event network simulator for Internet systems • http://www.nsnam.org • targeted primarily for research and educational use. • intended to eventually replace the ns-2 simulator • not backwards-compatible with ns-2 • a free, open source software project organized around research community development and maintenance • NS-3 is a GNU GPLv2-licensed project • Open mailing lists • http://www.nsnam.org/developers/tools/mailing-lists • ~30 maintainers worldwide NS-3
What is NS-3? • Main Groups • University of Washington (Tom Henderson), Georgia Tech (George Riley), Bucknell (Felipe Perrone) • Financial Support • U.S. National Science Foundation (NSF) & INRIA • Project timeline: 2010-14 • All code for merge to ns-3 is openly reviewed by maintainers • Syntactic (style) reviews • Design reviews • Documentation and tests • Papers using NS-3 starting to appear • http://www.nsnam.org/overview/publications NS-3
Language: NS-2 vs. NS-3 • Language aspect • ns-2 • simulator core: c++ and Otcl • script: Otcl • ns-3 • simulator core: NS-3 core is written entirely in C++ • script: user code - protocols and scenarios - also in C++ • Python wrappers for user code also exist, but can run ns-3 without any knowledge of Python NS-3
NS-3 Progress Report • Current Release • ns-3.12.1 (Aug 31, 2011) • Progress Report (1/3) • ns-3.1 : June 2008 NS-3
NS-3 Progress Report • Progress Report (2/3) • ns-3-3.9 (August 20, 2010) • Spectrum Modeling • OFDM • Underwater Acoustic Network • WiFi patches for bugs, etc. • See the page: http://www.nsnam.org/wiki/index.php/Ns-3.9 • ns-3-3.10 (Jan., 2011) • DSDV (Destination Sequenced Distance Vector) routing • Initial support for the 802.11g PHY • Consolidate Wi-Fi MAC high functionality • Energy model WiFi additions • New TCP • 3GPP LTE support, etc. • See the page: http://www.nsnam.org/wiki/index.php/Ns-3.10 NS-3
NS-3 Progress Report • Progress Report (3/3) • ns-3-3.11 (May, 2011) • The build system has been modularized, and the source code reorganized • Python bindings have also been modularized • An interface to an OpenFlow software implementation distribution has been added • Click Modular Routing • ns-3-3.12.1 (Aug 31, 2011) • SpectrumChannel models now support the usage of single-frequency propagation loss models based on the PropagationLossModel class • Support for IPv4 fragmentation has been added NS-3
Available modules (NS-3.11 May 2011) devices protocols utilities config- store bridge spectrum applications aodv csma flow-monitor dsdv tap-bridge internet energy emu uan netanim olsr mpi point-to- point virtual- net-device click stats mobility nix-vector- routing topology- read network lte wifi propagation core mesh wimax visualizer NS-3
NS-3 Features • Features (1/3) • Clean slate design from ns2, aiming to be easier to use and more ready for extension • Alignment with real systems • BSD-lookalike - sockets, device driver interfaces • Standard input/output formats so that other tools can be reused. • e.g., PCAP (tcpdump/wireshark) trace output • ns-3 is adding “running implementation code” • e.g., Linux TCP code NS-3
NS-3 Features • Features (2/3) • Looks just like IP architecture stack Application Application Application Application Sockets-like API Protocol stack Protocol stack Packet(s) Node Node NetDevice NetDevice NetDevice Channel NetDevice Channel NS-3 basic simulation model NS-3
NS-3 Features • Features (3/3) • Nodes have “network devices,” e.g. WiFi, CSMA • NetDevices transfer packets over Channels • Incorporating Layer 1 (Physical) & Layer 2 (Link) • A node can be equipped with multiple network interfaces. • Wireless Support • WiFi, WiMAX, UMTS (PPP) • Devices interface with Layer 3 (Network: IP, ARP) • Layer 3 supports Layer 4 (Transport: UDP, TCP) • Layer 4 is used by Layer 5 (Application) objects • Can run real implementation of applications. • Various Network Access Types • P2P link, shared link with CSMA. • Support (nearly) complete IPv6 NS-3
NS-3 Features • Extensively documented API (doxygen): • http://www.nsnam.org/documentation NS-3
Key Abstractions • Node • basic computing device abstraction • Node class provides methods for managing computing devices • An ns-3 Node is a husk of a computer to which applications, stacks, and NICs are added Application Application Application NS-3
virtual machine virtual machine Network Emulation • Network Emulation real machine ns-3 ns-3 real machine real machine ns-3 Testbed 1) ns-3 interconnects virtual machines 2) testbeds interconnect ns-3 stacks Added in ns-3.3 Added in ns-3.5 NS-3
NS-3 attribute system • Researchers want to know all of the values in effect in their simulations • and configure them easily • In NS-3 • Each ns-3 object has a set of attributes: • A name, help text • A type • An initial value • Object attributes are organized and documented in the Doxygen • Control all simulation parameters for static objects • Dump and read them all in configuration files • Visualize them in a GUI • Makes it easy to verify the parameters of a simulation NS-3
Key Abstractions • Application • user’s program to be simulated • Application class provides methods for managing user-level applications • Channel • medium connected by nodes • Channel class provides methods for managing communication media and connecting nodes to them. • Specialized Channel • CsmaChannel: Ethernet • PointToPointChannel • WifiChannel NS-3
Key Abstractions • Net device • like Network Interface Cards (NICs) • NICs are controlled using network device drivers collectively known as “net devices” • In Linux, you refer to these “net devices” by names such as eth0 • In NS-3, “net device” abstraction covers both the software driver and the simulated hardware • It enables a node to communicate with other nodes in simulation via channels • NetDevice class provides methods for managing connections to Node and Channel objects • a Node may be connected to more than one Channel via multiple NetDevices. • Specialized Channel • CsmaNetDevice • PointToPointNetDevice • WifiNetDevice NS-3
Key Abstractions • Topology helpers • In a large simulated network you will need to arrange many connections between Nodes, NetDevices and Channels. • By using “Topology helper” object, we can connect NetDevices to Nodes, NetDevices to Channels, and assign IP addresses to NetDevices NS-3
Additional third-party project releases • PhySim: high-fidelity physical layer model for 5 GHz OFDM • http://dsn.tm.uni-karlsruhe.de/english/ns3-physim.php • SliceTime: time synchronization between Xen PVMs and ns-3 • http://www.comsys.rwth-aachen.de/research/projects/slicetime • Multipath TCP: IETF TCP extensions • http://code.google.com/p/mptcp-ns3 • LENA project: LTE/EPC network simulator • http://www.ubiquisys.com/femtocell-media-press-releases-id-203.htm • ns-3 DCE: Direct Code Execution environment • http://www-sop.inria.fr/members/Mathieu.Lacage/dce.html • LTE: Univ. of Padua, HARQ and MOBILITY modules • https://sourceforge.net/projects/ns3-lte • Content Addressable Networks DHT • http://mailman.isi.edu/pipermail/ns-developers/2010-November/008460.html NS-3
Course usage • Georgia Tech (George Riley) • ECE 6110; http://users.ece.gatech.edu/~riley/ece6110 • University of Kansas (James Sterbenz) • EECS 882; http://www.ittc.ku.edu/~jpgs/courses/mwnets • University of Pennsylvania (Boon Thau Loo) • CIS553; http://netdb.cis.upenn.edu/cis553projects NS-3
Challenges for ns-3 • NS-3 lacks an integrated development/visualization environment (IDE) • NS-3 needs participation from the research community • 1) improving simulation credibility • 2) contributed and supported models • 3) maintainers NS-3
NS-3 Installation • Environment Recommendation Ubuntu in VirtualBox • Download ns-3.11 (all-in-one package recommended) • Download directly from http://www.nsnam.org • Or using mercurial tool (Ubuntu) home~$ wget http://www.nsnam.org/releases/ns-allinone-3.11.tar.bz2 home~$ tar xvfj ns-allinone-3.11.tar.bz2 home~$ sudo apt-get install mercurial home~$ mkdir repos home~$ cd repos home~$ hg clone http://code.nsnam.org/ns-3-allinone home~$ ls ns-3-allinone home~$ cd ns-3-allinone home~$ ls build.py* constants.py dist.py* download.py* README util.py home~$ ./download.py -n ns-3.11 NS-3
NS-3 Installation • Build NS-3.11 (all-in-one) version • Setting environment • Hello Simulator example ns-allinone-3.11$ ./build.py --enable-examples --enable-tests ns-allinone-3.11$ cd ns-3.11 ns-3.11$ ./waf -d optimized configure ns-3.11$ ./waf -d debug configure ns-3.11$ ./waf ns-3.11$ ./test.py -c core ns-3.11$ ./waf --run hello-simulator Waf: Entering Directory ‘/home/ns-allinone-3.11/ns-3.11/build’ Waf: Leaving Directory ‘/home/ns-allinone-3.11/ns-3.11/build’ ‘build’ finished successfully (0.677s) Hello Simulator NS-3
waf • Python-based framework, meta-build system • waf [command] [options] • waf commands • build (default) • configure • clean • distclean • install • waf options • - -run=program • - -pyrun=python-program • - -command-template=“template” • e.g.: - -command-template=“gdb - -args %s” NS-3
Tutorial #1 – UDP Echo System • examples/tutorial/first.cc (1/6) int main (int argc, char *argv[]) { LogComponentEnable (“UdpEchoClientApplication”, LOG_LEVEL_INFO); LogComponentEnable (“UdpEchoServerApplication”, LOG_LEVEL_INFO); CommandLine cmd; cmd.Parse (argc, argv); NodeContainer nodes; nodes.Create (2); nodes: NodeContainer Node 0 Node 1 NS-3
Tutorial #1 – UDP Echo System • examples/tutorial/first.cc (2/6) PointToPointHelper pointToPoint; pointToPoint.SetDeviceAttribute ("DataRate", StringValue ("5Mbps")); pointToPoint.SetChannelAttribute ("Delay", StringValue ("2ms")); NetDeviceContainer devices; devices = pointToPoint.Install (nodes); devices: NetDeviceContainer 5Mbit/s, 2ms Node 0 Node 1 PointToPointNetDevice NS-3
Tutorial #1 – UDP Echo System • examples/tutorial/first.cc (3/6) InternetStackHelper stack; stack.Install (nodes); Ipv4AddressHelper address; address.SetBase ("10.1.1.0", "255.255.255.0"); Ipv4InterfaceContainer interfaces = address.Assign (devices); interfaces: Ipv4InterfaceContainer 10.1.1.1 10.1.1.1 Ipv4Interface Node 0 Node 1 PointToPointNetDevice NS-3
Tutorial #1 – UDP Echo System • examples/tutorial/first.cc (4/6) UdpEchoServerHelper echoServer (9); ApplicationContainer serverApps = echoServer.Install (nodes.Get (1)); serverApps.Start (Seconds (1.0)); serverApps.Stop (Seconds (10.0)); serverApps: ApplicationContainer UdpEchoServer Node 0 Node 1 NS-3
Tutorial #1 – UDP Echo System • examples/tutorial/first.cc (5/6) UdpEchoClientHelper echoClient (interfaces.GetAddress (1), 9); echoClient.SetAttribute (“MaxPackets”, UintegerValue (1)); echoClient.SetAttribute (“Interval”, TimeValue (Seconds (1.))); echoClient.SetAttribute (“PacketSize”, UintegerValue (1024)); ApplicationContainer clientApps = echoClient.Install (nodes.Get (0)); clientApps.Start (Seconds (2.0)); clientApps.Stop (Seconds (10.0)); clientApps: ApplicationContainer Dest: 10.1.1.2, port 9 UdpEchoClient UdpEchoServer 1 packet, 1024 bytes Node 0 Node 1 NS-3
Tutorial #1 – UDP Echo System • examples/tutorial/first.cc (6/6) UdpEchoClient UdpEchoServer [...] Simulator::Run (); Simulator::Destroy (); return 0; } Node 0 (10.1.1.1) Node 1 (10.1.1.2) 1 UDP Packet 2 UDP Packet 3 $ ./waf --run first [...] Sent 1024 bytes to 10.1.1.2 Received 1024 bytes from 10.1.1.1 Received 1024 bytes from 10.1.1.2 1 2 3 NS-3
Internal API Overview • Simulator Core • Random Variables • Memory Management • Object Aggregation • NS-3 Type System • Debugging support • Tracing • Callback Objects • Nodes • Packets • Packet: Headers and Trailers • NS-3 Sockets NS-3
Simulator Core • Time is not manipulated directly: the Time class • Time class supports high precision 128 bit time values (nanosecond precision) Time t1 = Seconds (10); Time t2 = t1 + MilliSeconds (100); std::cout << t2.GetSeconds () << std::endl; //t2 = 10.1 • Get current time: • Time now = Simulator::Now (); • Schedule an event to happen in 3 seconds: • void MyCallback (T1 param1, T2 param2) {…} …. Simulator::Schedule (Seconds (3), MyCallback, param1, param2); • Also works with instance methods: Simulator::Schedule (Seconds (3), &MyClass::Method, instancePtr, param1, param2); NS-3
Random Variables • Currently implemented distributions • Uniform: values uniformly distributed in an interval • Constant: values is always the same (not really random) • Sequential: return a sequential list of predefined values • Exponential: exponential distribution (poisson process) • Normal (gaussian) • Log-normal • pareto, weibull, triangular, • … import pylab import NS-3 rng = NS-3.NormalVariable(10.0, 5.0) x = [rng.GetValue() for t in range(100000)] pylab.hist(x, 100) pylab.show() NS-3
Memory Management • Many NS-3 objects use automatic garbage collection • Reference counting • Packet *p = new Packet; // refcount initialized to 1 p->Ref (); // refcount becomes 2 p->Unref (); // refcount becomes 1 p->Unref (); // refcount becomes 0, packet is freed • Smart Pointers • Manual reference counting is error prone • Can easily lead to memory errors • Smart Pointers • Take care of all the reference counting work • Otherwise they behave like normal pointers • Example: void MyFunction () { Ptr<Packet> p = Create<Packet> (10); std::cerr << “Packet size: “ << p->GetSize () << std::endl; } //Packet is released (smart pointer goes out of scope) NS-3
Object Aggregation • A circular singly linked-list • AggregateObject() is a constant-time operation • GetObject() is a O(n) operation • Aggregate contains only one object of each type Node MobilityModel Node MobilityModel Ptr<Node> node=CreateObject<Node>(); Ptr<MobilityModel> mm=CreateObject<MobilityModel>(); node->AggregateObject (mm); Ptr<Ipv4> ipv4 = CreateObject<Ipv4>(); node->AggregateObject(ipv4); //Query Ptr<Ipv4> ipv4=node->GetObject<Ipv4>(); Ipv4 Node MobilityModel Ipv4 NS-3
NS-3 Type System • The aggregation mechanism needs information about the type of objects at runtime • The attribute mechanism needs information about the attributes supported by a specific object • The tracing mechanism needs information about the trace sources supported by a specific object • All this information is stored in NS-3::TypeId; • The parent type • The name of the type • The list of attributes (their name, their type, etc.) • The list of trace sources (their name, their type, etc.) NS-3
NS-3 Type System (cont.) • Derive from the NS-3::Object base class • Define a GetTypeId static method: • Define the features of the object: • call NS_OBJECT_ENSURE_REGISTERED macro in source code class MyClass : public Object { public: static TypeId GetTypeId(); }; TypeId MyClass::GetTypeId() { static TypeId tid = TypeId(“NS-3::MyClass”) .SetParent<Object>() .SetAttribute(“Name”, “Help”, ...) .AddTraceSource (“Name”, “Help”, ...); return tid; } NS_OBJECT_ENSURE_REGISTERED (MyClass); NS-3
Debugging Support • Assertions: NS_ASSERT (expression); • Aborts the program if expression evaluates to false • Includes source file name and line number • Unconditional Breakpoints: NS_BREAKPOINT (); • Forces an unconditional breakpoint, compiled in • Debug Logging (not to be confused with tracing!) • Purpose • Used to trace code execution logic • For debugging, not to extract results! • properties • NS_LOG* macros work with C++ IO streams • e.g.: NS_LOG_LOGIC (“I have received ” << p->GetSize() << “bytes”); • NS_LOG* macros evaluate to nothing in optimized builds • When debugging is done, logging does not get in the way of execution performance NS-3
Debugging Support (cont.) • Logging levels: • NS_LOG_ERROR (…): serious error messages only • NS_LOG_WARN (…): warning messages • NS_LOG_DEBUG (…): rare ad-hoc debug messages • NS_LOG_INFO (…): informational messages (e.g. banners) • NS_LOG_FUNCTION (…): function tracing • NS_LOG_PARAM (…): parameters to functions • NS_LOG_LOGIC (…): control flow tracing within functions • Logging “components” • Logging messages organized by components • Usually one component is one .cc source file • NS_LOG_COMPONENT_DEFINE (“OslrAgent”); • Displaying log messages. Two ways: • Programatically: • LogComponentEnable (“OslrAgent”, LOG_LEVEL_ALL); • From the environment: • NS_LOG=“OslrAgent” ./my-program NS-3
Tracing (by example) uint64_t g_packetDrops = 0; uint64_t g_packetDropBytes = 0; void TraceDevQueueDrop (std::string context, Ptr<const Packet> droppedPacket) { g_packetDrops += 1; g_packetDropBytes += droppedPacket->GetSize (); } int main (int argc, char *argv[]) { […] Config::Connect (“/NodeList/*/DeviceList/*/TxQueue/Drop”, MakeCallback (&TraceDevQueueDrop)); […] } NodeList 0..* NodeList Node 0..* DeviceList CsmaNetDevice TxQueue 1 Queue NS-3
Callback Objects • NS-3 Callback class implements function objects • Type safe callbacks, manipulated by value • used for example in sockets and tracing • Example double MyFunc (int x, float y) { return double (x+y)/2; } Callback<double, int, float> cb1; cb1 = MakeCallback (MyFunc); double result = cb1 (2, 3); //result receives 2.5 ------------------------------------------------------------------------------------------------- class MyClass { public: double MyMethod (int x, float y) { return double (x+y)/2; }}; Callback<double, int, float> cb1; MyClass myobj; cb1 = MakeCallback (&MyClass::MyMethod, &myObj); double result = cb1 (2, 3); //result receives 2.5 NS-3
Nodes • Node class • Represents a network element • May have an IPv4 stack object • But it is completely optional! • May have a mobility model • But it is optional • Contains a list of NetDevices • Contains a list of Applications • NodeList class (singleton) • Tracks all nodes ever created • Node index Ptr conversions Application NodeList 1 0..* Aggregates 0..* 1 IPv4 Node MobilityModel 1 0..* NetDevice NS-3
Packets • Packet objects used vertically in NS-3 to represent: • Units of information sent and received by applications • Information chunks of what will becomes a real packet (similar sk_buff in Linux kernel) • Simulated packets and L2/L1 frames being transmitted • Basic Usage • Create empty packet • Ptr<Packet> packet = Create<Packet> (); • Create packet with 10 “dummy” bytes • Ptr<Packet> packet = Create<Packet> (10); • Create packet with user data • Ptr<Packet> packet = Create<Packet> (“hello”, 5); • Copy a packet • Ptr<Packet> packet2 = packet1->Copy (); • Note: packet copy is usually cheap (copy-on-write) NS-3
Packet: Headers and Trailers • Packets support headers and trailers • Headers and trailers are implemented as classes that • Implement a Serialize method: • Writes the header information as a byte stream; • Implement a Deserialize method: • Reads the header information from a byte stream; • Headers and trailers used to implement protocols • Packets contain exact byte contents • They are not just structure as in NS-2 • Allows writing pcap trace files, readable from wireshark NS-3
Packet: Headers and Trailers (cont.) • LLC/SNAP header example • Adding a header • Removing a header uint32_t LlcSnapHeader::GetSerializedSize (void) const { return 8; } void LlcSnapHeader::Serialize (Buffer::Iterator start) const { Buffer::Iterator i = start; uint8_t buf[] = { 0xaa, 0xaa, 0x03, 0, 0, 0}; i.Write (buf, 6); i.WriteHtonU16 (m_etherType); } uint32_t LlcSnapHeader::Deserialize (Buffer::Iterator start) { Buffer::Iterator i = start; i.Next (5+1); m_etherType = i.ReadNtohU16 (); return GetSerializedSize (); } DSAP SSAP Ctrl. 00 00 00 Ethertype LlcSnapHeader llcsnap; llcsnap.SetType (0x0800); //IPv4 packet->AddHeader (llcsnap); LLC(3bytes) SNAP(5bytes) LlcSnapHeader llcsnap; packet->RemoveHeader (llcsnap); NS-3
NS-3 Sockets • Plain C sockets int sk; sk = socket (PF_INET, SOCK_DGRAM, 0); struct sockaddr_in src; inet_pton(AF_INET, “0.0.0.0”, &src.sin_addr); src.sin_port = htons(80); bind(sk, (struct sockaddr *)&src, sizeof(src)); struct sockaddr_in dest; inet_pton(AF_INET, “10.0.0.1”, &dest.sin_addr); dest.sin_port = htons(80); sendto(sk, “hello”, 6, 0, (struct sockaddr *)&dest, sizeof(dest)); char buf[6]; recv(sk, buf, 6, 0); • NS-3 sockets Ptr<SocketFactory> udpFactory=node-> GetObject<UdpSocketFactory> (); Ptr<Socket> sk = udpFactory->CreateSocket (); InetSocketAddress src = InetSocketAddress (Ipv4Address::GetAny(), 80); sk->Bind (src); InetSocketAddress dest = InetSocketAddress (Ipv4Address(“10.0.0.1”), 80); sk->SendTo (dest, Create<Packet> (“hello”, 6)); sk->SetReceiveCallback (MakeCallback (MySocketReceive)); void MySocketReceive (Ptr<Socket> sk) { char buf[6]; sk->Recv (buf, 6, 0); } NS-3
Tutorial #2 • Making a new agent called “MyAgent” • It communicates each other using IPv4 with protocol number (250) • New packet header “MyHeader” is used for information exchange • source IP, destnation IP, and sequence 0 32 source IP destination IP sequence MyHeader MyAgent MyAgent IPv4 PPP Node1 Node2 NS-3