31 NS-3

Report
NS-3 Tutorial
2013.05.16
Hojin Lee
내용
•
•
•
•
•
•
•
NS-3 현황 / 설치
핵심 클래스
보조 클래스
간단 예제
로그
트레이스
그 외..
시작하기 전에…
• 이 슬라이드는 제가 만든 부분도 있지만,
인터넷에서 검색되는 다른 분이 만든 슬라
이드도 많이 이용했습니다.
• 그 분들께 심심한 감사를…
NS-3
• Ns-3 is targeted at networking research.
Discrete event simulator
Packet level simulator
Layered architecture
Wired and wireless network
NS-3 status
• Periodic update
– Latest version is ns-3.17 (May 2013)
• Supporting platform
– FreeBSD, Linux, SunOS, Solaris, Windows (cygwin), OS X
• Free, open source software project
• Website
– http://www.nsnam.org/
– Can find the doxygen, reference manual, and tutorial
NS-3 components
• 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
NS-3 all-in-one package Directory Structure
ns-allinone-3.12.1
ns-3.12.1
nsc-0.5.2
...
Pybindgen0.15.0.795
...
bindings
examples
...
src
error-model
csma
mobility
network
...
...
Example
simulation
scripts
build
How to Install NS-3
•
Ns-3 download: http://www.nsnam.org/download.html
• ns-allinone-3.12.1.tar.bz2
–
–
[[email protected] ~]# tar xvf ns-allinone-3.12.1.tar.bz2
[[email protected] ~]# cd ns-allinone-3.12.1
• Building
–
[[email protected] ~/ns-allinone-3.12.1]# ./build.py
• Setting environment
–
–
–
–
[[email protected] ~/ns-allinone-3.12.1/ns-3.12.1]# ./waf –d optimized configure
[[email protected] ~/ns-allinone-3.12.1/ns-3.12.1]# ./waf –d debug configure
[[email protected] ~/ns-allinone-3.12.1/ns-3.12.1]# ./waf
[[email protected] ~/ns-allinone-3.12.1/ns-3.12.1]# ./test.py –c core
Simple Example
• cd ns-allinone-3.12.1/ns-3.12.1
• /ns-3.12.1$ ./waf --run scratch/scratch-simulator
• Output
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
핵심 클래스
• Node
– 패킷을 주고 받는 노드
– 이 자체는 특별한 기능이 없음
– 여기에 네트워크 장치, 네트워크 프로토콜 스택 등을 설치해야 함
• NetDevice
– 네트워크 장치
– PointToPointNetDevice, CsmaNetDevice, WifiNetDevice, …
• Channel
– 네트워크 채널: 정보가 흘러가는 논리적 경로
– 일반적으로 NetDevice와 1:1 대응
– PointToPointChannel, CsmaChannel, WifiChannel, …
• Application
– 응용
– UdpEchoSever, UdpEchoClient, OnOffApplication, BulkSendApplication,
…
NS-3 기본 모델
Application
Application
Application
Application
Sockets-like
API
Protocol
stack
Protocol
stack
Packet(s)
Node
NetDevice
NetDevice
Node
Channel
Channel
NetDevice
NetDevice
보조 클래스
• 핵심클래스 + @로부터 시뮬레이션 시나리오 작성을 도와주는 클래
스
• XXXContainer
– 그릇: 벡터를 품고 있음  일괄작업 용이
• std::vector<Ptr<XXX> >
– 주요 멤버함수
• Ptr<XXX> Get (uint32_t)
• uint32_t GetN ()
– NodeContainer, NetDeviceContainer, Ipv4InterfaceContainer,
ApplicationContainer
• XXXHelper
– 생성 및 설치를 도움
• 생성: 공장(ObjectFactory)을 품고 있음
– 주요 멤버함수
• SetYYY (…): 찍어낼 객체의 속성을 정함
• Install (…): 객체를 생성해서 설치 (생성된 객체를 담아서 XXXContainer로 리턴)
간단 예제 (1/3)
• 노드 2개 사이에 point-to-point 링크, 패킷 한 개 echo
#include
#include
#include
#include
#include
"ns3/core-module.h"
"ns3/network-module.h"
"ns3/internet-module.h"
"ns3/point-to-point-module.h"
"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);
간단 예제 (2/3)
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.)));
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;
}
간단 예제 (2/3)
• ../ns-3.12.1] ./waf –-run scratch/example1
• Output
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)
•
•
맞게 잘 짰나?
어, 왜 안되지……?
•
컴포넌트별로, 수준별로 로그를 on/off
•
src/applications/model/udp-echo-client.cc
– gdb
– printf
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);
}
…
}
로그 (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로 하면 누적
트레이스
• 시뮬레이션의 목적 – 성능 평가
– 트레이스로부터…
• High level
– 시뮬레이터에서 제공하는 종합적인 트레이스 이용
– 트레이스 파일을 나의 목적에 맞게 parsing해야 함
• Low level
– 내가 원하는 자료만 출력이 되도록 매번 직접 소스 코
드를 수정
• Mid level
– ???
High Level (1/3)
• IP 이상 계층
– 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: 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)
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)
2.000000 IP 10.1.1.1.49153 > 10.1.1.2.9: UDP, length 1024
2.514648 IP 10.1.1.2.9 > 10.1.1.1.49153: UDP, length 1024
$ tcpdump -nn -tt -r myfirst-1-0.pcap
reading from file myfirst-1-0.pcap, link-type PPP (PPP)
2.257324 IP 10.1.1.1.49153 > 10.1.1.2.9: UDP, length 1024
2.257324 IP 10.1.1.2.9 > 10.1.1.1.49153: UDP, length 1024
High Level (3/3)
• Reading output with Wireshark
• http://www.wireshark.org/download.html
Mid Level
• Trace source와 trace sink의 분리
– Trace source
• 원천,
• 관심이 있는 상태의 변화가 발생하거나, 관심 있는 데이터 변경 시 그 이벤
트를 생성
• 평소에는 비활성화, trace sink와 연결(connect)해야 활성화 됨
• 미리 프로그램되어 있음
– Trace sink
• 이벤트 및 관련 정보를 소비
• 사용자가 추가
Mid Level
• 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.12-14.
간단 예제 (1/2)
#include
#include
#include
#include
#include
"ns3/object.h"
"ns3/uinteger.h"
"ns3/traced-value.h"
"ns3/trace-source-accessor.h"
<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;
Provides the “hooks” used for connecting the
}
MyObject () {}
trace source to the outside the config system
TracedValue<int32_t> m_myInt;
};
Provides the infrastructure that overloads
the operators and drives callback process
간단 예제 (2/2)
void
IntTrace (int32_t oldValue, int32_t newValue)
{
std::cout << "Traced " << oldValue << " to " << newValue << std::endl;
}
Trace sink; callback function: this function will be called whenever
the overloaded operators of the TracedValue is excuted
int
main (int argc, char *argv[])
{
Ptr<MyObject> myObject = CreateObject<MyObject> ();
myObject->TraceConnectWithoutContext ("MyInteger", MakeCallback(&IntTrace));
myObject->m_myInt = 1234;
}
Connect between trace source and trace sink
Operator”=” invoke the Callback
Mid Level
• TracedValue <xxx>
– 연산자 overloading
– Callback 함수의 인자가
고정
• TracedCallback <…>
– TracedValue보다 flexible
TracedCallback 간단 예제
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 = 7.27897, y = 2.22677
…
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
– http://www.nsnam.org/docs/release/3.16/doxygen/group_
__trace_source_list.html
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, …
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;
–
–
–
–
NS-3
The
The
The
The
parent type
name of the type
list of attributes (their name, their type, etc.)
list of trace sources (their name, their type, etc.)
31
시뮬레이션 파라미터 설정 (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”
시뮬레이션 파라미터 설정 (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”
TIPs
• 작은 걸음
• Refactoring
– 중복제거, 가독성
– 부채
• 사람의 실수가 개입할 여지가 없게
• 구체화와 추상화
추천 도서
•
실용주의 프로그래머
•
리팩터링: 코드 품질을 개선하는 객체지향 사고법
•
임베디드 C를 위한 TDD
•
테스트 주도 개발
•
익스트림 프로그래밍

similar documents