Presentation is loading. Please wait.

Presentation is loading. Please wait.

NS-3 Tutorial 2013.05.16 Hojin Lee 한글로 만들자.

Similar presentations


Presentation on theme: "NS-3 Tutorial 2013.05.16 Hojin Lee 한글로 만들자."— Presentation transcript:

1 NS-3 Tutorial Hojin Lee 한글로 만들자

2 내용 NS-3 현황 / 설치 핵심 클래스 보조 클래스 간단 예제 로그 트레이스 그 외.. 기존 발표 자료 활용
1 시간 – 시간 안배 너무 많이 담으려고 하지 말자 15분 발표 5분 휴식 (질의 응답)

3 시작하기 전에… 이 슬라이드는 제가 만든 부분도 있지만, 인터넷에서 검색되는 다른 분이 만든 슬라이드도 많이 이용했습니다.
그 분들께 심심한 감사를…

4 NS-3 Ns-3 is targeted at networking research.

5 NS-3 status Periodic update Supporting platform
Latest version is ns-3.17 (May 2013) Supporting platform FreeBSD, Linux, SunOS, Solaris, Windows (cygwin), OS X Free, open source software project Website Can find the doxygen, reference manual, and tutorial

6 NS-3 components Ns-3 simulator Pre-processing Post-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

7 NS-3 all-in-one package Directory Structure
Example simulation scripts

8 How to Install NS-3 ns-allinone-3.12.1.tar.bz2 Building
Ns-3 download: ns-allinone tar.bz2 ~]# tar xvf ns-allinone tar.bz2 ~]# cd ns-allinone Building ~/ns-allinone ]# ./build.py Setting environment ~/ns-allinone /ns ]# ./waf –d optimized configure ~/ns-allinone /ns ]# ./waf –d debug configure ~/ns-allinone /ns ]# ./waf ~/ns-allinone /ns ]# ./test.py –c core

9 Simple Example cd ns-allinone-3.12.1/ns-3.12.1
/ns $ ./waf --run scratch/scratch-simulator Output

10 Workspace /ns-allinone-3.12.1/ns-3.12.1/scratch
Run program only in the scratch folder Run program by the commands below ./waf --run scratch/example (or) ./waf --run example

11 핵심 클래스 Node NetDevice Channel Application 패킷을 주고 받는 노드
이 자체는 특별한 기능이 없음 여기에 네트워크 장치, 네트워크 프로토콜 스택 등을 설치해야 함 NetDevice 네트워크 장치 PointToPointNetDevice, CsmaNetDevice, WifiNetDevice, … Channel 네트워크 채널: 정보가 흘러가는 논리적 경로 일반적으로 NetDevice와 1:1 대응 PointToPointChannel, CsmaChannel, WifiChannel, … Application 응용 UdpEchoSever, UdpEchoClient, OnOffApplication, BulkSendApplication, … 객체지향

12 NS-3 기본 모델 Application Sockets-like API Protocol stack Packet(s)‏ Node
NetDevice Sockets-like API Channel Packet(s)‏

13 보조 클래스 핵심클래스 + @로부터 시뮬레이션 시나리오 작성을 도와주는 클래스 XXXContainer XXXHelper
그릇: 벡터를 품고 있음  일괄작업 용이 std::vector<Ptr<XXX> > 주요 멤버함수 Ptr<XXX> Get (uint32_t) uint32_t GetN () NodeContainer, NetDeviceContainer, Ipv4InterfaceContainer, ApplicationContainer XXXHelper 생성 및 설치를 도움 생성: 공장(ObjectFactory)을 품고 있음 SetYYY (…): 찍어낼 객체의 속성을 정함 Install (…): 객체를 생성해서 설치 (생성된 객체를 담아서 XXXContainer로 리턴) 시나리오 작성 로그 트레이스 그래프

14 간단 예제 (1/3) 노드 2개 사이에 point-to-point 링크, 패킷 한 개 echo
#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);

15 간단 예제 (2/3) InternetStackHelper stack; stack.Install (nodes);
Ipv4AddressHelper address; address.SetBase (" ", " "); 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.))); 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; }

16 간단 예제 (2/3) ../ns-3.12.1] ./waf –-run scratch/example1 Output
Sent 1024 bytes to Received 1024 bytes from Received 1024 bytes from

17 로그 (1/2) 맞게 잘 짰나? 어, 왜 안되지……? 컴포넌트별로, 수준별로 로그를 on/off
gdb printf 컴포넌트별로, 수준별로 로그를 on/off src/applications/model/udp-echo-client.cc NS_LOG_COMPONENT_DEFINE ("UdpEchoClientApplication"); void UdpEchoClient::Send (void) { NS_LOG_FUNCTION (this); if (Ipv4Address::IsMatchingType (m_peerAddress)) { NS_LOG_INFO ("At time " << Simulator::Now ().GetSeconds () << "s client sent " << m_size << " bytes to " << Ipv4Address::ConvertFrom (m_peerAddress) << " port " << m_peerPort); } 로그와 트레이스

18 로그 (2/2) 로그 매크로 로그 켜기 NS_LOG_ERROR NS_LOG_WARN NS_LOG_DEBUG
NS_LOG_INFO NS_LOG_FUNCTION NS_LOG_LOGIC NS_LOG_ALL NS_LOG_UNCOND 로그 켜기 시나리오 스크립트 수정: LogComponent (“컴포넌트명”, 로그수준) 로그 수준: NS_ 제외, LOG_LEVEL_XXX로 하면 누적 환경변수: export 컴포넌트명=로그수준 로그수준: 소문자, NS_LOG_ 제외, level_xxx로 하면 누적

19 트레이스 시뮬레이션의 목적 – 성능 평가 High level Low level Mid level 트레이스로부터…
시뮬레이터에서 제공하는 종합적인 트레이스 이용 트레이스 파일을 나의 목적에 맞게 parsing해야 함 Low level 내가 원하는 자료만 출력이 되도록 매번 직접 소스 코드를 수정 Mid level ???

20 High Level (1/3) IP 이상 계층 Mac 이상 계층
void InternetStackHelper::EnableAsciiIpv4All (std::string prefix) void InternetStackHelper::EnablePcapIpv4All (std::string prefix) Mac 이상 계층 void AsciiTraceHelperForDevice::EnableAscii (std::string prefix) void PcapHelperForDevice::EnableAscii (std::string prefix) + 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: > ) ns3::UdpHeader (length: > 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: > ) ns3::UdpHeader (length: > 9) Payload (size=1024) 상속

21 High Level (2/3) PCAP Tracing .pcap file format Traffic trace analyze
pointToPoint.EnablePcapAll (“myfirst”); Reading output with tcpdump $ tcpdump -nn -tt -r myfirst-0-0.pcap reading from file myfirst-0-0.pcap, link-type PPP (PPP) IP > : UDP, length 1024 IP > : UDP, length 1024 $ tcpdump -nn -tt -r myfirst-1-0.pcap reading from file myfirst-1-0.pcap, link-type PPP (PPP) IP > : UDP, length 1024 IP > : UDP, length 1024

22 High Level (3/3) Reading output with Wireshark

23 Mid Level Trace source와 trace sink의 분리 Trace source Trace sink 원천,
관심이 있는 상태의 변화가 발생하거나, 관심 있는 데이터 변경 시 그 이벤트를 생성 평소에는 비활성화, trace sink와 연결(connect)해야 활성화 됨 미리 프로그램되어 있음 Trace sink 이벤트 및 관련 정보를 소비 사용자가 추가

24 Mid Level Callback Relation between tracing system and callback
The object is to allow a piece of code to call a function without any specific inter-module dependency Treat the address of the called function as a variable, i.e. a pointer-to-function variable Decouple the calling function from the called class completely Relation between tracing system and callback A trace source is a callback When a trace sink wants to know information given by a trace source, it add its own function to the callback list. It is good for students who want to know callbacks further to refer callback part in ns-3 manual pp

25 간단 예제 (1/2) #include "ns3/object.h" #include "ns3/uinteger.h" #include "ns3/traced-value.h" #include "ns3/trace-source-accessor.h" #include <iostream> using namespace ns3; class MyObject : public Object { public: static TypeId GetTypeId (void) static TypeId tid = TypeId ("MyObject") .SetParent (Object::GetTypeId ()) .AddConstructor<MyObject> () .AddTraceSource ("MyInteger", "An integer value to trace.", MakeTraceSourceAccessor (&MyObject::m_myInt)) ; return tid; } MyObject () {} TracedValue<int32_t> m_myInt; }; Provides the “hooks” used for connecting the trace source to the outside the config system Provides the infrastructure that overloads the operators and drives callback process

26 간단 예제 (2/2) Connect between trace source and trace sink
void IntTrace (int32_t oldValue, int32_t newValue) { std::cout << "Traced " << oldValue << " to " << newValue << std::endl; } int main (int argc, char *argv[]) Ptr<MyObject> myObject = CreateObject<MyObject> (); myObject->TraceConnectWithoutContext ("MyInteger", MakeCallback(&IntTrace)); myObject->m_myInt = 1234; Trace sink; callback function: this function will be called whenever the overloaded operators of the TracedValue is excuted Connect between trace source and trace sink Operator”=” invoke the Callback

27 Mid Level TracedValue <xxx> TracedCallback <…>
연산자 overloading Callback 함수의 인자가 고정 TracedCallback <…> TracedValue보다 flexible 실용적인 예: congestion window trace

28 TracedCallback 간단 예제 //Trace Sink //Config Path
void CourseChange (std::string context, Ptr<const MobilityModel> model) { Vector position = model->GetPosition (); NS_LOG_UNCOND (context << " x = " << position.x << ", y = " << position.y); } //Trace Sink std::ostringstream oss; oss << "/NodeList/" << wifiStaNodes.Get (nWifi - 1)->GetId () << "/$ns3::MobilityModel/CourseChange"; //Config Path Config::Connect (oss.str (), MakeCallback (&CourseChange)); //Connection between Trace Source and Sink Output Result: /NodeList/7/$ns3::MobilityModel/CourseChange x = , y =

29 Mid Level bool ObjectBase::TraceConnectWithoutContext (std::string name, const CallbackBase& cb) void Config::ConnectWithoutContext (std::string path, const Callback& cb) 멤버 함수 아님 (Config – namespace) path Trace sources

30 Config name, full name  attribute system
void Config::SetDefault (std::string name, const AttributeValue& value) void Config::Set (std::string path, const AttributeValue& value) AttributeValue IntegerValue, UintegerValue, DoubleValue, StringValue, …

31 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

32 시뮬레이션 파라미터 설정 (1/2) 명령행 인자로 시뮬레이션 파라미터를 바꿀 수 있음 main 함수 내에 아래 두 줄 추가
CommandLine cmd; cmd.Parse (argc, argv); 예제 ./waf --run "scratch/example1 --PrintHelp” ./waf –-run “scratch/example1 --PrintAttributes=ns3::PointToPointNetDevice” ./waf --run “scratch/example1 --ns3::PointToPointNetDevice::DataRate=5Mbps –ns3::PointToPointChannel::Delay=2ms”

33 시뮬레이션 파라미터 설정 (2/2) 명령행 인자 변수를 추가할 수 있음 예제
cmd.AddValue (…) 이용 예제 int 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”

34 TIPs 작은 걸음 Refactoring 중복제거, 가독성 부채 사람의 실수가 개입할 여지가 없게 구체화와 추상화

35 추천 도서 실용주의 프로그래머 리팩터링: 코드 품질을 개선하는 객체지향 사고법 임베디드 C를 위한 TDD 테스트 주도 개발
익스트림 프로그래밍


Download ppt "NS-3 Tutorial 2013.05.16 Hojin Lee 한글로 만들자."

Similar presentations


Ads by Google