.\" Man page generated from reStructuredText. . . .nr rst2man-indent-level 0 . .de1 rstReportMargin \\$1 \\n[an-margin] level \\n[rst2man-indent-level] level margin: \\n[rst2man-indent\\n[rst2man-indent-level]] - \\n[rst2man-indent0] \\n[rst2man-indent1] \\n[rst2man-indent2] .. .de1 INDENT .\" .rstReportMargin pre: . RS \\$1 . nr rst2man-indent\\n[rst2man-indent-level] \\n[an-margin] . nr rst2man-indent-level +1 .\" .rstReportMargin post: .. .de UNINDENT . RE .\" indent \\n[an-margin] .\" old: \\n[rst2man-indent\\n[rst2man-indent-level]] .nr rst2man-indent-level -1 .\" new: \\n[rst2man-indent\\n[rst2man-indent-level]] .in \\n[rst2man-indent\\n[rst2man-indent-level]]u .. .TH "NS-3-TUTORIAL" "1" "1649059818" "ns-3.35" "ns-3 project" .SH NAME ns-3-tutorial \- ns-3 Tutorial .sp This is the \fIns\-3 Tutorial\fP\&. Primary documentation for the ns\-3 project is available in five forms: .INDENT 0.0 .IP \(bu 2 \fI\%ns\-3 Doxygen\fP: Documentation of the public APIs of the simulator .IP \(bu 2 Tutorial \fI(this document)\fP, Manual, and Model Library for the \fI\%latest release\fP and \fI\%development tree\fP .IP \(bu 2 \fI\%ns\-3 wiki\fP .UNINDENT .sp This document is written in \fI\%reStructuredText\fP for \fI\%Sphinx\fP and is maintained in the \fBdoc/tutorial\fP directory of ns\-3’s source code. .SH QUICK START .sp This section is optional, for readers who want to get \fIns\-3\fP up and running as quickly as possible. Readers may skip forward to the \fI\%Introduction\fP chapter, followed by the \fI\%Getting Started\fP chapter, for a lengthier coverage of all of this material. .SS Brief Summary .sp \fIns\-3\fP is a discrete\-event simulator typically run from the command line. It is written directly in C++, not in a high\-level modeling language; simulation events are simply C++ function calls, organized by a scheduler. .sp An \fIns\-3\fP user will obtain the \fIns\-3\fP source code (see below), compile it into shared (or static) libraries, and link the libraries to \fImain()\fP programs that he or she authors. The \fImain()\fP program is where the specific simulation scenario configuration is performed and where the simulator is run and stopped. Several example programs are provided, which can be modified or copied to create new simulation scenarios. Users also often edit the \fIns\-3\fP library code (and rebuild the libraries) to change its behavior. .sp \fIns\-3\fP has optional Python bindings for authoring scenario configuration programs in Python (and using a Python\-based workflow); this quick start does not cover those aspects. .SS Prerequisites .sp \fIns\-3\fP has various optional extensions, but the main features just require a C++ compiler (g++ or clang++) and Python (version 3.6 or above); the Python is needed for the build system. We focus in this chapter only on getting \fIns\-3\fP up and running on a system supported by a recent C++ compiler and Python runtime support. .sp For Linux, use either g++ or clang++ compilers. For macOS, use clang++ (available in Xcode or Xcode Command Line Tools). For Windows, we recommend to either use a Linux virtual machine, or the Windows Subsystem for Linux. .SS Downloading ns\-3 .sp \fIns\-3\fP is distributed in source code only (some binary packages exist but they are not maintained by the open source project). There are two main ways to obtain the source code: 1) downloading the latest release as a source code archive from the main \fIns\-3\fP web site, or 2) cloning the Git repository from GitLab.com. These two options are described next; either one or the other download option (but not both) should be followed. .SS Downloading the Latest Release .INDENT 0.0 .IP 1. 3 Download the latest release from \fI\%https://www.nsnam.org/releases/latest\fP .IP 2. 3 Unpack it in a working directory of your choice. .INDENT 3.0 .INDENT 3.5 .sp .nf .ft C $ tar xjf ns\-allinone\-3.35.tar.bz2 .ft P .fi .UNINDENT .UNINDENT .IP 3. 3 Change into the \fIns\-3\fP directory directly; e.g. .INDENT 3.0 .INDENT 3.5 .sp .nf .ft C $ cd ns\-allinone\-3.35/ns\-3.35 .ft P .fi .UNINDENT .UNINDENT .UNINDENT .sp The ns\-allinone directory has some additional components but we are skipping over them here; one can work directly from the \fIns\-3\fP source code directory. .SS Cloning ns\-3 from GitLab.com .sp You can perform a Git clone in the usual way: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ git clone https://gitlab.com/nsnam/ns\-3\-dev.git .ft P .fi .UNINDENT .UNINDENT .sp If you are content to work with the tip of the development tree; you need only to \fIcd\fP into ns\-3\-dev; the \fImaster\fP branch is checked out by default. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ cd ns\-3\-dev .ft P .fi .UNINDENT .UNINDENT .sp If instead you want to try the most recent release (version 3.35 as of this writing), you can checkout a branch corresponding to that git tag: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ git checkout \-b ns\-3.35\-branch ns\-3.35 .ft P .fi .UNINDENT .UNINDENT .SS Building and testing ns\-3 .sp Once you have obtained the source either by downloading a release or by cloning a Git repository, the next step is to configure the build using the \fIWaf\fP build system that comes with \fIns\-3\fP\&. There are several options to control the build, but enabling the example programs and the tests, for a default debug build profile (with debugging symbols and support for \fIns\-3\fP logging) is what is usually done at first: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./waf configure \-\-enable\-examples \-\-enable\-tests .ft P .fi .UNINDENT .UNINDENT .sp Then, use Waf to build \fIns\-3\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./waf build .ft P .fi .UNINDENT .UNINDENT .sp Once complete, you can run the unit tests to check your build: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./test.py .ft P .fi .UNINDENT .UNINDENT .sp All tests should either PASS or be SKIPped. At this point, you have a working \fIns\-3\fP simulator. From here, you can start to run programs (look in the examples directory). To run the first tutorial program, whose source code is located at \fIexamples/tutorial/first.cc\fP, use Waf to run it (by doing so, the \fIns\-3\fP shared libraries are found automatically): .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./waf \-\-run first .ft P .fi .UNINDENT .UNINDENT .sp To view possible command\-line options, specify the \fI–PrintHelp\fP argument: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./waf \-\-run \(aqfirst \-\-PrintHelp\(aq .ft P .fi .UNINDENT .UNINDENT .sp To continue reading about the conceptual model and architecture of \fIns\-3\fP, the tutorial chapter \fI\%Conceptual Overview\fP would be the next natural place to skip to, or you can learn more about the project and the various build options by continuing directly with the \fI\%Introduction\fP and \fI\%Getting Started\fP chapters. .SH INTRODUCTION .sp The \fIns\-3\fP simulator is a discrete\-event network simulator targeted primarily for research and educational use. The \fI\%ns\-3 project\fP, started in 2006, is an open\-source project developing \fIns\-3\fP\&. .sp The purpose of this tutorial is to introduce new \fIns\-3\fP users to the system in a structured way. It is sometimes difficult for new users to glean essential information from detailed manuals and to convert this information into working simulations. In this tutorial, we will build several example simulations, introducing and explaining key concepts and features as we go. .sp As the tutorial unfolds, we will introduce the full \fIns\-3\fP documentation and provide pointers to source code for those interested in delving deeper into the workings of the system. .sp We also provide a quick start guide for those who are comfortable diving right in without too much documentation. .sp A few key points are worth noting at the onset: .INDENT 0.0 .IP \(bu 2 \fIns\-3\fP is open\-source, and the project strives to maintain an open environment for researchers to contribute and share their software. .IP \(bu 2 \fIns\-3\fP is not a backwards\-compatible extension of \fI\%ns\-2\fP; it is a new simulator. The two simulators are both written in C++ but \fIns\-3\fP is a new simulator that does not support the \fIns\-2\fP APIs. .UNINDENT .SS About ns\-3 .sp \fIns\-3\fP has been developed to provide an open, extensible network simulation platform, for networking research and education. In brief, \fIns\-3\fP provides models of how packet data networks work and perform, and provides a simulation engine for users to conduct simulation experiments. Some of the reasons to use \fIns\-3\fP include to perform studies that are more difficult or not possible to perform with real systems, to study system behavior in a highly controlled, reproducible environment, and to learn about how networks work. Users will note that the available model set in \fIns\-3\fP focuses on modeling how Internet protocols and networks work, but \fIns\-3\fP is not limited to Internet systems; several users are using \fIns\-3\fP to model non\-Internet\-based systems. .sp Many simulation tools exist for network simulation studies. Below are a few distinguishing features of \fIns\-3\fP in contrast to other tools. .INDENT 0.0 .IP \(bu 2 \fIns\-3\fP is designed as a set of libraries that can be combined together and also with other external software libraries. While some simulation platforms provide users with a single, integrated graphical user interface environment in which all tasks are carried out, \fIns\-3\fP is more modular in this regard. Several external animators and data analysis and visualization tools can be used with \fIns\-3\fP\&. However, users should expect to work at the command line and with C++ and/or Python software development tools. .IP \(bu 2 \fIns\-3\fP is primarily used on Linux or macOS systems, although support exists for BSD systems and also for Windows frameworks that can build Linux code, such as Windows Subsystem for Linux, or Cygwin. Native Windows Visual Studio is not presently supported although a developer is working on future support. Windows users may also use a Linux virtual machine. .IP \(bu 2 \fIns\-3\fP is not an officially supported software product of any company. Support for \fIns\-3\fP is done on a best\-effort basis on the ns\-3\-users forum (\fI\%ns\-3\-users@googlegroups.com\fP). .UNINDENT .SS For ns\-2 Users .sp For those familiar with \fIns\-2\fP (a popular tool that preceded \fIns\-3\fP), the most visible outward change when moving to \fIns\-3\fP is the choice of scripting language. Programs in \fIns\-2\fP are scripted in OTcl and results of simulations can be visualized using the Network Animator nam. It is not possible to run a simulation in \fIns\-2\fP purely from C++ (i.e., as a main() program without any OTcl). Moreover, some components of \fIns\-2\fP are written in C++ and others in OTcl. In \fIns\-3\fP, the simulator is written entirely in C++, with optional Python bindings. Simulation scripts can therefore be written in C++ or in Python. New animators and visualizers are available and under current development. Since \fIns\-3\fP generates pcap packet trace files, other utilities can be used to analyze traces as well. In this tutorial, we will first concentrate on scripting directly in C++ and interpreting results via trace files. .sp But there are similarities as well (both, for example, are based on C++ objects, and some code from \fIns\-2\fP has already been ported to \fIns\-3\fP). We will try to highlight differences between \fIns\-2\fP and \fIns\-3\fP as we proceed in this tutorial. .sp A question that we often hear is “Should I still use \fIns\-2\fP or move to \fIns\-3\fP?” In this author’s opinion, unless the user is somehow vested in \fIns\-2\fP (either based on existing personal comfort with and knowledge of \fIns\-2\fP, or based on a specific simulation model that is only available in \fIns\-2\fP), a user will be more productive with \fIns\-3\fP for the following reasons: .INDENT 0.0 .IP \(bu 2 \fIns\-3\fP is actively maintained with an active, responsive users mailing list, while \fIns\-2\fP is only lightly maintained and has not seen significant development in its main code tree for over a decade. .IP \(bu 2 \fIns\-3\fP provides features not available in \fIns\-2\fP, such as a implementation code execution environment (allowing users to run real implementation code in the simulator) .IP \(bu 2 \fIns\-3\fP provides a lower base level of abstraction compared with \fIns\-2\fP, allowing it to align better with how real systems are put together. Some limitations found in \fIns\-2\fP (such as supporting multiple types of interfaces on nodes correctly) have been remedied in \fIns\-3\fP\&. .UNINDENT .sp \fIns\-2\fP has a more diverse set of contributed modules than does \fIns\-3\fP, owing to its long history. However, \fIns\-3\fP has more detailed models in several popular areas of research (including sophisticated LTE and WiFi models), and its support of implementation code admits a very wide spectrum of high\-fidelity models. Users may be surprised to learn that the whole Linux networking stack can be encapsulated in an \fIns\-3\fP node, using the Direct Code Execution (DCE) framework. \fIns\-2\fP models can sometimes be ported to \fIns\-3\fP, particularly if they have been implemented in C++. .sp If in doubt, a good guideline would be to look at both simulators (as well as other simulators), and in particular the models available for your research, but keep in mind that your experience may be better in using the tool that is being actively developed and maintained (\fIns\-3\fP). .SS Contributing .sp \fIns\-3\fP is a research and educational simulator, by and for the research community. It will rely on the ongoing contributions of the community to develop new models, debug or maintain existing ones, and share results. There are a few policies that we hope will encourage people to contribute to \fIns\-3\fP like they have for \fIns\-2\fP: .INDENT 0.0 .IP \(bu 2 Open source licensing based on GNU GPLv2 compatibility .IP \(bu 2 \fI\%wiki\fP .IP \(bu 2 \fI\%Contributed Code\fP page, similar to \fIns\-2\fP’s popular Contributed Code \fI\%page\fP .IP \(bu 2 Use of GitLab.com including issue tracker <\fI\%https://www.gitlab.com/nsnam\fP>\(ga_ .UNINDENT .sp We realize that if you are reading this document, contributing back to the project is probably not your foremost concern at this point, but we want you to be aware that contributing is in the spirit of the project and that even the act of dropping us a note about your early experience with \fIns\-3\fP (e.g. “this tutorial section was not clear…”), reports of stale documentation or comments in the code, etc. are much appreciated. The preferred way to submit patches is either to fork our project on GitLab.com and generate a Merge Request, or to open an issue on our issue tracker and append a patch. .SS Tutorial Organization .sp The tutorial assumes that new users might initially follow a path such as the following: .INDENT 0.0 .IP \(bu 2 Try to download and build a copy; .IP \(bu 2 Try to run a few sample programs; .IP \(bu 2 Look at simulation output, and try to adjust it. .UNINDENT .sp As a result, we have tried to organize the tutorial along the above broad sequences of events. .SH RESOURCES .SS The Web .sp There are several important resources of which any \fIns\-3\fP user must be aware. The main web site is located at \fI\%https://www.nsnam.org\fP and provides access to basic information about the \fIns\-3\fP system. Detailed documentation is available through the main web site at \fI\%https://www.nsnam.org/documentation/\fP\&. You can also find documents relating to the system architecture from this page. .sp There is a Wiki that complements the main \fIns\-3\fP web site which you will find at \fI\%https://www.nsnam.org/wiki/\fP\&. You will find user and developer FAQs there, as well as troubleshooting guides, third\-party contributed code, papers, etc. .sp The source code may be found and browsed at GitLab.com: \fI\%https://gitlab.com/nsnam/\fP\&. There you will find the current development tree in the repository named \fBns\-3\-dev\fP\&. Past releases and experimental repositories of the core developers may also be found at the project’s old Mercurial site at \fI\%http://code.nsnam.org\fP\&. .SS Git .sp Complex software systems need some way to manage the organization and changes to the underlying code and documentation. There are many ways to perform this feat, and you may have heard of some of the systems that are currently used to do this. Until recently, the \fIns\-3\fP project used Mercurial as its source code management system, but in December 2018, switch to using Git. Although you do not need to know much about Git in order to complete this tutorial, we recommend becoming familiar with Git and using it to access the source code. GitLab.com provides resources to get started at: \fI\%https://docs.gitlab.com/ee/gitlab\-basics/\fP\&. .SS Waf .sp Once you have source code downloaded to your local system, you will need to compile that source to produce usable programs. Just as in the case of source code management, there are many tools available to perform this function. Probably the most well known of these tools is \fBmake\fP\&. Along with being the most well known, \fBmake\fP is probably the most difficult to use in a very large and highly configurable system. Because of this, many alternatives have been developed. Recently these systems have been developed using the Python language. .sp The build system Waf is used on the \fIns\-3\fP project. It is one of the new generation of Python\-based build systems. You will not need to understand any Python to build the existing \fIns\-3\fP system. .sp For those interested in the gory details of Waf, the Waf book is available at \fI\%https://waf.io/book/\fP and the current code at \fI\%https://gitlab.com/ita1024/waf/\fP\&. .SS Development Environment .sp As mentioned above, scripting in \fIns\-3\fP is done in C++ or Python. Most of the \fIns\-3\fP API is available in Python, but the models are written in C++ in either case. A working knowledge of C++ and object\-oriented concepts is assumed in this document. We will take some time to review some of the more advanced concepts or possibly unfamiliar language features, idioms and design patterns as they appear. We don’t want this tutorial to devolve into a C++ tutorial, though, so we do expect a basic command of the language. There are a wide number of sources of information on C++ available on the web or in print. .sp If you are new to C++, you may want to find a tutorial\- or cookbook\-based book or web site and work through at least the basic features of the language before proceeding. For instance, \fI\%this tutorial\fP\&. .sp On Linux, the \fIns\-3\fP system uses several components of the GNU “toolchain” for development. A software toolchain is the set of programming tools available in the given environment. For a quick review of what is included in the GNU toolchain see, \fI\%http://en.wikipedia.org/wiki/GNU_toolchain\fP\&. \fIns\-3\fP uses gcc, GNU binutils, and gdb. However, we do not use the GNU build system tools, neither make nor autotools. We use Waf for these functions. .sp On macOS, the toolchain used is Xcode. \fIns\-3\fP users on a Mac are strongly encouraged to install Xcode and the command\-line tools packages from the Apple App Store, and to look at the \fIns\-3\fP installation wiki for more information (\fI\%https://www.nsnam.org/wiki/Installation\fP). .sp Typically an \fIns\-3\fP author will work in Linux or a Unix\-like environment. For those running under Windows, there do exist environments which simulate the Linux environment to various degrees. The \fIns\-3\fP project has in the past (but not presently) supported development in the Cygwin environment for these users. See \fI\%http://www.cygwin.com/\fP for details on downloading, and visit the \fIns\-3\fP wiki for more information about Cygwin and \fIns\-3\fP\&. MinGW is presently not officially supported. Another alternative to Cygwin is to install a virtual machine environment such as VMware server and install a Linux virtual machine. .SS Socket Programming .sp We will assume a basic facility with the Berkeley Sockets API in the examples used in this tutorial. If you are new to sockets, we recommend reviewing the API and some common usage cases. For a good overview of programming TCP/IP sockets we recommend \fI\%TCP/IP Sockets in C, Donahoo and Calvert\fP\&. .sp There is an associated web site that includes source for the examples in the book, which you can find at: \fI\%http://cs.baylor.edu/~donahoo/practical/CSockets/\fP\&. .sp If you understand the first four chapters of the book (or for those who do not have access to a copy of the book, the echo clients and servers shown in the website above) you will be in good shape to understand the tutorial. There is a similar book on Multicast Sockets, \fI\%Multicast Sockets, Makofske and Almeroth\fP\&. that covers material you may need to understand if you look at the multicast examples in the distribution. .SH GETTING STARTED .sp This section is aimed at getting a user to a working state starting with a machine that may never have had \fIns\-3\fP installed. It covers supported platforms, prerequisites, ways to obtain \fIns\-3\fP, ways to build \fIns\-3\fP, and ways to verify your build and run simple programs. .SS Overview .sp \fIns\-3\fP is built as a system of software libraries that work together. User programs can be written that links with (or imports from) these libraries. User programs are written in either the C++ or Python programming languages. .sp \fIns\-3\fP is distributed as source code, meaning that the target system needs to have a software development environment to build the libraries first, then build the user program. \fIns\-3\fP could in principle be distributed as pre\-built libraries for selected systems, and in the future it may be distributed that way, but at present, many users actually do their work by editing \fIns\-3\fP itself, so having the source code around to rebuild the libraries is useful. If someone would like to undertake the job of making pre\-built libraries and packages for operating systems, please contact the ns\-developers mailing list. .sp In the following, we’ll look at three ways of downloading and building \fIns\-3\fP\&. The first is to download and build an official release from the main web site. The second is to fetch and build development copies of a basic \fIns\-3\fP installation. The third is to use an additional build tool to download more extensions for \fIns\-3\fP\&. We’ll walk through each since the tools involved are slightly different. .sp Experienced Linux users may wonder at this point why \fIns\-3\fP is not provided like most other libraries using a package management tool? Although there exist some binary packages for various Linux distributions (e.g. Debian), most users end up editing and having to rebuild the \fIns\-3\fP libraries themselves, so having the source code available is more convenient. We will therefore focus on a source installation in this tutorial. .sp For most uses of \fIns\-3\fP, root permissions are not needed, and the use of a non\-privileged user account is recommended. .SS Prerequisites .sp The entire set of available \fIns\-3\fP libraries has a number of dependencies on third\-party libraries, but most of \fIns\-3\fP can be built and used with support for a few common (often installed by default) components: a C++ compiler, an installation of Python, a source code editor (such as vim, emacs, or Eclipse) and, if using the development repositories, an installation of Git source code control system. Most beginning users need not concern themselves if their configuration reports some missing optional features of \fIns\-3\fP, but for those wishing a full installation, the project provides a wiki that includes pages with many useful hints and tips. One such page is the “Installation” page, with install instructions for various systems, available at \fI\%https://www.nsnam.org/wiki/Installation\fP\&. .sp The “Prerequisites” section of this wiki page explains which packages are required to support common \fIns\-3\fP options, and also provides the commands used to install them for common Linux or macOS variants. .sp You may want to take this opportunity to explore the \fIns\-3\fP wiki a bit, or the main web site at \fI\%https://www.nsnam.org\fP, since there is a wealth of information there. .sp As of the most recent \fIns\-3\fP release (ns\-3.35), the following tools are needed to get started with \fIns\-3\fP: .TS center; |l|l|. _ T{ Prerequisite T} T{ Package/version T} _ T{ C++ compiler T} T{ \fBclang++\fP or \fBg++\fP (g++ version 7 or greater) T} _ T{ Python T} T{ \fBpython3\fP version >=3.6 T} _ T{ Git T} T{ any recent version (to access \fIns\-3\fP from \fI\%GitLab.com\fP) T} _ T{ tar T} T{ any recent version (to unpack an \fI\%ns\-3 release\fP) T} _ T{ bunzip2 T} T{ any recent version (to uncompress an \fIns\-3\fP release) T} _ .TE .sp To check the default version of Python, type \fBpython \-V\fP\&. To check the default version of g++, type \fBg++ \-v\fP\&. If your installation is missing or too old, please consult the \fIns\-3\fP installation wiki for guidance. .sp From this point forward, we are going to assume that the reader is working in Linux, macOS, or a Linux emulation environment, and has at least the above prerequisites. .sp \fBNote:\fP The \fIns\-3\fP build system (\fIWaf\fP, introduced below) does not tolerate spaces in the installation path. Make sure that you are downloading into a directory that does not contain spaces in the full path name. .sp For example, do not use a directory path such as the below, because one of the parent directories contains a space in the directory name: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ pwd /home/user/5G simulations/ns\-3\-allinone/ns\-3\-dev .ft P .fi .UNINDENT .UNINDENT .SS Downloading a release of ns\-3 as a source archive .sp This option is for the new user who wishes to download and experiment with the most recently released and packaged version of \fIns\-3\fP\&. \fIns\-3\fP publishes its releases as compressed source archives, sometimes referred to as a tarball. A tarball is a particular format of software archive where multiple files are bundled together and the archive is usually compressed. The process for downloading \fIns\-3\fP via tarball is simple; you just have to pick a release, download it and uncompress it. .sp Let’s assume that you, as a user, wish to build \fIns\-3\fP in a local directory called \fBworkspace\fP\&. If you adopt the \fBworkspace\fP directory approach, you can get a copy of a release by typing the following into your Linux shell (substitute the appropriate version numbers, of course) .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ cd $ mkdir workspace $ cd workspace $ wget https://www.nsnam.org/release/ns\-allinone\-3.35.tar.bz2 $ tar xjf ns\-allinone\-3.35.tar.bz2 .ft P .fi .UNINDENT .UNINDENT .sp Notice the use above of the \fBwget\fP utility, which is a command\-line tool to fetch objects from the web; if you do not have this installed, you can use a browser for this step. .sp Following these steps, if you change into the directory \fBns\-allinone\-3.35\fP, you should see a number of files and directories .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ cd ns\-allinone\-3.35 $ ls bake constants.py ns\-3.35 README build.py netanim\-3.108 pybindgen\-0.22.0 util.py .ft P .fi .UNINDENT .UNINDENT .sp You are now ready to build the base \fIns\-3\fP distribution and may skip ahead to the section on building \fIns\-3\fP\&. .SS Downloading ns\-3 using Git .sp The \fIns\-3\fP code is available in Git repositories on the GitLab.com service at \fI\%https://gitlab.com/nsnam/\fP\&. The group name \fBnsnam\fP organizes the various repositories used by the open source project. .sp The simplest way to get started using Git repositories is to fork or clone the \fBns\-3\-allinone\fP environment. This is a set of scripts that manages the downloading and building of the most commonly used subsystems of \fIns\-3\fP for you. If you are new to Git, the terminology of \fBfork\fP and \fBclone\fP may be foreign to you; if so, we recommend that you simply \fBclone\fP (create your own replica) of the repository found on GitLab.com, as follows: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ cd $ mkdir workspace $ cd workspace $ git clone https://gitlab.com/nsnam/ns\-3\-allinone.git $ cd ns\-3\-allinone .ft P .fi .UNINDENT .UNINDENT .sp At this point, your view of the ns\-3\-allinone directory is slightly different than described above with a release archive; it should look something like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ls build.py constants.py download.py README util.py .ft P .fi .UNINDENT .UNINDENT .sp Note the presence of the \fBdownload.py\fP script, which will further fetch the \fIns\-3\fP and related sourcecode. At this point, you have a choice, to either download the most recent development snapshot of \fIns\-3\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ python3 download.py .ft P .fi .UNINDENT .UNINDENT .sp or to specify a release of \fIns\-3\fP, using the \fB\-n\fP flag to specify a release number: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ python3 download.py \-n ns\-3.35 .ft P .fi .UNINDENT .UNINDENT .sp After this step, the additional repositories of \fIns\-3\fP, bake, pybindgen, and netanim will be downloaded to the \fBns\-3\-allinone\fP directory. .SS Downloading ns\-3 Using Bake .sp The above two techniques (source archive, or ns\-3\-allinone repository via Git) are useful to get the most basic installation of \fIns\-3\fP with a few addons (pybindgen for generating Python bindings, and netanim for network animiations). The third repository provided by default in ns\-3\-allinone is called \fBbake\fP\&. .sp Bake is a tool for coordinated software building from multiple repositories, developed for the \fIns\-3\fP project. \ Bake can be used to fetch development versions of the \fIns\-3\fP software, and to download and build extensions to the base \fIns\-3\fP distribution, such as the Direct Code Execution environment, Network Simulation Cradle, ability to create new Python bindings, and various \fIns\-3\fP “apps”. If you envision that your \fIns\-3\fP installation may use advanced or optional features, you may wish to follow this installation path. .sp In recent \fIns\-3\fP releases, Bake has been included in the release tarball. The configuration file included in the released version will allow one to download any software that was current at the time of the release. That is, for example, the version of Bake that is distributed with the \fBns\-3.30\fP release can be used to fetch components for that \fIns\-3\fP release or earlier, but can’t be used to fetch components for later releases (unless the \fBbakeconf.xml\fP package description file is updated). .sp You can also get the most recent copy of \fBbake\fP by typing the following into your Linux shell (assuming you have installed Git): .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ cd $ mkdir workspace $ cd workspace $ git clone https://gitlab.com/nsnam/bake.git .ft P .fi .UNINDENT .UNINDENT .sp As the git command executes, you should see something like the following displayed: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Cloning into \(aqbake\(aq... remote: Enumerating objects: 2086, done. remote: Counting objects: 100% (2086/2086), done. remote: Compressing objects: 100% (649/649), done. remote: Total 2086 (delta 1404), reused 2078 (delta 1399) Receiving objects: 100% (2086/2086), 2.68 MiB | 3.82 MiB/s, done. Resolving deltas: 100% (1404/1404), done. .ft P .fi .UNINDENT .UNINDENT .sp After the clone command completes, you should have a directory called \fBbake\fP, the contents of which should look something like the following: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ cd bake $ ls bake bakeconf.xml bake.py doc examples generate\-binary.py test TODO .ft P .fi .UNINDENT .UNINDENT .sp Notice that you have downloaded some Python scripts, a Python module called \fBbake\fP, and an XML configuration file. The next step will be to use those scripts to download and build the \fIns\-3\fP distribution of your choice. .sp There are a few configuration targets available: .INDENT 0.0 .IP 1. 3 \fBns\-3.35\fP: the module corresponding to the release; it will download components similar to the release tarball. .IP 2. 3 \fBns\-3\-dev\fP: a similar module but using the development code tree .IP 3. 3 \fBns\-allinone\-3.35\fP: the module that includes other optional features such as bake build system, netanim animator, and pybindgen .IP 4. 3 \fBns\-3\-allinone\fP: similar to the released version of the allinone module, but for development code. .UNINDENT .sp The current development snapshot (unreleased) of \fIns\-3\fP may be found at \fI\%https://gitlab.com/nsnam/ns\-3\-dev.git\fP\&. The developers attempt to keep these repositories in consistent, working states but they are in a development area with unreleased code present, so you may want to consider staying with an official release if you do not need newly\- introduced features. .sp You can find the latest version of the code either by inspection of the repository list or by going to the \fI\%“ns\-3 Releases”\fP web page and clicking on the latest release link. We’ll proceed in this tutorial example with \fBns\-3.35\fP\&. .sp We are now going to use the bake tool to pull down the various pieces of \fIns\-3\fP you will be using. First, we’ll say a word about running bake. .sp Bake works by downloading source packages into a source directory, and installing libraries into a build directory. bake can be run by referencing the binary, but if one chooses to run bake from outside of the directory it was downloaded into, it is advisable to put bake into your path, such as follows (Linux bash shell example). First, change into the ‘bake’ directory, and then set the following environment variables: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ export BAKE_HOME=\(gapwd\(ga $ export PATH=$PATH:$BAKE_HOME:$BAKE_HOME/build/bin $ export PYTHONPATH=$PYTHONPATH:$BAKE_HOME:$BAKE_HOME/build/lib .ft P .fi .UNINDENT .UNINDENT .sp This will put the bake.py program into the shell’s path, and will allow other programs to find executables and libraries created by bake. Although several bake use cases do not require setting PATH and PYTHONPATH as above, full builds of ns\-3\-allinone (with the optional packages) typically do. .sp Step into the workspace directory and type the following into your shell: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./bake.py configure \-e ns\-3.35 .ft P .fi .UNINDENT .UNINDENT .sp Next, we’ll ask bake to check whether we have enough tools to download various components. Type: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./bake.py check .ft P .fi .UNINDENT .UNINDENT .sp You should see something like the following: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C > Python \- OK > GNU C++ compiler \- OK > Mercurial \- OK > Git \- OK > Tar tool \- OK > Unzip tool \- OK > Make \- OK > cMake \- OK > patch tool \- OK > Path searched for tools: /usr/local/sbin /usr/local/bin /usr/sbin /usr/bin /sbin /bin ... .ft P .fi .UNINDENT .UNINDENT .sp In particular, download tools such as Git and Mercurial are our principal concerns at this point, since they allow us to fetch the code. Please install missing tools at this stage, in the usual way for your system (if you are able to), or contact your system administrator as needed to install these tools. You can also .sp Next, try to download the software: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./bake.py download .ft P .fi .UNINDENT .UNINDENT .sp should yield something like: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >> Searching for system dependency setuptools \- OK >> Searching for system dependency libgoocanvas2 \- OK >> Searching for system dependency gi\-cairo \- OK >> Searching for system dependency pygobject \- OK >> Searching for system dependency pygraphviz \- OK >> Searching for system dependency python\-dev \- OK >> Searching for system dependency qt \- OK >> Searching for system dependency g++ \- OK >> Searching for system dependency cxxfilt \- OK >> Searching for system dependency setuptools \- OK >> Searching for system dependency gi\-cairo \- OK >> Searching for system dependency gir\-bindings \- OK >> Searching for system dependency pygobject \- OK >> Searching for system dependency cmake \- OK >> Downloading netanim\-3.108 \- OK >> Downloading pybindgen\-0.22.0 (target directory:pybindgen) \- OK >> Downloading ns\-3.35 (target directory:ns\-3.35) \- OK .ft P .fi .UNINDENT .UNINDENT .sp The above suggests that three sources have been downloaded. Check the \fBsource\fP directory now and type \fBls\fP; one should see: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ cd source $ ls netanim\-3.108 ns\-3.35 pybindgen .ft P .fi .UNINDENT .UNINDENT .sp You are now ready to build the \fIns\-3\fP distribution. .SS Building ns\-3 .sp As with downloading \fIns\-3\fP, there are a few ways to build \fIns\-3\fP\&. The main thing that we wish to emphasize is the following. \fIns\-3\fP is built with a build tool called \fBWaf\fP, described below. Most users will end up working most directly with Waf, but there are some convenience scripts to get you started or to orchestrate more complicated builds. Therefore, please have a look at \fBbuild.py\fP and building with \fBbake\fP, before reading about Waf below. .SS Building with \fBbuild.py\fP .sp \fBNote:\fP This build step is only available from a source archive release described above; not from downloading via git or bake. .sp When working from a released tarball, a convenience script available as part of \fBns\-3\-allinone\fP can orchestrate a simple build of components. This program is called \fBbuild.py\fP\&. This program will get the project configured for you in the most commonly useful way. However, please note that more advanced configuration and work with \fIns\-3\fP will typically involve using the native \fIns\-3\fP build system, Waf, to be introduced later in this tutorial. .sp If you downloaded using a tarball you should have a directory called something like \fBns\-allinone\-3.35\fP under your \fB~/workspace\fP directory. Type the following: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./build.py \-\-enable\-examples \-\-enable\-tests .ft P .fi .UNINDENT .UNINDENT .sp Because we are working with examples and tests in this tutorial, and because they are not built by default in \fIns\-3\fP, the arguments for build.py tells it to build them for us. The program also defaults to building all available modules. Later, you can build \fIns\-3\fP without examples and tests, or eliminate the modules that are not necessary for your work, if you wish. .sp You will see lots of compiler output messages displayed as the build script builds the various pieces you downloaded. First, the script will attempt to build the netanim animator, then the pybindgen bindings generator, and finally \fIns\-3\fP\&. Eventually you should see the following: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Waf: Leaving directory \(aq/path/to/workspace/ns\-allinone\-3.35/ns\-3.35/build\(aq \(aqbuild\(aq finished successfully (6m25.032s) Modules built: antenna aodv applications bridge buildings config\-store core csma csma\-layout dsdv dsr energy fd\-net\-device flow\-monitor internet internet\-apps lr\-wpan lte mesh mobility mpi netanim (no Python) network nix\-vector\-routing olsr point\-to\-point point\-to\-point\-layout propagation sixlowpan spectrum stats tap\-bridge test (no Python) topology\-read traffic\-control uan virtual\-net\-device visualizer wave wifi wimax Modules not built (see ns\-3 tutorial for explanation): brite click openflow Leaving directory ./ns\-3.35 .ft P .fi .UNINDENT .UNINDENT .sp Regarding the portion about modules not built: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Modules not built (see ns\-3 tutorial for explanation): brite click .ft P .fi .UNINDENT .UNINDENT .sp This just means that some \fIns\-3\fP modules that have dependencies on outside libraries may not have been built, or that the configuration specifically asked not to build them. It does not mean that the simulator did not build successfully or that it will provide wrong results for the modules listed as being built. .SS Building with bake .sp If you used bake above to fetch source code from project repositories, you may continue to use it to build \fIns\-3\fP\&. Type: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./bake.py build .ft P .fi .UNINDENT .UNINDENT .sp and you should see something like: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >> Building pybindgen\-0.22.0 \- OK >> Building netanim\-3.108 \- OK >> Building ns\-3.35 \- OK .ft P .fi .UNINDENT .UNINDENT .sp There may be failures to build all components, but the build will proceed anyway if the component is optional. For example, a recent portability issue has been that castxml may not build via the bake build tool on all platforms; in this case, the line will show something like: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >> Building castxml \- Problem > Problem: Optional dependency, module "castxml" failed This may reduce the functionality of the final build. However, bake will continue since "castxml" is not an essential dependency. For more information call bake with \-v or \-vvv, for full verbose mode. .ft P .fi .UNINDENT .UNINDENT .sp However, castxml is only needed if one wants to generate updated Python bindings, and most users do not need to do so (or to do so until they are more involved with ns\-3 changes), so such warnings might be safely ignored for now. .sp If there happens to be a failure, please have a look at what the following command tells you; it may give a hint as to a missing dependency: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./bake.py show .ft P .fi .UNINDENT .UNINDENT .sp This will list out the various dependencies of the packages you are trying to build. .SS Building with Waf .sp Up to this point, we have used either the \fIbuild.py\fP script, or the \fIbake\fP tool, to get started with building \fIns\-3\fP\&. These tools are useful for building \fIns\-3\fP and supporting libraries, and they call into the \fIns\-3\fP directory to call the Waf build tool to do the actual building. An installation of Waf is bundled with the \fIns\-3\fP source code. Most users quickly transition to using Waf directly to configure and build \fIns\-3\fP\&. So, to proceed, please change your working directory to the \fIns\-3\fP directory that you have initially built. .sp It’s not strictly required at this point, but it will be valuable to take a slight detour and look at how to make changes to the configuration of the project. Probably the most useful configuration change you can make will be to build the optimized version of the code. By default you have configured your project to build the debug version. Let’s tell the project to make an optimized build. To explain to Waf that it should do optimized builds that include the examples and tests, you will need to execute the following commands: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./waf clean $ ./waf configure \-\-build\-profile=optimized \-\-enable\-examples \-\-enable\-tests .ft P .fi .UNINDENT .UNINDENT .sp This runs Waf out of the local directory (which is provided as a convenience for you). The first command to clean out the previous build is not typically strictly necessary but is good practice (but see \fI\%Build Profiles\fP, below); it will remove the previously built libraries and object files found in directory \fBbuild/\fP\&. When the project is reconfigured and the build system checks for various dependencies, you should see output that looks similar to the following: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Setting top to : /home/ns3user/workspace/bake/source/ns\-3\-dev Setting out to : /home/ns3user/workspace/bake/source/ns\-3\-dev/build Checking for \(aqgcc\(aq (C compiler) : /usr/bin/gcc Checking for cc version : 7.3.0 Checking for \(aqg++\(aq (C++ compiler) : /usr/bin/g++ Checking for compilation flag \-march=native support : ok Checking for compilation flag \-Wl,\-\-soname=foo support : ok Checking for compilation flag \-std=c++11 support : ok Checking boost includes : headers not found, please provide a \-\-boost\-includes argument (see help) Checking boost includes : headers not found, please provide a \-\-boost\-includes argument (see help) Checking for program \(aqpython\(aq : /usr/bin/python Checking for python version >= 2.3 : 2.7.15 python\-config : /usr/bin/python\-config Asking python\-config for pyembed \(aq\-\-cflags \-\-libs \-\-ldflags\(aq flags : yes Testing pyembed configuration : yes Asking python\-config for pyext \(aq\-\-cflags \-\-libs \-\-ldflags\(aq flags : yes Testing pyext configuration : yes Checking for compilation flag \-fvisibility=hidden support : ok Checking for compilation flag \-Wno\-array\-bounds support : ok Checking for pybindgen location : ../pybindgen (guessed) Checking for python module \(aqpybindgen\(aq : 0.21.0 Checking for pybindgen version : 0.21.0 Checking for code snippet : yes Checking for types uint64_t and unsigned long equivalence : no Checking for code snippet : no Checking for types uint64_t and unsigned long long equivalence : yes Checking for the apidefs that can be used for Python bindings : gcc\-LP64 Checking for internal GCC cxxabi : complete Checking for python module \(aqpygccxml\(aq : not found Checking for click location : not found Checking for program \(aqpkg\-config\(aq : /usr/bin/pkg\-config Checking for \(aqgtk+\-3.0\(aq : not found Checking for \(aqlibxml\-2.0\(aq : yes checking for uint128_t : not found checking for __uint128_t : yes Checking high precision implementation : 128\-bit integer (default) Checking for header stdint.h : yes Checking for header inttypes.h : yes Checking for header sys/inttypes.h : not found Checking for header sys/types.h : yes Checking for header sys/stat.h : yes Checking for header dirent.h : yes Checking for header stdlib.h : yes Checking for header signal.h : yes Checking for header pthread.h : yes Checking for header stdint.h : yes Checking for header inttypes.h : yes Checking for header sys/inttypes.h : not found Checking for library rt : yes Checking for header sys/ioctl.h : yes Checking for header net/if.h : yes Checking for header net/ethernet.h : yes Checking for header linux/if_tun.h : yes Checking for header netpacket/packet.h : yes Checking for NSC location : not found Checking for \(aqsqlite3\(aq : not found Checking for header linux/if_tun.h : yes Checking for python module \(aqgi\(aq : 3.26.1 Checking for python module \(aqgi.repository.GObject\(aq : ok Checking for python module \(aqcairo\(aq : ok Checking for python module \(aqpygraphviz\(aq : 1.4rc1 Checking for python module \(aqgi.repository.Gtk\(aq : ok Checking for python module \(aqgi.repository.Gdk\(aq : ok Checking for python module \(aqgi.repository.Pango\(aq : ok Checking for python module \(aqgi.repository.GooCanvas\(aq : ok Checking for program \(aqsudo\(aq : /usr/bin/sudo Checking for program \(aqvalgrind\(aq : not found Checking for \(aqgsl\(aq : not found python\-config : not found Checking for compilation flag \-fstrict\-aliasing support : ok Checking for compilation flag \-fstrict\-aliasing support : ok Checking for compilation flag \-Wstrict\-aliasing support : ok Checking for compilation flag \-Wstrict\-aliasing support : ok Checking for program \(aqdoxygen\(aq : /usr/bin/doxygen \-\-\-\- Summary of optional NS\-3 features: Build profile : optimized Build directory : BRITE Integration : not enabled (BRITE not enabled (see option \-\-with\-brite)) DES Metrics event collection : not enabled (defaults to disabled) Emulation FdNetDevice : enabled Examples : enabled File descriptor NetDevice : enabled GNU Scientific Library (GSL) : not enabled (GSL not found) Gcrypt library : not enabled (libgcrypt not found: you can use libgcrypt\-config to find its location.) GtkConfigStore : not enabled (library \(aqgtk+\-3.0 >= 3.0\(aq not found) MPI Support : not enabled (option \-\-enable\-mpi not selected) NS\-3 Click Integration : not enabled (nsclick not enabled (see option \-\-with\-nsclick)) NS\-3 OpenFlow Integration : not enabled (Required boost libraries not found) Network Simulation Cradle : not enabled (NSC not found (see option \-\-with\-nsc)) PlanetLab FdNetDevice : not enabled (PlanetLab operating system not detected (see option \-\-force\-planetlab)) PyViz visualizer : enabled Python API Scanning Support : not enabled (Missing \(aqpygccxml\(aq Python module) Python Bindings : enabled Real Time Simulator : enabled SQlite stats data output : not enabled (library \(aqsqlite3\(aq not found) Tap Bridge : enabled Tap FdNetDevice : enabled Tests : enabled Threading Primitives : enabled Use sudo to set suid bit : not enabled (option \-\-enable\-sudo not selected) XmlIo : enabled \(aqconfigure\(aq finished successfully (6.387s) .ft P .fi .UNINDENT .UNINDENT .sp Note the last part of the above output. Some \fIns\-3\fP options are not enabled by default or require support from the underlying system to work properly. For instance, to enable XmlTo, the library libxml\-2.0 must be found on the system. If this library were not found, the corresponding \fIns\-3\fP feature would not be enabled and a message would be displayed. Note further that there is a feature to use the program \fBsudo\fP to set the suid bit of certain programs. This is not enabled by default and so this feature is reported as “not enabled.” Finally, to reprint this summary of which optional features are enabled, use the \fB\-\-check\-config\fP option to waf. .sp Now go ahead and switch back to the debug build that includes the examples and tests. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./waf clean $ ./waf configure \-\-build\-profile=debug \-\-enable\-examples \-\-enable\-tests .ft P .fi .UNINDENT .UNINDENT .sp The build system is now configured and you can build the debug versions of the \fIns\-3\fP programs by simply typing: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./waf .ft P .fi .UNINDENT .UNINDENT .sp Although the above steps made you build the \fIns\-3\fP part of the system twice, now you know how to change the configuration and build optimized code. .sp A command exists for checking which profile is currently active for an already configured project: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./waf \-\-check\-profile Waf: Entering directory \e\(ga/path/to/ns\-allinone\-3.35/ns\-3.35/build\e\(aq Build profile: debug .ft P .fi .UNINDENT .UNINDENT .sp The build.py script discussed above supports also the \fB\-\-enable\-examples\fP and \fBenable\-tests\fP arguments, but in general, does not directly support other waf options; for example, this will not work: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./build.py \-\-disable\-python .ft P .fi .UNINDENT .UNINDENT .sp will result in: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C build.py: error: no such option: \-\-disable\-python .ft P .fi .UNINDENT .UNINDENT .sp However, the special operator \fB\-\-\fP can be used to pass additional options through to waf, so instead of the above, the following will work: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./build.py \-\- \-\-disable\-python .ft P .fi .UNINDENT .UNINDENT .sp as it generates the underlying command \fB\&./waf configure \-\-disable\-python\fP\&. .sp Here are a few more introductory tips about Waf. .SS Handling build errors .sp \fIns\-3\fP releases are tested against the most recent C++ compilers available in the mainstream Linux and macOS distributions at the time of the release. However, over time, newer distributions are released, with newer compilers, and these newer compilers tend to be more pedantic about warnings. \fIns\-3\fP configures its build to treat all warnings as errors, so it is sometimes the case, if you are using an older release version on a newer system, that a compiler warning will cause the build to fail. .sp For instance, ns\-3.28 was released prior to Fedora 28, which included a new major version of gcc (gcc\-8). Building ns\-3.28 or older releases on Fedora 28, when Gtk2+ is installed, will result in an error such as: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C /usr/include/gtk\-2.0/gtk/gtkfilechooserbutton.h:59:8: error: unnecessary parentheses in declaration of ‘__gtk_reserved1’ [\-Werror=parentheses] void (*__gtk_reserved1); .ft P .fi .UNINDENT .UNINDENT .sp In releases starting with ns\-3.28.1, an option is available in Waf to work around these issues. The option disables the inclusion of the ‘\-Werror’ flag to g++ and clang++. The option is ‘–disable\-werror’ and must be used at configure time; e.g.: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C \&./waf configure \-\-disable\-werror \-\-enable\-examples \-\-enable\-tests .ft P .fi .UNINDENT .UNINDENT .SS Configure vs. Build .sp Some Waf commands are only meaningful during the configure phase and some commands are valid in the build phase. For example, if you wanted to use the emulation features of \fIns\-3\fP, you might want to enable setting the suid bit using sudo as described above. This turns out to be a configuration\-time command, and so you could reconfigure using the following command that also includes the examples and tests. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./waf configure \-\-enable\-sudo \-\-enable\-examples \-\-enable\-tests .ft P .fi .UNINDENT .UNINDENT .sp If you do this, Waf will have run sudo to change the socket creator programs of the emulation code to run as root. .sp There are many other configure\- and build\-time options available in Waf. To explore these options, type: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./waf \-\-help .ft P .fi .UNINDENT .UNINDENT .sp We’ll use some of the testing\-related commands in the next section. .SS Build Profiles .sp We already saw how you can configure Waf for \fBdebug\fP or \fBoptimized\fP builds: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./waf \-\-build\-profile=debug .ft P .fi .UNINDENT .UNINDENT .sp There is also an intermediate build profile, \fBrelease\fP\&. \fB\-d\fP is a synonym for \fB\-\-build\-profile\fP\&. .sp The build profile controls the use of logging, assertions, and compiler optimization: .SS Build profiles .TS center; |l|l|l|l|. _ T{ Feature T} T{ Build Profile T} _ T{ \fBdebug\fP T} T{ \fBrelease\fP T} T{ \fBoptimized\fP T} _ T{ Enabled Features T} T{ .nf \fBNS3_BUILD_PROFILE_DEBUG\fP \fBNS_LOG...\fP \fBNS_ASSERT...\fP .fi T} T{ \fBNS3_BUILD_PROFILE_RELEASE\fP T} T{ \fBNS3_BUILD_PROFILE_OPTIMIZED\fP T} _ T{ Code Wrapper Macro T} T{ \fBNS_BUILD_DEBUG(code)\fP T} T{ \fBNS_BUILD_RELEASE(code)\fP T} T{ \fBNS_BUILD_OPTIMIZED(code)\fP T} _ T{ Compiler Flags T} T{ \fB\-O0 \-ggdb \-g3\fP T} T{ \fB\-O3 \-g0\fP \fB\-fomit\-frame\-pointer\fP T} T{ \fB\-O3 \-g\fP \fB\-fstrict\-overflow\fP \fB\-march=native\fP T} _ .TE .sp As you can see, logging and assertions are only configured by default in debug builds, although they can be selectively enabled in other build profiles by using the \fB\-\-enable\-logs\fP and \fB\-\-enable\-asserts\fP flags during Waf configuration time. Recommended practice is to develop your scenario in debug mode, then conduct repetitive runs (for statistics or changing parameters) in optimized build profile. .sp If you have code that should only run in specific build profiles, use the indicated Code Wrapper macro: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C NS_BUILD_DEBUG (std::cout << "Part of an output line..." << std::flush; timer.Start ()); DoLongInvolvedComputation (); NS_BUILD_DEBUG (timer.Stop (); std::cout << "Done: " << timer << std::endl;) .ft P .fi .UNINDENT .UNINDENT .sp By default Waf puts the build artifacts in the \fBbuild\fP directory. You can specify a different output directory with the \fB\-\-out\fP option, e.g. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./waf configure \-\-out=my\-build\-dir .ft P .fi .UNINDENT .UNINDENT .sp Combining this with build profiles lets you switch between the different compile options in a clean way: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./waf configure \-\-build\-profile=debug \-\-out=build/debug $ ./waf build \&... $ ./waf configure \-\-build\-profile=optimized \-\-out=build/optimized $ ./waf build \&... .ft P .fi .UNINDENT .UNINDENT .sp This allows you to work with multiple builds rather than always overwriting the last build. When you switch, Waf will only compile what it has to, instead of recompiling everything. .sp When you do switch build profiles like this, you have to be careful to give the same configuration parameters each time. It may be convenient to define some environment variables to help you avoid mistakes: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ export NS3CONFIG="\-\-enable\-examples \-\-enable\-tests" $ export NS3DEBUG="\-\-build\-profile=debug \-\-out=build/debug" $ export NS3OPT=="\-\-build\-profile=optimized \-\-out=build/optimized" $ ./waf configure $NS3CONFIG $NS3DEBUG $ ./waf build \&... $ ./waf configure $NS3CONFIG $NS3OPT $ ./waf build .ft P .fi .UNINDENT .UNINDENT .SS Compilers and Flags .sp In the examples above, Waf uses the GCC C++ compiler, \fBg++\fP, for building \fIns\-3\fP\&. However, it’s possible to change the C++ compiler used by Waf by defining the \fBCXX\fP environment variable. For example, to use the Clang C++ compiler, \fBclang++\fP, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ CXX="clang++" ./waf configure $ ./waf build .ft P .fi .UNINDENT .UNINDENT .sp One can also set up Waf to do distributed compilation with \fBdistcc\fP in a similar way: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ CXX="distcc g++" ./waf configure $ ./waf build .ft P .fi .UNINDENT .UNINDENT .sp More info on \fBdistcc\fP and distributed compilation can be found on it’s \fI\%project page\fP under Documentation section. .sp To add compiler flags, use the \fBCXXFLAGS_EXTRA\fP environment variable when you configure \fIns\-3\fP\&. .SS Install .sp Waf may be used to install libraries in various places on the system. The default location where libraries and executables are built is in the \fBbuild\fP directory, and because Waf knows the location of these libraries and executables, it is not necessary to install the libraries elsewhere. .sp If users choose to install things outside of the build directory, users may issue the \fB\&./waf install\fP command. By default, the prefix for installation is \fB/usr/local\fP, so \fB\&./waf install\fP will install programs into \fB/usr/local/bin\fP, libraries into \fB/usr/local/lib\fP, and headers into \fB/usr/local/include\fP\&. Superuser privileges are typically needed to install to the default prefix, so the typical command would be \fBsudo ./waf install\fP\&. When running programs with Waf, Waf will first prefer to use shared libraries in the build directory, then will look for libraries in the library path configured in the local environment. So when installing libraries to the system, it is good practice to check that the intended libraries are being used. .sp Users may choose to install to a different prefix by passing the \fB\-\-prefix\fP option at configure time, such as: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C \&./waf configure \-\-prefix=/opt/local .ft P .fi .UNINDENT .UNINDENT .sp If later after the build the user issues the \fB\&./waf install\fP command, the prefix \fB/opt/local\fP will be used. .sp The \fB\&./waf clean\fP command should be used prior to reconfiguring the project if Waf will be used to install things at a different prefix. .sp In summary, it is not necessary to call \fB\&./waf install\fP to use \fIns\-3\fP\&. Most users will not need this command since Waf will pick up the current libraries from the \fBbuild\fP directory, but some users may find it useful if their use case involves working with programs outside of the \fIns\-3\fP directory. .SS One Waf .sp There is only one Waf script, at the top level of the \fIns\-3\fP source tree. As you work, you may find yourself spending a lot of time in \fBscratch/\fP, or deep in \fBsrc/...\fP, and needing to invoke Waf. You could just remember where you are, and invoke Waf like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ../../../waf ... .ft P .fi .UNINDENT .UNINDENT .sp but that gets tedious, and error prone, and there are better solutions. .sp One common way when using a text\-based editor such as emacs or vim is to open two terminal sessions and use one to build \fIns\-3\fP and one to edit source code. .sp If you only have the tarball, an environment variable can help: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ export NS3DIR="$PWD" $ function waff { cd $NS3DIR && ./waf $* ; } $ cd scratch $ waff build .ft P .fi .UNINDENT .UNINDENT .sp It might be tempting in a module directory to add a trivial \fBwaf\fP script along the lines of \fBexec ../../waf\fP\&. Please don’t. It’s confusing to newcomers, and when done poorly it leads to subtle build errors. The solutions above are the way to go. .SS Testing ns\-3 .sp You can run the unit tests of the \fIns\-3\fP distribution by running the \fB\&./test.py\fP script: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./test.py .ft P .fi .UNINDENT .UNINDENT .sp These tests are run in parallel by Waf. You should eventually see a report saying that .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C 92 of 92 tests passed (92 passed, 0 failed, 0 crashed, 0 valgrind errors) .ft P .fi .UNINDENT .UNINDENT .sp This is the important message to check for; failures, crashes, or valgrind errors indicate problems with the code or incompatibilities between the tools and the code. .sp You will also see the summary output from Waf and the test runner executing each test, which will actually look something like: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Waf: Entering directory \(ga/path/to/workspace/ns\-3\-allinone/ns\-3\-dev/build\(aq Waf: Leaving directory \(ga/path/to/workspace/ns\-3\-allinone/ns\-3\-dev/build\(aq \(aqbuild\(aq finished successfully (1.799s) Modules built: aodv applications bridge click config\-store core csma csma\-layout dsdv emu energy flow\-monitor internet lte mesh mobility mpi netanim network nix\-vector\-routing ns3tcp ns3wifi olsr openflow point\-to\-point point\-to\-point\-layout propagation spectrum stats tap\-bridge template test tools topology\-read uan virtual\-net\-device visualizer wifi wimax PASS: TestSuite wifi\-interference PASS: TestSuite histogram \&... PASS: TestSuite object PASS: TestSuite random\-number\-generators 92 of 92 tests passed (92 passed, 0 failed, 0 crashed, 0 valgrind errors) .ft P .fi .UNINDENT .UNINDENT .sp This command is typically run by users to quickly verify that an \fIns\-3\fP distribution has built correctly. (Note the order of the \fBPASS: ...\fP lines can vary, which is okay. What’s important is that the summary line at the end report that all tests passed; none failed or crashed.) .sp Both Waf and \fBtest.py\fP will split up the job on the available CPU cores of the machine, in parallel. .SS Running a Script .sp We typically run scripts under the control of Waf. This allows the build system to ensure that the shared library paths are set correctly and that the libraries are available at run time. To run a program, simply use the \fB\-\-run\fP option in Waf. Let’s run the \fIns\-3\fP equivalent of the ubiquitous hello world program by typing the following: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./waf \-\-run hello\-simulator .ft P .fi .UNINDENT .UNINDENT .sp Waf first checks to make sure that the program is built correctly and executes a build if required. Waf then executes the program, which produces the following output. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Hello Simulator .ft P .fi .UNINDENT .UNINDENT .sp Congratulations! You are now an ns\-3 user! .sp \fBWhat do I do if I don’t see the output?\fP .sp If you see Waf messages indicating that the build was completed successfully, but do not see the “Hello Simulator” output, chances are that you have switched your build mode to \fBoptimized\fP in the \fI\%Building with Waf\fP section, but have missed the change back to \fBdebug\fP mode. All of the console output used in this tutorial uses a special \fIns\-3\fP logging component that is useful for printing user messages to the console. Output from this component is automatically disabled when you compile optimized code – it is “optimized out.” If you don’t see the “Hello Simulator” output, type the following: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./waf configure \-\-build\-profile=debug \-\-enable\-examples \-\-enable\-tests .ft P .fi .UNINDENT .UNINDENT .sp to tell Waf to build the debug versions of the \fIns\-3\fP programs that includes the examples and tests. You must still build the actual debug version of the code by typing .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./waf .ft P .fi .UNINDENT .UNINDENT .sp Now, if you run the \fBhello\-simulator\fP program, you should see the expected output. .SS Program Arguments .sp To feed command line arguments to an \fIns\-3\fP program use this pattern: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./waf \-\-run \-\-command\-template="%s " .ft P .fi .UNINDENT .UNINDENT .sp Substitute your program name for \fB\fP, and the arguments for \fB\fP\&. The \fB\-\-command\-template\fP argument to Waf is basically a recipe for constructing the actual command line Waf should use to execute the program. Waf checks that the build is complete, sets the shared library paths, then invokes the executable using the provided command line template, inserting the program name for the \fB%s\fP placeholder. .sp If you find the above to be syntactically complicated, a simpler variant exists, which is to include the \fIns\-3\fP program and its arguments enclosed by single quotes, such as: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./waf \-\-run \(aq \-\-arg1=value1 \-\-arg2=value2 ...\(aq .ft P .fi .UNINDENT .UNINDENT .sp Another particularly useful example is to run a test suite by itself. Let’s assume that a \fBmytest\fP test suite exists (it doesn’t). Above, we used the \fB\&./test.py\fP script to run a whole slew of tests in parallel, by repeatedly invoking the real testing program, \fBtest\-runner\fP\&. To invoke \fBtest\-runner\fP directly for a single test: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./waf \-\-run test\-runner \-\-command\-template="%s \-\-suite=mytest \-\-verbose" .ft P .fi .UNINDENT .UNINDENT .sp This passes the arguments to the \fBtest\-runner\fP program. Since \fBmytest\fP does not exist, an error message will be generated. To print the available \fBtest\-runner\fP options: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./waf \-\-run test\-runner \-\-command\-template="%s \-\-help" .ft P .fi .UNINDENT .UNINDENT .SS Debugging .sp To run \fIns\-3\fP programs under the control of another utility, such as a debugger (\fIe.g.\fP \fBgdb\fP) or memory checker (\fIe.g.\fP \fBvalgrind\fP), you use a similar \fB\-\-command\-template="..."\fP form. .sp For example, to run your \fIns\-3\fP program \fBhello\-simulator\fP with the arguments \fB\fP under the \fBgdb\fP debugger: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./waf \-\-run=hello\-simulator \-\-command\-template="gdb %s \-\-args " .ft P .fi .UNINDENT .UNINDENT .sp Notice that the \fIns\-3\fP program name goes with the \fB\-\-run\fP argument, and the control utility (here \fBgdb\fP) is the first token in the \fB\-\-command\-template\fP argument. The \fB\-\-args\fP tells \fBgdb\fP that the remainder of the command line belongs to the “inferior” program. (Some \fBgdb\fP’s don’t understand the \fB\-\-args\fP feature. In this case, omit the program arguments from the \fB\-\-command\-template\fP, and use the \fBgdb\fP command \fBset args\fP\&.) .sp We can combine this recipe and the previous one to run a test under the debugger: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./waf \-\-run test\-runner \-\-command\-template="gdb %s \-\-args \-\-suite=mytest \-\-verbose" .ft P .fi .UNINDENT .UNINDENT .SS Working Directory .sp Waf needs to run from its location at the top of the \fIns\-3\fP tree. This becomes the working directory where output files will be written. But what if you want to keep those files out of the \fIns\-3\fP source tree? Use the \fB\-\-cwd\fP argument: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./waf \-\-cwd=... .ft P .fi .UNINDENT .UNINDENT .sp It may be more convenient to start with your working directory where you want the output files, in which case a little indirection can help: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ function waff { CWD="$PWD" cd $NS3DIR >/dev/null ./waf \-\-cwd="$CWD" $* cd \- >/dev/null } .ft P .fi .UNINDENT .UNINDENT .sp This embellishment of the previous version saves the current working directory, \fBcd\fP’s to the Waf directory, then instructs Waf to change the working directory \fIback\fP to the saved current working directory before running the program. .sp We mention this \fB\-\-cwd\fP command for completeness; most users will simply run Waf from the top\-level directory and generate the output data files there. .SS Running without Building .sp As of the ns\-3.30 release, a new Waf option was introduced to allow the running of programs while skipping the build step. This can reduce the time to run programs when, for example, running the same program repeatedly through a shell script, or when demonstrating program execution. This option, \fB\-\-run\-no\-build\fP, behaves the same as the \fB\-run\fP option, except that the program and ns\-3 libraries will not be rebuilt. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./waf \-\-run\-no\-build \(aq \-\-arg1=value1 \-\-arg2=value2 ...\(aq .ft P .fi .UNINDENT .UNINDENT .SS Build version .sp As of the ns\-3.32 release, a new Waf configure option \fB\-\-enable\-build\-version\fP was introduced which inspects the local ns3 git repository during builds and adds version metadata to the core module. .sp This configuration option has the following prerequisites: .INDENT 0.0 .IP \(bu 2 The ns\-3 directory must be part of a local git repository .IP \(bu 2 The local git repository must have at least one ns\-3 release tag .UNINDENT .sp or .INDENT 0.0 .IP \(bu 2 A file named version.cache, containing version information, is located in the src/core directory .UNINDENT .sp If these prerequisites are not met, the configuration will fail. .sp When these prerequisites are met and ns\-3 is configured with the \fB\-\-enable\-build\-version\fP option, the waf command \fB\-\-check\-version\fP can be used to query the local git repository and display the current version metadata. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./waf \-\-check\-version .ft P .fi .UNINDENT .UNINDENT .sp Waf will collect information about the build and print out something similar to the output below. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C ns\-3.33+249@g80e0dd0\-dirty\-debug .ft P .fi .UNINDENT .UNINDENT .sp If \fB\-\-check\-version\fP is run when \fB\-enable\-build\-version\fP was not configured, an error message indicating that the option is disabled will be displayed instead. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Build version support is not enabled, reconfigure with \-\-enable\-build\-version flag .ft P .fi .UNINDENT .UNINDENT .sp The build information is generated by examining the current state of the git repository. The output of \fB\-\-check\-version\fP will change whenever the state of the active branch changes. .sp The output of \fB\-\-check\-version\fP has the following format: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C [+closest_tag][+distance_from_tag]@[\-tree_state]\- .ft P .fi .UNINDENT .UNINDENT .INDENT 0.0 .TP .B version_tag version_tag contains the version of the ns\-3 code. The version tag is defined as a git tag with the format ns\-3*. If multiple git tags match the format, the tag on the active branch which is closest to the current commit is chosen. .TP .B closest_tag closest_tag is similar to version_tag except it is the first tag found, regardless of format. The closest tag is not included in the output when closest_tag and version_tag have the same value. .TP .B distance_from_tag distance_from_tag contains the number of commits between the current commit and closest_tag. distance_from_tag is not included in the output when the value is 0 (i.e. when closest_tag points to the current commit) .TP .B commit_hash commit_hash is the hash of the commit at the tip of the active branch. The value is ‘g’ followed by the first 7 characters of the commit hash. The ‘g’ prefix is used to indicate that this is a git hash. .TP .B tree_state tree_state indicates the state of the working tree. When the working tree has uncommitted changes this field has the value ‘dirty’. The tree state is not included in the version output when the working tree is clean (e.g. when there are no uncommitted changes). .TP .B profile The build profile specified in the \fB\-\-build\-profile\fP option passed to \fBwaf configure\fP .UNINDENT .sp A new class, named Version, has been added to the core module. The Version class contains functions to retrieve individual fields of the build version as well as functions to print the full build version like \fB\-\-check\-version\fP\&. The \fBbuild\-version\-example\fP application provides an example of how to use the Version class to retrieve the various build version fields. See the documentation for the Version class for specifics on the output of the Version class functions. .sp The version information stored in the Version class is updated every time the git repository changes. This may lead to frequent recompilations/linking of the core module when the \fB\-\-enable\-build\-version\fP option is configured. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C build\-version\-example: Program Version (according to CommandLine): ns\-3.33+249@g80e0dd0\-dirty\-debug Version fields: LongVersion: ns\-3.33+249@g80e0dd0\-dirty\-debug ShortVersion: ns\-3.33+* BuildSummary: ns\-3.33+* VersionTag: ns\-3.33 Major: 3 Minor: 33 Patch: 0 ReleaseCandidate: ClosestAncestorTag: ns\-3.33 TagDistance: 249 CommitHash: g80e0dd0 BuildProfile: debug WorkingTree: dirty .ft P .fi .UNINDENT .UNINDENT .sp The CommandLine class has also been updated to support the \fB\-\-version\fP option which will print the full build version and exit. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C \&./waf \-\-run\-no\-build "command\-line\-example \-\-version" Waf: Entering directory \(ga/g/g14/mdb/gitlab/mdb/ns\-3\-dev/build/debug\(aq ns\-3.33+249@g80e0dd0\-dirty\-debug .ft P .fi .UNINDENT .UNINDENT .sp If the \fB\-\-enable\-build\-version\fP option was not configured, \fB\-\-version\fP will print out a message similar to \fB\-\-check\-version\fP indicating that the build version option is not enabled. .SS Source version .sp An alternative to storing build version information in the \fIns\-3\fP libraries is to track the source code version used to build the code. When using Git, the following recipe can be added to Bash shell scripts to create a \fBversion.txt\fP file with Git revision information, appended with a patch of any changes to that revision if the repository is dirty. The resulting text file can then be saved with any corresponding \fIns\-3\fP simulation results. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C echo \(gagit describe\(ga > version.txt gitDiff=\(gagit diff\(ga if [[ $gitDiff ]] then echo "$gitDiff" >> version.txt fi .ft P .fi .UNINDENT .UNINDENT .SH CONCEPTUAL OVERVIEW .sp The first thing we need to do before actually starting to look at or write \fIns\-3\fP code is to explain a few core concepts and abstractions in the system. Much of this may appear transparently obvious to some, but we recommend taking the time to read through this section just to ensure you are starting on a firm foundation. .SS Key Abstractions .sp In this section, we’ll review some terms that are commonly used in networking, but have a specific meaning in \fIns\-3\fP\&. .SS Node .sp In Internet jargon, a computing device that connects to a network is called a \fIhost\fP or sometimes an \fIend system\fP\&. Because \fIns\-3\fP is a \fInetwork\fP simulator, not specifically an \fIInternet\fP simulator, we intentionally do not use the term host since it is closely associated with the Internet and its protocols. Instead, we use a more generic term also used by other simulators that originates in Graph Theory — the \fInode\fP\&. .sp In \fIns\-3\fP the basic computing device abstraction is called the node. This abstraction is represented in C++ by the class \fBNode\fP\&. The \fBNode\fP class provides methods for managing the representations of computing devices in simulations. .sp You should think of a \fBNode\fP as a computer to which you will add functionality. One adds things like applications, protocol stacks and peripheral cards with their associated drivers to enable the computer to do useful work. We use the same basic model in \fIns\-3\fP\&. .SS Application .sp Typically, computer software is divided into two broad classes. \fISystem Software\fP organizes various computer resources such as memory, processor cycles, disk, network, etc., according to some computing model. System software usually does not use those resources to complete tasks that directly benefit a user. A user would typically run an \fIapplication\fP that acquires and uses the resources controlled by the system software to accomplish some goal. .sp Often, the line of separation between system and application software is made at the privilege level change that happens in operating system traps. In \fIns\-3\fP there is no real concept of operating system and especially no concept of privilege levels or system calls. We do, however, have the idea of an application. Just as software applications run on computers to perform tasks in the “real world,” \fIns\-3\fP applications run on \fIns\-3\fP \fBNodes\fP to drive simulations in the simulated world. .sp In \fIns\-3\fP the basic abstraction for a user program that generates some activity to be simulated is the application. This abstraction is represented in C++ by the class \fBApplication\fP\&. The \fBApplication\fP class provides methods for managing the representations of our version of user\-level applications in simulations. Developers are expected to specialize the \fBApplication\fP class in the object\-oriented programming sense to create new applications. In this tutorial, we will use specializations of class \fBApplication\fP called \fBUdpEchoClientApplication\fP and \fBUdpEchoServerApplication\fP\&. As you might expect, these applications compose a client/server application set used to generate and echo simulated network packets .SS Channel .sp In the real world, one can connect a computer to a network. Often the media over which data flows in these networks are called \fIchannels\fP\&. When you connect your Ethernet cable to the plug in the wall, you are connecting your computer to an Ethernet communication channel. In the simulated world of \fIns\-3\fP, one connects a \fBNode\fP to an object representing a communication channel. Here the basic communication subnetwork abstraction is called the channel and is represented in C++ by the class \fBChannel\fP\&. .sp The \fBChannel\fP class provides methods for managing communication subnetwork objects and connecting nodes to them. \fBChannels\fP may also be specialized by developers in the object oriented programming sense. A \fBChannel\fP specialization may model something as simple as a wire. The specialized \fBChannel\fP can also model things as complicated as a large Ethernet switch, or three\-dimensional space full of obstructions in the case of wireless networks. .sp We will use specialized versions of the \fBChannel\fP called \fBCsmaChannel\fP, \fBPointToPointChannel\fP and \fBWifiChannel\fP in this tutorial. The \fBCsmaChannel\fP, for example, models a version of a communication subnetwork that implements a \fIcarrier sense multiple access\fP communication medium. This gives us Ethernet\-like functionality. .SS Net Device .sp It used to be the case that if you wanted to connect a computer to a network, you had to buy a specific kind of network cable and a hardware device called (in PC terminology) a \fIperipheral card\fP that needed to be installed in your computer. If the peripheral card implemented some networking function, they were called Network Interface Cards, or \fINICs\fP\&. Today most computers come with the network interface hardware built in and users don’t see these building blocks. .sp A NIC will not work without a software driver to control the hardware. In Unix (or Linux), a piece of peripheral hardware is classified as a \fIdevice\fP\&. Devices are controlled using \fIdevice drivers\fP, and network devices (NICs) are controlled using \fInetwork device drivers\fP collectively known as \fInet devices\fP\&. In Unix and Linux you refer to these net devices by names such as \fIeth0\fP\&. .sp In \fIns\-3\fP the \fInet device\fP abstraction covers both the software driver and the simulated hardware. A net device is “installed” in a \fBNode\fP in order to enable the \fBNode\fP to communicate with other \fBNodes\fP in the simulation via \fBChannels\fP\&. Just as in a real computer, a \fBNode\fP may be connected to more than one \fBChannel\fP via multiple \fBNetDevices\fP\&. .sp The net device abstraction is represented in C++ by the class \fBNetDevice\fP\&. The \fBNetDevice\fP class provides methods for managing connections to \fBNode\fP and \fBChannel\fP objects; and may be specialized by developers in the object\-oriented programming sense. We will use the several specialized versions of the \fBNetDevice\fP called \fBCsmaNetDevice\fP, \fBPointToPointNetDevice\fP, and \fBWifiNetDevice\fP in this tutorial. Just as an Ethernet NIC is designed to work with an Ethernet network, the \fBCsmaNetDevice\fP is designed to work with a \fBCsmaChannel\fP; the \fBPointToPointNetDevice\fP is designed to work with a \fBPointToPointChannel\fP and a \fBWifiNetNevice\fP is designed to work with a \fBWifiChannel\fP\&. .SS Topology Helpers .sp In a real network, you will find host computers with added (or built\-in) NICs. In \fIns\-3\fP we would say that you will find \fBNodes\fP with attached \fBNetDevices\fP\&. In a large simulated network you will need to arrange many connections between \fBNodes\fP, \fBNetDevices\fP and \fBChannels\fP\&. .sp Since connecting \fBNetDevices\fP to \fBNodes\fP, \fBNetDevices\fP to \fBChannels\fP, assigning IP addresses, etc., are such common tasks in \fIns\-3\fP, we provide what we call \fItopology helpers\fP to make this as easy as possible. For example, it may take many distinct \fIns\-3\fP core operations to create a NetDevice, add a MAC address, install that net device on a \fBNode\fP, configure the node’s protocol stack, and then connect the \fBNetDevice\fP to a \fBChannel\fP\&. Even more operations would be required to connect multiple devices onto multipoint channels and then to connect individual networks together into internetworks. We provide topology helper objects that combine those many distinct operations into an easy to use model for your convenience. .SS A First ns\-3 Script .sp If you downloaded the system as was suggested above, you will have a release of \fIns\-3\fP in a directory called \fBrepos\fP under your home directory. Change into that release directory, and you should find a directory structure something like the following: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C AUTHORS examples scratch utils waf.bat* bindings LICENSE src utils.py waf\-tools build ns3 test.py* utils.pyc wscript CHANGES.html README testpy\-output VERSION wutils.py doc RELEASE_NOTES testpy.supp waf* wutils.pyc .ft P .fi .UNINDENT .UNINDENT .sp Change into the \fBexamples/tutorial\fP directory. You should see a file named \fBfirst.cc\fP located there. This is a script that will create a simple point\-to\-point link between two nodes and echo a single packet between the nodes. Let’s take a look at that script line by line, so go ahead and open \fBfirst.cc\fP in your favorite editor. .SS Boilerplate .sp The first line in the file is an emacs mode line. This tells emacs about the formatting conventions (coding style) we use in our source code. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C /* \-*\- Mode:C++; c\-file\-style:"gnu"; indent\-tabs\-mode:nil; \-*\- */ .ft P .fi .UNINDENT .UNINDENT .sp This is always a somewhat controversial subject, so we might as well get it out of the way immediately. The \fIns\-3\fP project, like most large projects, has adopted a coding style to which all contributed code must adhere. If you want to contribute your code to the project, you will eventually have to conform to the \fIns\-3\fP coding standard as described in the file \fBdoc/codingstd.txt\fP or shown on the project web page \fI\%here\fP\&. .sp We recommend that you, well, just get used to the look and feel of \fIns\-3\fP code and adopt this standard whenever you are working with our code. All of the development team and contributors have done so with various amounts of grumbling. The emacs mode line above makes it easier to get the formatting correct if you use the emacs editor. .sp The \fIns\-3\fP simulator is licensed using the GNU General Public License. You will see the appropriate GNU legalese at the head of every file in the \fIns\-3\fP distribution. Often you will see a copyright notice for one of the institutions involved in the \fIns\-3\fP project above the GPL text and an author listed below. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111\-1307 USA */ .ft P .fi .UNINDENT .UNINDENT .SS Module Includes .sp The code proper starts with a number of include statements. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C #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" .ft P .fi .UNINDENT .UNINDENT .sp To help our high\-level script users deal with the large number of include files present in the system, we group includes according to relatively large modules. We provide a single include file that will recursively load all of the include files used in each module. Rather than having to look up exactly what header you need, and possibly have to get a number of dependencies right, we give you the ability to load a group of files at a large granularity. This is not the most efficient approach but it certainly makes writing scripts much easier. .sp Each of the \fIns\-3\fP include files is placed in a directory called \fBns3\fP (under the build directory) during the build process to help avoid include file name collisions. The \fBns3/core\-module.h\fP file corresponds to the ns\-3 module you will find in the directory \fBsrc/core\fP in your downloaded release distribution. If you list this directory you will find a large number of header files. When you do a build, Waf will place public header files in an \fBns3\fP directory under the appropriate \fBbuild/debug\fP or \fBbuild/optimized\fP directory depending on your configuration. Waf will also automatically generate a module include file to load all of the public header files. .sp Since you are, of course, following this tutorial religiously, you will already have done a .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./waf \-d debug \-\-enable\-examples \-\-enable\-tests configure .ft P .fi .UNINDENT .UNINDENT .sp in order to configure the project to perform debug builds that include examples and tests. You will also have done a .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./waf .ft P .fi .UNINDENT .UNINDENT .sp to build the project. So now if you look in the directory \fB\&../../build/debug/ns3\fP you will find the four module include files shown above. You can take a look at the contents of these files and find that they do include all of the public include files in their respective modules. .SS Ns3 Namespace .sp The next line in the \fBfirst.cc\fP script is a namespace declaration. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C using namespace ns3; .ft P .fi .UNINDENT .UNINDENT .sp The \fIns\-3\fP project is implemented in a C++ namespace called \fBns3\fP\&. This groups all \fIns\-3\fP\-related declarations in a scope outside the global namespace, which we hope will help with integration with other code. The C++ \fBusing\fP statement introduces the \fIns\-3\fP namespace into the current (global) declarative region. This is a fancy way of saying that after this declaration, you will not have to type \fBns3::\fP scope resolution operator before all of the \fIns\-3\fP code in order to use it. If you are unfamiliar with namespaces, please consult almost any C++ tutorial and compare the \fBns3\fP namespace and usage here with instances of the \fBstd\fP namespace and the \fBusing namespace std;\fP statements you will often find in discussions of \fBcout\fP and streams. .SS Logging .sp The next line of the script is the following, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C NS_LOG_COMPONENT_DEFINE ("FirstScriptExample"); .ft P .fi .UNINDENT .UNINDENT .sp We will use this statement as a convenient place to talk about our Doxygen documentation system. If you look at the project web site, \fI\%ns\-3 project\fP, you will find a link to “Documentation” in the navigation bar. If you select this link, you will be taken to our documentation page. There is a link to “Latest Release” that will take you to the documentation for the latest stable release of \fIns\-3\fP\&. If you select the “API Documentation” link, you will be taken to the \fIns\-3\fP API documentation page. .sp Along the left side, you will find a graphical representation of the structure of the documentation. A good place to start is the \fBNS\-3 Modules\fP “book” in the \fIns\-3\fP navigation tree. If you expand \fBModules\fP you will see a list of \fIns\-3\fP module documentation. The concept of module here ties directly into the module include files discussed above. The \fIns\-3\fP logging subsystem is discussed in the \fI\%Using the Logging Module\fP section, so we’ll get to it later in this tutorial, but you can find out about the above statement by looking at the \fBCore\fP module, then expanding the \fBDebugging tools\fP book, and then selecting the \fBLogging\fP page. Click on \fBLogging\fP\&. .sp You should now be looking at the Doxygen documentation for the Logging module. In the list of \fBMacros\fP’s at the top of the page you will see the entry for \fBNS_LOG_COMPONENT_DEFINE\fP\&. Before jumping in, it would probably be good to look for the “Detailed Description” of the logging module to get a feel for the overall operation. You can either scroll down or select the “More…” link under the collaboration diagram to do this. .sp Once you have a general idea of what is going on, go ahead and take a look at the specific \fBNS_LOG_COMPONENT_DEFINE\fP documentation. I won’t duplicate the documentation here, but to summarize, this line declares a logging component called \fBFirstScriptExample\fP that allows you to enable and disable console message logging by reference to the name. .SS Main Function .sp The next lines of the script you will find are, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C int main (int argc, char *argv[]) { .ft P .fi .UNINDENT .UNINDENT .sp This is just the declaration of the main function of your program (script). Just as in any C++ program, you need to define a main function that will be the first function run. There is nothing at all special here. Your \fIns\-3\fP script is just a C++ program. .sp The next line sets the time resolution to one nanosecond, which happens to be the default value: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Time::SetResolution (Time::NS); .ft P .fi .UNINDENT .UNINDENT .sp The resolution is the smallest time value that can be represented (as well as the smallest representable difference between two time values). You can change the resolution exactly once. The mechanism enabling this flexibility is somewhat memory hungry, so once the resolution has been set explicitly we release the memory, preventing further updates. (If you don’t set the resolution explicitly, it will default to one nanosecond, and the memory will be released when the simulation starts.) .sp The next two lines of the script are used to enable two logging components that are built into the Echo Client and Echo Server applications: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C LogComponentEnable("UdpEchoClientApplication", LOG_LEVEL_INFO); LogComponentEnable("UdpEchoServerApplication", LOG_LEVEL_INFO); .ft P .fi .UNINDENT .UNINDENT .sp If you have read over the Logging component documentation you will have seen that there are a number of levels of logging verbosity/detail that you can enable on each component. These two lines of code enable debug logging at the INFO level for echo clients and servers. This will result in the application printing out messages as packets are sent and received during the simulation. .sp Now we will get directly to the business of creating a topology and running a simulation. We use the topology helper objects to make this job as easy as possible. .SS Topology Helpers .SS NodeContainer .sp The next two lines of code in our script will actually create the \fIns\-3\fP \fBNode\fP objects that will represent the computers in the simulation. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C NodeContainer nodes; nodes.Create (2); .ft P .fi .UNINDENT .UNINDENT .sp Let’s find the documentation for the \fBNodeContainer\fP class before we continue. Another way to get into the documentation for a given class is via the \fBClasses\fP tab in the Doxygen pages. If you still have the Doxygen handy, just scroll up to the top of the page and select the \fBClasses\fP tab. You should see a new set of tabs appear, one of which is \fBClass List\fP\&. Under that tab you will see a list of all of the \fIns\-3\fP classes. Scroll down, looking for \fBns3::NodeContainer\fP\&. When you find the class, go ahead and select it to go to the documentation for the class. .sp You may recall that one of our key abstractions is the \fBNode\fP\&. This represents a computer to which we are going to add things like protocol stacks, applications and peripheral cards. The \fBNodeContainer\fP topology helper provides a convenient way to create, manage and access any \fBNode\fP objects that we create in order to run a simulation. The first line above just declares a NodeContainer which we call \fBnodes\fP\&. The second line calls the \fBCreate\fP method on the \fBnodes\fP object and asks the container to create two nodes. As described in the Doxygen, the container calls down into the \fIns\-3\fP system proper to create two \fBNode\fP objects and stores pointers to those objects internally. .sp The nodes as they stand in the script do nothing. The next step in constructing a topology is to connect our nodes together into a network. The simplest form of network we support is a single point\-to\-point link between two nodes. We’ll construct one of those links here. .SS PointToPointHelper .sp We are constructing a point to point link, and, in a pattern which will become quite familiar to you, we use a topology helper object to do the low\-level work required to put the link together. Recall that two of our key abstractions are the \fBNetDevice\fP and the \fBChannel\fP\&. In the real world, these terms correspond roughly to peripheral cards and network cables. Typically these two things are intimately tied together and one cannot expect to interchange, for example, Ethernet devices and wireless channels. Our Topology Helpers follow this intimate coupling and therefore you will use a single \fBPointToPointHelper\fP to configure and connect \fIns\-3\fP \fBPointToPointNetDevice\fP and \fBPointToPointChannel\fP objects in this script. .sp The next three lines in the script are, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C PointToPointHelper pointToPoint; pointToPoint.SetDeviceAttribute ("DataRate", StringValue ("5Mbps")); pointToPoint.SetChannelAttribute ("Delay", StringValue ("2ms")); .ft P .fi .UNINDENT .UNINDENT .sp The first line, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C PointToPointHelper pointToPoint; .ft P .fi .UNINDENT .UNINDENT .sp instantiates a \fBPointToPointHelper\fP object on the stack. From a high\-level perspective the next line, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C pointToPoint.SetDeviceAttribute ("DataRate", StringValue ("5Mbps")); .ft P .fi .UNINDENT .UNINDENT .sp tells the \fBPointToPointHelper\fP object to use the value “5Mbps” (five megabits per second) as the “DataRate” when it creates a \fBPointToPointNetDevice\fP object. .sp From a more detailed perspective, the string “DataRate” corresponds to what we call an \fBAttribute\fP of the \fBPointToPointNetDevice\fP\&. If you look at the Doxygen for class \fBns3::PointToPointNetDevice\fP and find the documentation for the \fBGetTypeId\fP method, you will find a list of \fBAttributes\fP defined for the device. Among these is the “DataRate” \fBAttribute\fP\&. Most user\-visible \fIns\-3\fP objects have similar lists of \fBAttributes\fP\&. We use this mechanism to easily configure simulations without recompiling as you will see in a following section. .sp Similar to the “DataRate” on the \fBPointToPointNetDevice\fP you will find a “Delay” \fBAttribute\fP associated with the \fBPointToPointChannel\fP\&. The final line, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C pointToPoint.SetChannelAttribute ("Delay", StringValue ("2ms")); .ft P .fi .UNINDENT .UNINDENT .sp tells the \fBPointToPointHelper\fP to use the value “2ms” (two milliseconds) as the value of the propagation delay of every point to point channel it subsequently creates. .SS NetDeviceContainer .sp At this point in the script, we have a \fBNodeContainer\fP that contains two nodes. We have a \fBPointToPointHelper\fP that is primed and ready to make \fBPointToPointNetDevices\fP and wire \fBPointToPointChannel\fP objects between them. Just as we used the \fBNodeContainer\fP topology helper object to create the \fBNodes\fP for our simulation, we will ask the \fBPointToPointHelper\fP to do the work involved in creating, configuring and installing our devices for us. We will need to have a list of all of the NetDevice objects that are created, so we use a NetDeviceContainer to hold them just as we used a NodeContainer to hold the nodes we created. The following two lines of code, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C NetDeviceContainer devices; devices = pointToPoint.Install (nodes); .ft P .fi .UNINDENT .UNINDENT .sp will finish configuring the devices and channel. The first line declares the device container mentioned above and the second does the heavy lifting. The \fBInstall\fP method of the \fBPointToPointHelper\fP takes a \fBNodeContainer\fP as a parameter. Internally, a \fBNetDeviceContainer\fP is created. For each node in the \fBNodeContainer\fP (there must be exactly two for a point\-to\-point link) a \fBPointToPointNetDevice\fP is created and saved in the device container. A \fBPointToPointChannel\fP is created and the two \fBPointToPointNetDevices\fP are attached. When objects are created by the \fBPointToPointHelper\fP, the \fBAttributes\fP previously set in the helper are used to initialize the corresponding \fBAttributes\fP in the created objects. .sp After executing the \fBpointToPoint.Install (nodes)\fP call we will have two nodes, each with an installed point\-to\-point net device and a single point\-to\-point channel between them. Both devices will be configured to transmit data at five megabits per second over the channel which has a two millisecond transmission delay. .SS InternetStackHelper .sp We now have nodes and devices configured, but we don’t have any protocol stacks installed on our nodes. The next two lines of code will take care of that. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C InternetStackHelper stack; stack.Install (nodes); .ft P .fi .UNINDENT .UNINDENT .sp The \fBInternetStackHelper\fP is a topology helper that is to internet stacks what the \fBPointToPointHelper\fP is to point\-to\-point net devices. The \fBInstall\fP method takes a \fBNodeContainer\fP as a parameter. When it is executed, it will install an Internet Stack (TCP, UDP, IP, etc.) on each of the nodes in the node container. .SS Ipv4AddressHelper .sp Next we need to associate the devices on our nodes with IP addresses. We provide a topology helper to manage the allocation of IP addresses. The only user\-visible API is to set the base IP address and network mask to use when performing the actual address allocation (which is done at a lower level inside the helper). .sp The next two lines of code in our example script, \fBfirst.cc\fP, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Ipv4AddressHelper address; address.SetBase ("10.1.1.0", "255.255.255.0"); .ft P .fi .UNINDENT .UNINDENT .sp declare an address helper object and tell it that it should begin allocating IP addresses from the network 10.1.1.0 using the mask 255.255.255.0 to define the allocatable bits. By default the addresses allocated will start at one and increase monotonically, so the first address allocated from this base will be 10.1.1.1, followed by 10.1.1.2, etc. The low level \fIns\-3\fP system actually remembers all of the IP addresses allocated and will generate a fatal error if you accidentally cause the same address to be generated twice (which is a very hard to debug error, by the way). .sp The next line of code, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Ipv4InterfaceContainer interfaces = address.Assign (devices); .ft P .fi .UNINDENT .UNINDENT .sp performs the actual address assignment. In \fIns\-3\fP we make the association between an IP address and a device using an \fBIpv4Interface\fP object. Just as we sometimes need a list of net devices created by a helper for future reference we sometimes need a list of \fBIpv4Interface\fP objects. The \fBIpv4InterfaceContainer\fP provides this functionality. .sp Now we have a point\-to\-point network built, with stacks installed and IP addresses assigned. What we need at this point are applications to generate traffic. .SS Applications .sp Another one of the core abstractions of the ns\-3 system is the \fBApplication\fP\&. In this script we use two specializations of the core \fIns\-3\fP class \fBApplication\fP called \fBUdpEchoServerApplication\fP and \fBUdpEchoClientApplication\fP\&. Just as we have in our previous explanations, we use helper objects to help configure and manage the underlying objects. Here, we use \fBUdpEchoServerHelper\fP and \fBUdpEchoClientHelper\fP objects to make our lives easier. .SS UdpEchoServerHelper .sp The following lines of code in our example script, \fBfirst.cc\fP, are used to set up a UDP echo server application on one of the nodes we have previously created. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C UdpEchoServerHelper echoServer (9); ApplicationContainer serverApps = echoServer.Install (nodes.Get (1)); serverApps.Start (Seconds (1.0)); serverApps.Stop (Seconds (10.0)); .ft P .fi .UNINDENT .UNINDENT .sp The first line of code in the above snippet declares the \fBUdpEchoServerHelper\fP\&. As usual, this isn’t the application itself, it is an object used to help us create the actual applications. One of our conventions is to place \fIrequired\fP \fBAttributes\fP in the helper constructor. In this case, the helper can’t do anything useful unless it is provided with a port number that the client also knows about. Rather than just picking one and hoping it all works out, we require the port number as a parameter to the constructor. The constructor, in turn, simply does a \fBSetAttribute\fP with the passed value. If you want, you can set the “Port” \fBAttribute\fP to another value later using \fBSetAttribute\fP\&. .sp Similar to many other helper objects, the \fBUdpEchoServerHelper\fP object has an \fBInstall\fP method. It is the execution of this method that actually causes the underlying echo server application to be instantiated and attached to a node. Interestingly, the \fBInstall\fP method takes a \fBNodeContainter\fP as a parameter just as the other \fBInstall\fP methods we have seen. This is actually what is passed to the method even though it doesn’t look so in this case. There is a C++ \fIimplicit conversion\fP at work here that takes the result of \fBnodes.Get (1)\fP (which returns a smart pointer to a node object — \fBPtr\fP) and uses that in a constructor for an unnamed \fBNodeContainer\fP that is then passed to \fBInstall\fP\&. If you are ever at a loss to find a particular method signature in C++ code that compiles and runs just fine, look for these kinds of implicit conversions. .sp We now see that \fBechoServer.Install\fP is going to install a \fBUdpEchoServerApplication\fP on the node found at index number one of the \fBNodeContainer\fP we used to manage our nodes. \fBInstall\fP will return a container that holds pointers to all of the applications (one in this case since we passed a \fBNodeContainer\fP containing one node) created by the helper. .sp Applications require a time to “start” generating traffic and may take an optional time to “stop”. We provide both. These times are set using the \fBApplicationContainer\fP methods \fBStart\fP and \fBStop\fP\&. These methods take \fBTime\fP parameters. In this case, we use an \fIexplicit\fP C++ conversion sequence to take the C++ double 1.0 and convert it to an \fIns\-3\fP \fBTime\fP object using a \fBSeconds\fP cast. Be aware that the conversion rules may be controlled by the model author, and C++ has its own rules, so you can’t always just assume that parameters will be happily converted for you. The two lines, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C serverApps.Start (Seconds (1.0)); serverApps.Stop (Seconds (10.0)); .ft P .fi .UNINDENT .UNINDENT .sp will cause the echo server application to \fBStart\fP (enable itself) at one second into the simulation and to \fBStop\fP (disable itself) at ten seconds into the simulation. By virtue of the fact that we have declared a simulation event (the application stop event) to be executed at ten seconds, the simulation will last \fIat least\fP ten seconds. .SS UdpEchoClientHelper .sp The echo client application is set up in a method substantially similar to that for the server. There is an underlying \fBUdpEchoClientApplication\fP that is managed by an \fBUdpEchoClientHelper\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C 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)); .ft P .fi .UNINDENT .UNINDENT .sp For the echo client, however, we need to set five different \fBAttributes\fP\&. The first two \fBAttributes\fP are set during construction of the \fBUdpEchoClientHelper\fP\&. We pass parameters that are used (internally to the helper) to set the “RemoteAddress” and “RemotePort” \fBAttributes\fP in accordance with our convention to make required \fBAttributes\fP parameters in the helper constructors. .sp Recall that we used an \fBIpv4InterfaceContainer\fP to keep track of the IP addresses we assigned to our devices. The zeroth interface in the \fBinterfaces\fP container is going to correspond to the IP address of the zeroth node in the \fBnodes\fP container. The first interface in the \fBinterfaces\fP container corresponds to the IP address of the first node in the \fBnodes\fP container. So, in the first line of code (from above), we are creating the helper and telling it so set the remote address of the client to be the IP address assigned to the node on which the server resides. We also tell it to arrange to send packets to port nine. .sp The “MaxPackets” \fBAttribute\fP tells the client the maximum number of packets we allow it to send during the simulation. The “Interval” \fBAttribute\fP tells the client how long to wait between packets, and the “PacketSize” \fBAttribute\fP tells the client how large its packet payloads should be. With this particular combination of \fBAttributes\fP, we are telling the client to send one 1024\-byte packet. .sp Just as in the case of the echo server, we tell the echo client to \fBStart\fP and \fBStop\fP, but here we start the client one second after the server is enabled (at two seconds into the simulation). .SS Simulator .sp What we need to do at this point is to actually run the simulation. This is done using the global function \fBSimulator::Run\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Simulator::Run (); .ft P .fi .UNINDENT .UNINDENT .sp When we previously called the methods, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C serverApps.Start (Seconds (1.0)); serverApps.Stop (Seconds (10.0)); \&... clientApps.Start (Seconds (2.0)); clientApps.Stop (Seconds (10.0)); .ft P .fi .UNINDENT .UNINDENT .sp we actually scheduled events in the simulator at 1.0 seconds, 2.0 seconds and two events at 10.0 seconds. When \fBSimulator::Run\fP is called, the system will begin looking through the list of scheduled events and executing them. First it will run the event at 1.0 seconds, which will enable the echo server application (this event may, in turn, schedule many other events). Then it will run the event scheduled for t=2.0 seconds which will start the echo client application. Again, this event may schedule many more events. The start event implementation in the echo client application will begin the data transfer phase of the simulation by sending a packet to the server. .sp The act of sending the packet to the server will trigger a chain of events that will be automatically scheduled behind the scenes and which will perform the mechanics of the packet echo according to the various timing parameters that we have set in the script. .sp Eventually, since we only send one packet (recall the \fBMaxPackets\fP \fBAttribute\fP was set to one), the chain of events triggered by that single client echo request will taper off and the simulation will go idle. Once this happens, the remaining events will be the \fBStop\fP events for the server and the client. When these events are executed, there are no further events to process and \fBSimulator::Run\fP returns. The simulation is then complete. .sp All that remains is to clean up. This is done by calling the global function \fBSimulator::Destroy\fP\&. As the helper functions (or low level \fIns\-3\fP code) executed, they arranged it so that hooks were inserted in the simulator to destroy all of the objects that were created. You did not have to keep track of any of these objects yourself — all you had to do was to call \fBSimulator::Destroy\fP and exit. The \fIns\-3\fP system took care of the hard part for you. The remaining lines of our first \fIns\-3\fP script, \fBfirst.cc\fP, do just that: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Simulator::Destroy (); return 0; } .ft P .fi .UNINDENT .UNINDENT .SS When the simulator will stop? .sp \fIns\-3\fP is a Discrete Event (DE) simulator. In such a simulator, each event is associated with its execution time, and the simulation proceeds by executing events in the temporal order of simulation time. Events may cause future events to be scheduled (for example, a timer may reschedule itself to expire at the next interval). .sp The initial events are usually triggered by each object, e.g., IPv6 will schedule Router Advertisements, Neighbor Solicitations, etc., an Application schedule the first packet sending event, etc. .sp When an event is processed, it may generate zero, one or more events. As a simulation executes, events are consumed, but more events may (or may not) be generated. The simulation will stop automatically when no further events are in the event queue, or when a special Stop event is found. The Stop event is created through the \fBSimulator::Stop (stopTime);\fP function. .sp There is a typical case where \fBSimulator::Stop\fP is absolutely necessary to stop the simulation: when there is a self\-sustaining event. Self\-sustaining (or recurring) events are events that always reschedule themselves. As a consequence, they always keep the event queue non\-empty. .sp There are many protocols and modules containing recurring events, e.g.: .INDENT 0.0 .IP \(bu 2 FlowMonitor \- periodic check for lost packets .IP \(bu 2 RIPng \- periodic broadcast of routing tables update .IP \(bu 2 etc. .UNINDENT .sp In these cases, \fBSimulator::Stop\fP is necessary to gracefully stop the simulation. In addition, when \fIns\-3\fP is in emulation mode, the \fBRealtimeSimulator\fP is used to keep the simulation clock aligned with the machine clock, and \fBSimulator::Stop\fP is necessary to stop the process. .sp Many of the simulation programs in the tutorial do not explicitly call \fBSimulator::Stop\fP, since the event queue will automatically run out of events. However, these programs will also accept a call to \fBSimulator::Stop\fP\&. For example, the following additional statement in the first example program will schedule an explicit stop at 11 seconds: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C + Simulator::Stop (Seconds (11.0)); Simulator::Run (); Simulator::Destroy (); return 0; } .ft P .fi .UNINDENT .UNINDENT .sp The above will not actually change the behavior of this program, since this particular simulation naturally ends after 10 seconds. But if you were to change the stop time in the above statement from 11 seconds to 1 second, you would notice that the simulation stops before any output is printed to the screen (since the output occurs around time 2 seconds of simulation time). .sp It is important to call \fBSimulator::Stop\fP \fIbefore\fP calling \fBSimulator::Run\fP; otherwise, \fBSimulator::Run\fP may never return control to the main program to execute the stop! .SS Building Your Script .sp We have made it trivial to build your simple scripts. All you have to do is to drop your script into the scratch directory and it will automatically be built if you run Waf. Let’s try it. Copy \fBexamples/tutorial/first.cc\fP into the \fBscratch\fP directory after changing back into the top level directory. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ cd ../.. $ cp examples/tutorial/first.cc scratch/myfirst.cc .ft P .fi .UNINDENT .UNINDENT .sp Now build your first example script using waf: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./waf .ft P .fi .UNINDENT .UNINDENT .sp You should see messages reporting that your \fBmyfirst\fP example was built successfully. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Waf: Entering directory \(ga/home/craigdo/repos/ns\-3\-allinone/ns\-3\-dev/build\(aq [614/708] cxx: scratch/myfirst.cc \-> build/debug/scratch/myfirst_3.o [706/708] cxx_link: build/debug/scratch/myfirst_3.o \-> build/debug/scratch/myfirst Waf: Leaving directory \(ga/home/craigdo/repos/ns\-3\-allinone/ns\-3\-dev/build\(aq \(aqbuild\(aq finished successfully (2.357s) .ft P .fi .UNINDENT .UNINDENT .sp You can now run the example (note that if you build your program in the scratch directory you must run it out of the scratch directory): .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./waf \-\-run scratch/myfirst .ft P .fi .UNINDENT .UNINDENT .sp You should see some output: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Waf: Entering directory \(ga/home/craigdo/repos/ns\-3\-allinone/ns\-3\-dev/build\(aq Waf: Leaving directory \(ga/home/craigdo/repos/ns\-3\-allinone/ns\-3\-dev/build\(aq \(aqbuild\(aq finished successfully (0.418s) Sent 1024 bytes to 10.1.1.2 Received 1024 bytes from 10.1.1.1 Received 1024 bytes from 10.1.1.2 .ft P .fi .UNINDENT .UNINDENT .sp Here you see that the build system checks to make sure that the file has been build and then runs it. You see the logging component on the echo client indicate that it has sent one 1024 byte packet to the Echo Server on 10.1.1.2. You also see the logging component on the echo server say that it has received the 1024 bytes from 10.1.1.1. The echo server silently echoes the packet and you see the echo client log that it has received its packet back from the server. .SS Ns\-3 Source Code .sp Now that you have used some of the \fIns\-3\fP helpers you may want to have a look at some of the source code that implements that functionality. The most recent code can be browsed on our web server at the following link: \fI\%https://gitlab.com/nsnam/ns\-3\-dev.git\fP\&. There, you will see the Git/GitLab summary page for our \fIns\-3\fP development tree. .sp At the top of the page, you will see a number of links, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C summary | shortlog | changelog | graph | tags | files .ft P .fi .UNINDENT .UNINDENT .sp Go ahead and select the \fBfiles\fP link. This is what the top\-level of most of our \fIrepositories\fP will look: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C drwxr\-xr\-x [up] drwxr\-xr\-x bindings python files drwxr\-xr\-x doc files drwxr\-xr\-x examples files drwxr\-xr\-x ns3 files drwxr\-xr\-x scratch files drwxr\-xr\-x src files drwxr\-xr\-x utils files \-rw\-r\-\-r\-\- 2009\-07\-01 12:47 +0200 560 .hgignore file | revisions | annotate \-rw\-r\-\-r\-\- 2009\-07\-01 12:47 +0200 1886 .hgtags file | revisions | annotate \-rw\-r\-\-r\-\- 2009\-07\-01 12:47 +0200 1276 AUTHORS file | revisions | annotate \-rw\-r\-\-r\-\- 2009\-07\-01 12:47 +0200 30961 CHANGES.html file | revisions | annotate \-rw\-r\-\-r\-\- 2009\-07\-01 12:47 +0200 17987 LICENSE file | revisions | annotate \-rw\-r\-\-r\-\- 2009\-07\-01 12:47 +0200 3742 README file | revisions | annotate \-rw\-r\-\-r\-\- 2009\-07\-01 12:47 +0200 16171 RELEASE_NOTES file | revisions | annotate \-rw\-r\-\-r\-\- 2009\-07\-01 12:47 +0200 6 VERSION file | revisions | annotate \-rwxr\-xr\-x 2009\-07\-01 12:47 +0200 88110 waf file | revisions | annotate \-rwxr\-xr\-x 2009\-07\-01 12:47 +0200 28 waf.bat file | revisions | annotate \-rw\-r\-\-r\-\- 2009\-07\-01 12:47 +0200 35395 wscript file | revisions | annotate \-rw\-r\-\-r\-\- 2009\-07\-01 12:47 +0200 7673 wutils.py file | revisions | annotate .ft P .fi .UNINDENT .UNINDENT .sp Our example scripts are in the \fBexamples\fP directory. If you click on \fBexamples\fP you will see a list of subdirectories. One of the files in \fBtutorial\fP subdirectory is \fBfirst.cc\fP\&. If you click on \fBfirst.cc\fP you will find the code you just walked through. .sp The source code is mainly in the \fBsrc\fP directory. You can view source code either by clicking on the directory name or by clicking on the \fBfiles\fP link to the right of the directory name. If you click on the \fBsrc\fP directory, you will be taken to the listing of the \fBsrc\fP subdirectories. If you then click on \fBcore\fP subdirectory, you will find a list of files. The first file you will find (as of this writing) is \fBabort.h\fP\&. If you click on the \fBabort.h\fP link, you will be sent to the source file for \fBabort.h\fP which contains useful macros for exiting scripts if abnormal conditions are detected. .sp The source code for the helpers we have used in this chapter can be found in the \fBsrc/applications/helper\fP directory. Feel free to poke around in the directory tree to get a feel for what is there and the style of \fIns\-3\fP programs. .SH TWEAKING .SS Using the Logging Module .sp We have already taken a brief look at the \fIns\-3\fP logging module while going over the \fBfirst.cc\fP script. We will now take a closer look and see what kind of use\-cases the logging subsystem was designed to cover. .SS Logging Overview .sp Many large systems support some kind of message logging facility, and \fIns\-3\fP is not an exception. In some cases, only error messages are logged to the “operator console” (which is typically \fBstderr\fP in Unix\- based systems). In other systems, warning messages may be output as well as more detailed informational messages. In some cases, logging facilities are used to output debug messages which can quickly turn the output into a blur. .sp \fIns\-3\fP takes the view that all of these verbosity levels are useful and we provide a selectable, multi\-level approach to message logging. Logging can be disabled completely, enabled on a component\-by\-component basis, or enabled globally; and it provides selectable verbosity levels. The \fIns\-3\fP log module provides a straightforward, relatively easy to use way to get useful information out of your simulation. .sp You should understand that we do provide a general purpose mechanism — tracing — to get data out of your models which should be preferred for simulation output (see the tutorial section Using the Tracing System for more details on our tracing system). Logging should be preferred for debugging information, warnings, error messages, or any time you want to easily get a quick message out of your scripts or models. .sp There are currently seven levels of log messages of increasing verbosity defined in the system. .INDENT 0.0 .IP \(bu 2 LOG_ERROR — Log error messages (associated macro: NS_LOG_ERROR); .IP \(bu 2 LOG_WARN — Log warning messages (associated macro: NS_LOG_WARN); .IP \(bu 2 LOG_DEBUG — Log relatively rare, ad\-hoc debugging messages (associated macro: NS_LOG_DEBUG); .IP \(bu 2 LOG_INFO — Log informational messages about program progress (associated macro: NS_LOG_INFO); .IP \(bu 2 LOG_FUNCTION — Log a message describing each function called (two associated macros: NS_LOG_FUNCTION, used for member functions, and NS_LOG_FUNCTION_NOARGS, used for static functions); .IP \(bu 2 LOG_LOGIC – Log messages describing logical flow within a function (associated macro: NS_LOG_LOGIC); .IP \(bu 2 LOG_ALL — Log everything mentioned above (no associated macro). .UNINDENT .sp For each LOG_TYPE there is also LOG_LEVEL_TYPE that, if used, enables logging of all the levels above it in addition to it’s level. (As a consequence of this, LOG_ERROR and LOG_LEVEL_ERROR and also LOG_ALL and LOG_LEVEL_ALL are functionally equivalent.) For example, enabling LOG_INFO will only enable messages provided by NS_LOG_INFO macro, while enabling LOG_LEVEL_INFO will also enable messages provided by NS_LOG_DEBUG, NS_LOG_WARN and NS_LOG_ERROR macros. .sp We also provide an unconditional logging macro that is always displayed, irrespective of logging levels or component selection. .INDENT 0.0 .IP \(bu 2 NS_LOG_UNCOND – Log the associated message unconditionally (no associated log level). .UNINDENT .sp Each level can be requested singly or cumulatively; and logging can be set up using a shell environment variable (NS_LOG) or by logging system function call. As was seen earlier in the tutorial, the logging system has Doxygen documentation and now would be a good time to peruse the Logging Module documentation if you have not done so. .sp Now that you have read the documentation in great detail, let’s use some of that knowledge to get some interesting information out of the \fBscratch/myfirst.cc\fP example script you have already built. .SS Enabling Logging .sp Let’s use the NS_LOG environment variable to turn on some more logging, but first, just to get our bearings, go ahead and run the last script just as you did previously, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./waf \-\-run scratch/myfirst .ft P .fi .UNINDENT .UNINDENT .sp You should see the now familiar output of the first \fIns\-3\fP example program .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ Waf: Entering directory \(ga/home/craigdo/repos/ns\-3\-allinone/ns\-3\-dev/build\(aq Waf: Leaving directory \(ga/home/craigdo/repos/ns\-3\-allinone/ns\-3\-dev/build\(aq \(aqbuild\(aq finished successfully (0.413s) Sent 1024 bytes to 10.1.1.2 Received 1024 bytes from 10.1.1.1 Received 1024 bytes from 10.1.1.2 .ft P .fi .UNINDENT .UNINDENT .sp It turns out that the “Sent” and “Received” messages you see above are actually logging messages from the \fBUdpEchoClientApplication\fP and \fBUdpEchoServerApplication\fP\&. We can ask the client application, for example, to print more information by setting its logging level via the NS_LOG environment variable. .sp I am going to assume from here on that you are using an sh\-like shell that uses the”VARIABLE=value” syntax. If you are using a csh\-like shell, then you will have to convert my examples to the “setenv VARIABLE value” syntax required by those shells. .sp Right now, the UDP echo client application is responding to the following line of code in \fBscratch/myfirst.cc\fP, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C LogComponentEnable("UdpEchoClientApplication", LOG_LEVEL_INFO); .ft P .fi .UNINDENT .UNINDENT .sp This line of code enables the \fBLOG_LEVEL_INFO\fP level of logging. When we pass a logging level flag, we are actually enabling the given level and all lower levels. In this case, we have enabled \fBNS_LOG_INFO\fP, \fBNS_LOG_DEBUG\fP, \fBNS_LOG_WARN\fP and \fBNS_LOG_ERROR\fP\&. We can increase the logging level and get more information without changing the script and recompiling by setting the NS_LOG environment variable like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ export NS_LOG=UdpEchoClientApplication=level_all .ft P .fi .UNINDENT .UNINDENT .sp This sets the shell environment variable \fBNS_LOG\fP to the string, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C UdpEchoClientApplication=level_all .ft P .fi .UNINDENT .UNINDENT .sp The left hand side of the assignment is the name of the logging component we want to set, and the right hand side is the flag we want to use. In this case, we are going to turn on all of the debugging levels for the application. If you run the script with NS_LOG set this way, the \fIns\-3\fP logging system will pick up the change and you should see the following output: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Waf: Entering directory \(ga/home/craigdo/repos/ns\-3\-allinone/ns\-3\-dev/build\(aq Waf: Leaving directory \(ga/home/craigdo/repos/ns\-3\-allinone/ns\-3\-dev/build\(aq \(aqbuild\(aq finished successfully (0.404s) UdpEchoClientApplication:UdpEchoClient() UdpEchoClientApplication:SetDataSize(1024) UdpEchoClientApplication:StartApplication() UdpEchoClientApplication:ScheduleTransmit() UdpEchoClientApplication:Send() Sent 1024 bytes to 10.1.1.2 Received 1024 bytes from 10.1.1.1 UdpEchoClientApplication:HandleRead(0x6241e0, 0x624a20) Received 1024 bytes from 10.1.1.2 UdpEchoClientApplication:StopApplication() UdpEchoClientApplication:DoDispose() UdpEchoClientApplication:~UdpEchoClient() .ft P .fi .UNINDENT .UNINDENT .sp The additional debug information provided by the application is from the NS_LOG_FUNCTION level. This shows every time a function in the application is called during script execution. Generally, use of (at least) NS_LOG_FUNCTION(this) in member functions is preferred. Use NS_LOG_FUNCTION_NOARGS() only in static functions. Note, however, that there are no requirements in the \fIns\-3\fP system that models must support any particular logging functionality. The decision regarding how much information is logged is left to the individual model developer. In the case of the echo applications, a good deal of log output is available. .sp You can now see a log of the function calls that were made to the application. If you look closely you will notice a single colon between the string \fBUdpEchoClientApplication\fP and the method name where you might have expected a C++ scope operator (\fB::\fP). This is intentional. .sp The name is not actually a class name, it is a logging component name. When there is a one\-to\-one correspondence between a source file and a class, this will generally be the class name but you should understand that it is not actually a class name, and there is a single colon there instead of a double colon to remind you in a relatively subtle way to conceptually separate the logging component name from the class name. .sp It turns out that in some cases, it can be hard to determine which method actually generates a log message. If you look in the text above, you may wonder where the string “\fBReceived 1024 bytes from 10.1.1.2\fP” comes from. You can resolve this by OR’ing the \fBprefix_func\fP level into the \fBNS_LOG\fP environment variable. Try doing the following, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ export \(aqNS_LOG=UdpEchoClientApplication=level_all|prefix_func\(aq .ft P .fi .UNINDENT .UNINDENT .sp Note that the quotes are required since the vertical bar we use to indicate an OR operation is also a Unix pipe connector. .sp Now, if you run the script you will see that the logging system makes sure that every message from the given log component is prefixed with the component name. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Waf: Entering directory \(ga/home/craigdo/repos/ns\-3\-allinone/ns\-3\-dev/build\(aq Waf: Leaving directory \(ga/home/craigdo/repos/ns\-3\-allinone/ns\-3\-dev/build\(aq \(aqbuild\(aq finished successfully (0.417s) UdpEchoClientApplication:UdpEchoClient() UdpEchoClientApplication:SetDataSize(1024) UdpEchoClientApplication:StartApplication() UdpEchoClientApplication:ScheduleTransmit() UdpEchoClientApplication:Send() UdpEchoClientApplication:Send(): Sent 1024 bytes to 10.1.1.2 Received 1024 bytes from 10.1.1.1 UdpEchoClientApplication:HandleRead(0x6241e0, 0x624a20) UdpEchoClientApplication:HandleRead(): Received 1024 bytes from 10.1.1.2 UdpEchoClientApplication:StopApplication() UdpEchoClientApplication:DoDispose() UdpEchoClientApplication:~UdpEchoClient() .ft P .fi .UNINDENT .UNINDENT .sp You can now see all of the messages coming from the UDP echo client application are identified as such. The message “Received 1024 bytes from 10.1.1.2” is now clearly identified as coming from the echo client application. The remaining message must be coming from the UDP echo server application. We can enable that component by entering a colon separated list of components in the NS_LOG environment variable. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ export \(aqNS_LOG=UdpEchoClientApplication=level_all|prefix_func: UdpEchoServerApplication=level_all|prefix_func\(aq .ft P .fi .UNINDENT .UNINDENT .sp Warning: You will need to remove the newline after the \fB:\fP in the example text above which is only there for document formatting purposes. .sp Now, if you run the script you will see all of the log messages from both the echo client and server applications. You may see that this can be very useful in debugging problems. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Waf: Entering directory \(ga/home/craigdo/repos/ns\-3\-allinone/ns\-3\-dev/build\(aq Waf: Leaving directory \(ga/home/craigdo/repos/ns\-3\-allinone/ns\-3\-dev/build\(aq \(aqbuild\(aq finished successfully (0.406s) UdpEchoServerApplication:UdpEchoServer() UdpEchoClientApplication:UdpEchoClient() UdpEchoClientApplication:SetDataSize(1024) UdpEchoServerApplication:StartApplication() UdpEchoClientApplication:StartApplication() UdpEchoClientApplication:ScheduleTransmit() UdpEchoClientApplication:Send() UdpEchoClientApplication:Send(): Sent 1024 bytes to 10.1.1.2 UdpEchoServerApplication:HandleRead(): Received 1024 bytes from 10.1.1.1 UdpEchoServerApplication:HandleRead(): Echoing packet UdpEchoClientApplication:HandleRead(0x624920, 0x625160) UdpEchoClientApplication:HandleRead(): Received 1024 bytes from 10.1.1.2 UdpEchoServerApplication:StopApplication() UdpEchoClientApplication:StopApplication() UdpEchoClientApplication:DoDispose() UdpEchoServerApplication:DoDispose() UdpEchoClientApplication:~UdpEchoClient() UdpEchoServerApplication:~UdpEchoServer() .ft P .fi .UNINDENT .UNINDENT .sp It is also sometimes useful to be able to see the simulation time at which a log message is generated. You can do this by ORing in the prefix_time bit. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ export \(aqNS_LOG=UdpEchoClientApplication=level_all|prefix_func|prefix_time: UdpEchoServerApplication=level_all|prefix_func|prefix_time\(aq .ft P .fi .UNINDENT .UNINDENT .sp Again, you will have to remove the newline above. If you run the script now, you should see the following output: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Waf: Entering directory \(ga/home/craigdo/repos/ns\-3\-allinone/ns\-3\-dev/build\(aq Waf: Leaving directory \(ga/home/craigdo/repos/ns\-3\-allinone/ns\-3\-dev/build\(aq \(aqbuild\(aq finished successfully (0.418s) 0s UdpEchoServerApplication:UdpEchoServer() 0s UdpEchoClientApplication:UdpEchoClient() 0s UdpEchoClientApplication:SetDataSize(1024) 1s UdpEchoServerApplication:StartApplication() 2s UdpEchoClientApplication:StartApplication() 2s UdpEchoClientApplication:ScheduleTransmit() 2s UdpEchoClientApplication:Send() 2s UdpEchoClientApplication:Send(): Sent 1024 bytes to 10.1.1.2 2.00369s UdpEchoServerApplication:HandleRead(): Received 1024 bytes from 10.1.1.1 2.00369s UdpEchoServerApplication:HandleRead(): Echoing packet 2.00737s UdpEchoClientApplication:HandleRead(0x624290, 0x624ad0) 2.00737s UdpEchoClientApplication:HandleRead(): Received 1024 bytes from 10.1.1.2 10s UdpEchoServerApplication:StopApplication() 10s UdpEchoClientApplication:StopApplication() UdpEchoClientApplication:DoDispose() UdpEchoServerApplication:DoDispose() UdpEchoClientApplication:~UdpEchoClient() UdpEchoServerApplication:~UdpEchoServer() .ft P .fi .UNINDENT .UNINDENT .sp You can see that the constructor for the UdpEchoServer was called at a simulation time of 0 seconds. This is actually happening before the simulation starts, but the time is displayed as zero seconds. The same is true for the UdpEchoClient constructor message. .sp Recall that the \fBscratch/first.cc\fP script started the echo server application at one second into the simulation. You can now see that the \fBStartApplication\fP method of the server is, in fact, called at one second. You can also see that the echo client application is started at a simulation time of two seconds as we requested in the script. .sp You can now follow the progress of the simulation from the \fBScheduleTransmit\fP call in the client that calls \fBSend\fP to the \fBHandleRead\fP callback in the echo server application. Note that the elapsed time for the packet to be sent across the point\-to\-point link is 3.69 milliseconds. You see the echo server logging a message telling you that it has echoed the packet and then, after another channel delay, you see the echo client receive the echoed packet in its \fBHandleRead\fP method. .sp There is a lot that is happening under the covers in this simulation that you are not seeing as well. You can very easily follow the entire process by turning on all of the logging components in the system. Try setting the \fBNS_LOG\fP variable to the following, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ export \(aqNS_LOG=*=level_all|prefix_func|prefix_time\(aq .ft P .fi .UNINDENT .UNINDENT .sp The asterisk above is the logging component wildcard. This will turn on all of the logging in all of the components used in the simulation. I won’t reproduce the output here (as of this writing it produces 1265 lines of output for the single packet echo) but you can redirect this information into a file and look through it with your favorite editor if you like, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./waf \-\-run scratch/myfirst > log.out 2>&1 .ft P .fi .UNINDENT .UNINDENT .sp I personally use this extremely verbose version of logging when I am presented with a problem and I have no idea where things are going wrong. I can follow the progress of the code quite easily without having to set breakpoints and step through code in a debugger. I can just edit up the output in my favorite editor and search around for things I expect, and see things happening that I don’t expect. When I have a general idea about what is going wrong, I transition into a debugger for a fine\-grained examination of the problem. This kind of output can be especially useful when your script does something completely unexpected. If you are stepping using a debugger you may miss an unexpected excursion completely. Logging the excursion makes it quickly visible. .SS Adding Logging to your Code .sp You can add new logging to your simulations by making calls to the log component via several macros. Let’s do so in the \fBmyfirst.cc\fP script we have in the \fBscratch\fP directory. .sp Recall that we have defined a logging component in that script: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C NS_LOG_COMPONENT_DEFINE ("FirstScriptExample"); .ft P .fi .UNINDENT .UNINDENT .sp You now know that you can enable all of the logging for this component by setting the \fBNS_LOG\fP environment variable to the various levels. Let’s go ahead and add some logging to the script. The macro used to add an informational level log message is \fBNS_LOG_INFO\fP\&. Go ahead and add one (just before we start creating the nodes) that tells you that the script is “Creating Topology.” This is done as in this code snippet, .sp Open \fBscratch/myfirst.cc\fP in your favorite editor and add the line, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C NS_LOG_INFO ("Creating Topology"); .ft P .fi .UNINDENT .UNINDENT .sp right before the lines, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C NodeContainer nodes; nodes.Create (2); .ft P .fi .UNINDENT .UNINDENT .sp Now build the script using waf and clear the \fBNS_LOG\fP variable to turn off the torrent of logging we previously enabled: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./waf $ export NS_LOG= .ft P .fi .UNINDENT .UNINDENT .sp Now, if you run the script, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./waf \-\-run scratch/myfirst .ft P .fi .UNINDENT .UNINDENT .sp you will \fBnot\fP see your new message since its associated logging component (\fBFirstScriptExample\fP) has not been enabled. In order to see your message you will have to enable the \fBFirstScriptExample\fP logging component with a level greater than or equal to \fBNS_LOG_INFO\fP\&. If you just want to see this particular level of logging, you can enable it by, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ export NS_LOG=FirstScriptExample=info .ft P .fi .UNINDENT .UNINDENT .sp If you now run the script you will see your new “Creating Topology” log message, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Waf: Entering directory \(ga/home/craigdo/repos/ns\-3\-allinone/ns\-3\-dev/build\(aq Waf: Leaving directory \(ga/home/craigdo/repos/ns\-3\-allinone/ns\-3\-dev/build\(aq \(aqbuild\(aq finished successfully (0.404s) Creating Topology Sent 1024 bytes to 10.1.1.2 Received 1024 bytes from 10.1.1.1 Received 1024 bytes from 10.1.1.2 .ft P .fi .UNINDENT .UNINDENT .SS Using Command Line Arguments .SS Overriding Default Attributes .sp Another way you can change how \fIns\-3\fP scripts behave without editing and building is via \fIcommand line arguments.\fP We provide a mechanism to parse command line arguments and automatically set local and global variables based on those arguments. .sp The first step in using the command line argument system is to declare the command line parser. This is done quite simply (in your main program) as in the following code, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C int main (int argc, char *argv[]) { ... CommandLine cmd; cmd.Parse (argc, argv); ... } .ft P .fi .UNINDENT .UNINDENT .sp This simple two line snippet is actually very useful by itself. It opens the door to the \fIns\-3\fP global variable and \fBAttribute\fP systems. Go ahead and add that two lines of code to the \fBscratch/myfirst.cc\fP script at the start of \fBmain\fP\&. Go ahead and build the script and run it, but ask the script for help in the following way, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./waf \-\-run "scratch/myfirst \-\-PrintHelp" .ft P .fi .UNINDENT .UNINDENT .sp This will ask Waf to run the \fBscratch/myfirst\fP script and pass the command line argument \fB\-\-PrintHelp\fP to the script. The quotes are required to sort out which program gets which argument. The command line parser will now see the \fB\-\-PrintHelp\fP argument and respond with, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Waf: Entering directory \(ga/home/craigdo/repos/ns\-3\-allinone/ns\-3\-dev/build\(aq Waf: Leaving directory \(ga/home/craigdo/repos/ns\-3\-allinone/ns\-3\-dev/build\(aq \(aqbuild\(aq finished successfully (0.413s) TcpL4Protocol:TcpStateMachine() CommandLine:HandleArgument(): Handle arg name=PrintHelp value= \-\-PrintHelp: Print this help message. \-\-PrintGroups: Print the list of groups. \-\-PrintTypeIds: Print all TypeIds. \-\-PrintGroup=[group]: Print all TypeIds of group. \-\-PrintAttributes=[typeid]: Print all attributes of typeid. \-\-PrintGlobals: Print the list of globals. .ft P .fi .UNINDENT .UNINDENT .sp Let’s focus on the \fB\-\-PrintAttributes\fP option. We have already hinted at the \fIns\-3\fP \fBAttribute\fP system while walking through the \fBfirst.cc\fP script. We looked at the following lines of code, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C PointToPointHelper pointToPoint; pointToPoint.SetDeviceAttribute ("DataRate", StringValue ("5Mbps")); pointToPoint.SetChannelAttribute ("Delay", StringValue ("2ms")); .ft P .fi .UNINDENT .UNINDENT .sp and mentioned that \fBDataRate\fP was actually an \fBAttribute\fP of the \fBPointToPointNetDevice\fP\&. Let’s use the command line argument parser to take a look at the \fBAttributes\fP of the PointToPointNetDevice. The help listing says that we should provide a \fBTypeId\fP\&. This corresponds to the class name of the class to which the \fBAttributes\fP belong. In this case it will be \fBns3::PointToPointNetDevice\fP\&. Let’s go ahead and type in, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./waf \-\-run "scratch/myfirst \-\-PrintAttributes=ns3::PointToPointNetDevice" .ft P .fi .UNINDENT .UNINDENT .sp The system will print out all of the \fBAttributes\fP of this kind of net device. Among the \fBAttributes\fP you will see listed is, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C \-\-ns3::PointToPointNetDevice::DataRate=[32768bps]: The default data rate for point to point links .ft P .fi .UNINDENT .UNINDENT .sp This is the default value that will be used when a \fBPointToPointNetDevice\fP is created in the system. We overrode this default with the \fBAttribute\fP setting in the \fBPointToPointHelper\fP above. Let’s use the default values for the point\-to\-point devices and channels by deleting the \fBSetDeviceAttribute\fP call and the \fBSetChannelAttribute\fP call from the \fBmyfirst.cc\fP we have in the scratch directory. .sp Your script should now just declare the \fBPointToPointHelper\fP and not do any \fBset\fP operations as in the following example, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C \&... NodeContainer nodes; nodes.Create (2); PointToPointHelper pointToPoint; NetDeviceContainer devices; devices = pointToPoint.Install (nodes); \&... .ft P .fi .UNINDENT .UNINDENT .sp Go ahead and build the new script with Waf (\fB\&./waf\fP) and let’s go back and enable some logging from the UDP echo server application and turn on the time prefix. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ export \(aqNS_LOG=UdpEchoServerApplication=level_all|prefix_time\(aq .ft P .fi .UNINDENT .UNINDENT .sp If you run the script, you should now see the following output, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Waf: Entering directory \(ga/home/craigdo/repos/ns\-3\-allinone/ns\-3\-dev/build\(aq Waf: Leaving directory \(ga/home/craigdo/repos/ns\-3\-allinone/ns\-3\-dev/build\(aq \(aqbuild\(aq finished successfully (0.405s) 0s UdpEchoServerApplication:UdpEchoServer() 1s UdpEchoServerApplication:StartApplication() Sent 1024 bytes to 10.1.1.2 2.25732s Received 1024 bytes from 10.1.1.1 2.25732s Echoing packet Received 1024 bytes from 10.1.1.2 10s UdpEchoServerApplication:StopApplication() UdpEchoServerApplication:DoDispose() UdpEchoServerApplication:~UdpEchoServer() .ft P .fi .UNINDENT .UNINDENT .sp Recall that the last time we looked at the simulation time at which the packet was received by the echo server, it was at 2.00369 seconds. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C 2.00369s UdpEchoServerApplication:HandleRead(): Received 1024 bytes from 10.1.1.1 .ft P .fi .UNINDENT .UNINDENT .sp Now it is receiving the packet at 2.25732 seconds. This is because we just dropped the data rate of the \fBPointToPointNetDevice\fP down to its default of 32768 bits per second from five megabits per second. .sp If we were to provide a new \fBDataRate\fP using the command line, we could speed our simulation up again. We do this in the following way, according to the formula implied by the help item: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./waf \-\-run "scratch/myfirst \-\-ns3::PointToPointNetDevice::DataRate=5Mbps" .ft P .fi .UNINDENT .UNINDENT .sp This will set the default value of the \fBDataRate\fP \fBAttribute\fP back to five megabits per second. Are you surprised by the result? It turns out that in order to get the original behavior of the script back, we will have to set the speed\-of\-light delay of the channel as well. We can ask the command line system to print out the \fBAttributes\fP of the channel just like we did for the net device: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./waf \-\-run "scratch/myfirst \-\-PrintAttributes=ns3::PointToPointChannel" .ft P .fi .UNINDENT .UNINDENT .sp We discover the \fBDelay\fP \fBAttribute\fP of the channel is set in the following way: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C \-\-ns3::PointToPointChannel::Delay=[0ns]: Transmission delay through the channel .ft P .fi .UNINDENT .UNINDENT .sp We can then set both of these default values through the command line system, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./waf \-\-run "scratch/myfirst \-\-ns3::PointToPointNetDevice::DataRate=5Mbps \-\-ns3::PointToPointChannel::Delay=2ms" .ft P .fi .UNINDENT .UNINDENT .sp in which case we recover the timing we had when we explicitly set the \fBDataRate\fP and \fBDelay\fP in the script: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Waf: Entering directory \(ga/home/craigdo/repos/ns\-3\-allinone/ns\-3\-dev/build\(aq Waf: Leaving directory \(ga/home/craigdo/repos/ns\-3\-allinone/ns\-3\-dev/build\(aq \(aqbuild\(aq finished successfully (0.417s) 0s UdpEchoServerApplication:UdpEchoServer() 1s UdpEchoServerApplication:StartApplication() Sent 1024 bytes to 10.1.1.2 2.00369s Received 1024 bytes from 10.1.1.1 2.00369s Echoing packet Received 1024 bytes from 10.1.1.2 10s UdpEchoServerApplication:StopApplication() UdpEchoServerApplication:DoDispose() UdpEchoServerApplication:~UdpEchoServer() .ft P .fi .UNINDENT .UNINDENT .sp Note that the packet is again received by the server at 2.00369 seconds. We could actually set any of the \fBAttributes\fP used in the script in this way. In particular we could set the \fBUdpEchoClient Attribute MaxPackets\fP to some other value than one. .sp How would you go about that? Give it a try. Remember you have to comment out the place we override the default \fBAttribute\fP and explicitly set \fBMaxPackets\fP in the script. Then you have to rebuild the script. You will also have to find the syntax for actually setting the new default attribute value using the command line help facility. Once you have this figured out you should be able to control the number of packets echoed from the command line. Since we’re nice folks, we’ll tell you that your command line should end up looking something like, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./waf \-\-run "scratch/myfirst \-\-ns3::PointToPointNetDevice::DataRate=5Mbps \-\-ns3::PointToPointChannel::Delay=2ms \-\-ns3::UdpEchoClient::MaxPackets=2" .ft P .fi .UNINDENT .UNINDENT .sp A natural question to arise at this point is how to learn about the existence of all of these attributes. Again, the command line help facility has a feature for this. If we ask for command line help we should see: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./waf \-\-run "scratch/myfirst \-\-PrintHelp" myfirst [Program Arguments] [General Arguments] General Arguments: \-\-PrintGlobals: Print the list of globals. \-\-PrintGroups: Print the list of groups. \-\-PrintGroup=[group]: Print all TypeIds of group. \-\-PrintTypeIds: Print all TypeIds. \-\-PrintAttributes=[typeid]: Print all attributes of typeid. \-\-PrintHelp: Print this help message. .ft P .fi .UNINDENT .UNINDENT .sp If you select the “PrintGroups” argument, you should see a list of all registered TypeId groups. The group names are aligned with the module names in the source directory (although with a leading capital letter). Printing out all of the information at once would be too much, so a further filter is available to print information on a per\-group basis. So, focusing again on the point\-to\-point module: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C \&./waf \-\-run "scratch/myfirst \-\-PrintGroup=PointToPoint" TypeIds in group PointToPoint: ns3::PointToPointChannel ns3::PointToPointNetDevice ns3::PointToPointRemoteChannel ns3::PppHeader .ft P .fi .UNINDENT .UNINDENT .sp and from here, one can find the possible TypeId names to search for attributes, such as in the \fB\-\-PrintAttributes=ns3::PointToPointChannel\fP example shown above. .sp Another way to find out about attributes is through the ns\-3 Doxygen; there is a page that lists out all of the registered attributes in the simulator. .SS Hooking Your Own Values .sp You can also add your own hooks to the command line system. This is done quite simply by using the \fBAddValue\fP method to the command line parser. .sp Let’s use this facility to specify the number of packets to echo in a completely different way. Let’s add a local variable called \fBnPackets\fP to the \fBmain\fP function. We’ll initialize it to one to match our previous default behavior. To allow the command line parser to change this value, we need to hook the value into the parser. We do this by adding a call to \fBAddValue\fP\&. Go ahead and change the \fBscratch/myfirst.cc\fP script to start with the following code, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C 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); ... .ft P .fi .UNINDENT .UNINDENT .sp Scroll down to the point in the script where we set the \fBMaxPackets\fP \fBAttribute\fP and change it so that it is set to the variable \fBnPackets\fP instead of the constant \fB1\fP as is shown below. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C echoClient.SetAttribute ("MaxPackets", UintegerValue (nPackets)); .ft P .fi .UNINDENT .UNINDENT .sp Now if you run the script and provide the \fB\-\-PrintHelp\fP argument, you should see your new \fBUser Argument\fP listed in the help display. .sp Try, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./waf \-\-run "scratch/myfirst \-\-PrintHelp" .ft P .fi .UNINDENT .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Waf: Entering directory \(ga/home/craigdo/repos/ns\-3\-allinone/ns\-3\-dev/build\(aq Waf: Leaving directory \(ga/home/craigdo/repos/ns\-3\-allinone/ns\-3\-dev/build\(aq \(aqbuild\(aq finished successfully (0.403s) \-\-PrintHelp: Print this help message. \-\-PrintGroups: Print the list of groups. \-\-PrintTypeIds: Print all TypeIds. \-\-PrintGroup=[group]: Print all TypeIds of group. \-\-PrintAttributes=[typeid]: Print all attributes of typeid. \-\-PrintGlobals: Print the list of globals. User Arguments: \-\-nPackets: Number of packets to echo .ft P .fi .UNINDENT .UNINDENT .sp If you want to specify the number of packets to echo, you can now do so by setting the \fB\-\-nPackets\fP argument in the command line, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./waf \-\-run "scratch/myfirst \-\-nPackets=2" .ft P .fi .UNINDENT .UNINDENT .sp You should now see .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Waf: Entering directory \(ga/home/craigdo/repos/ns\-3\-allinone/ns\-3\-dev/build\(aq Waf: Leaving directory \(ga/home/craigdo/repos/ns\-3\-allinone/ns\-3\-dev/build\(aq \(aqbuild\(aq finished successfully (0.404s) 0s UdpEchoServerApplication:UdpEchoServer() 1s UdpEchoServerApplication:StartApplication() Sent 1024 bytes to 10.1.1.2 2.25732s Received 1024 bytes from 10.1.1.1 2.25732s Echoing packet Received 1024 bytes from 10.1.1.2 Sent 1024 bytes to 10.1.1.2 3.25732s Received 1024 bytes from 10.1.1.1 3.25732s Echoing packet Received 1024 bytes from 10.1.1.2 10s UdpEchoServerApplication:StopApplication() UdpEchoServerApplication:DoDispose() UdpEchoServerApplication:~UdpEchoServer() .ft P .fi .UNINDENT .UNINDENT .sp You have now echoed two packets. Pretty easy, isn’t it? .sp You can see that if you are an \fIns\-3\fP user, you can use the command line argument system to control global values and \fBAttributes\fP\&. If you are a model author, you can add new \fBAttributes\fP to your \fBObjects\fP and they will automatically be available for setting by your users through the command line system. If you are a script author, you can add new variables to your scripts and hook them into the command line system quite painlessly. .SS Using the Tracing System .sp The whole point of simulation is to generate output for further study, and the \fIns\-3\fP tracing system is a primary mechanism for this. Since \fIns\-3\fP is a C++ program, standard facilities for generating output from C++ programs could be used: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C #include \&... int main () { ... std::cout << "The value of x is " << x << std::endl; ... } .ft P .fi .UNINDENT .UNINDENT .sp You could even use the logging module to add a little structure to your solution. There are many well\-known problems generated by such approaches and so we have provided a generic event tracing subsystem to address the issues we thought were important. .sp The basic goals of the \fIns\-3\fP tracing system are: .INDENT 0.0 .IP \(bu 2 For basic tasks, the tracing system should allow the user to generate standard tracing for popular tracing sources, and to customize which objects generate the tracing; .IP \(bu 2 Intermediate users must be able to extend the tracing system to modify the output format generated, or to insert new tracing sources, without modifying the core of the simulator; .IP \(bu 2 Advanced users can modify the simulator core to add new tracing sources and sinks. .UNINDENT .sp The \fIns\-3\fP tracing system is built on the concepts of independent tracing sources and tracing sinks, and a uniform mechanism for connecting sources to sinks. Trace sources are entities that can signal events that happen in a simulation and provide access to interesting underlying data. For example, a trace source could indicate when a packet is received by a net device and provide access to the packet contents for interested trace sinks. .sp Trace sources are not useful by themselves, they must be “connected” to other pieces of code that actually do something useful with the information provided by the sink. Trace sinks are consumers of the events and data provided by the trace sources. For example, one could create a trace sink that would (when connected to the trace source of the previous example) print out interesting parts of the received packet. .sp The rationale for this explicit division is to allow users to attach new types of sinks to existing tracing sources, without requiring editing and recompilation of the core of the simulator. Thus, in the example above, a user could define a new tracing sink in her script and attach it to an existing tracing source defined in the simulation core by editing only the user script. .sp In this tutorial, we will walk through some pre\-defined sources and sinks and show how they may be customized with little user effort. See the ns\-3 manual or how\-to sections for information on advanced tracing configuration including extending the tracing namespace and creating new tracing sources. .SS ASCII Tracing .sp \fIns\-3\fP provides helper functionality that wraps the low\-level tracing system to help you with the details involved in configuring some easily understood packet traces. If you enable this functionality, you will see output in a ASCII files — thus the name. For those familiar with \fIns\-2\fP output, this type of trace is analogous to the \fBout.tr\fP generated by many scripts. .sp Let’s just jump right in and add some ASCII tracing output to our \fBscratch/myfirst.cc\fP script. Right before the call to \fBSimulator::Run ()\fP, add the following lines of code: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C AsciiTraceHelper ascii; pointToPoint.EnableAsciiAll (ascii.CreateFileStream ("myfirst.tr")); .ft P .fi .UNINDENT .UNINDENT .sp Like in many other \fIns\-3\fP idioms, this code uses a helper object to help create ASCII traces. The second line contains two nested method calls. The “inside” method, \fBCreateFileStream()\fP uses an unnamed object idiom to create a file stream object on the stack (without an object name) and pass it down to the called method. We’ll go into this more in the future, but all you have to know at this point is that you are creating an object representing a file named “myfirst.tr” and passing it into \fBns\-3\fP\&. You are telling \fBns\-3\fP to deal with the lifetime issues of the created object and also to deal with problems caused by a little\-known (intentional) limitation of C++ ofstream objects relating to copy constructors. .sp The outside call, to \fBEnableAsciiAll()\fP, tells the helper that you want to enable ASCII tracing on all point\-to\-point devices in your simulation; and you want the (provided) trace sinks to write out information about packet movement in ASCII format. .sp For those familiar with \fIns\-2\fP, the traced events are equivalent to the popular trace points that log “+”, “\-”, “d”, and “r” events. .sp You can now build the script and run it from the command line: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./waf \-\-run scratch/myfirst .ft P .fi .UNINDENT .UNINDENT .sp Just as you have seen many times before, you will see some messages from Waf and then “‘build’ finished successfully” with some number of messages from the running program. .sp When it ran, the program will have created a file named \fBmyfirst.tr\fP\&. Because of the way that Waf works, the file is not created in the local directory, it is created at the top\-level directory of the repository by default. If you want to control where the traces are saved you can use the \fB\-\-cwd\fP option of Waf to specify this. We have not done so, thus we need to change into the top level directory of our repo and take a look at the ASCII trace file \fBmyfirst.tr\fP in your favorite editor. .SS Parsing Ascii Traces .sp There’s a lot of information there in a pretty dense form, but the first thing to notice is that there are a number of distinct lines in this file. It may be difficult to see this clearly unless you widen your window considerably. .sp Each line in the file corresponds to a \fItrace event\fP\&. In this case we are tracing events on the \fItransmit queue\fP present in every point\-to\-point net device in the simulation. The transmit queue is a queue through which every packet destined for a point\-to\-point channel must pass. Note that each line in the trace file begins with a lone character (has a space after it). This character will have the following meaning: .INDENT 0.0 .IP \(bu 2 \fB+\fP: An enqueue operation occurred on the device queue; .IP \(bu 2 \fB\-\fP: A dequeue operation occurred on the device queue; .IP \(bu 2 \fBd\fP: A packet was dropped, typically because the queue was full; .IP \(bu 2 \fBr\fP: A packet was received by the net device. .UNINDENT .sp Let’s take a more detailed view of the first line in the trace file. I’ll break it down into sections (indented for clarity) with a reference number on the left side: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C + 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) .ft P .fi .UNINDENT .UNINDENT .sp The first section of this expanded trace event (reference number 0) is the operation. We have a \fB+\fP character, so this corresponds to an \fIenqueue\fP operation on the transmit queue. The second section (reference 1) is the simulation time expressed in seconds. You may recall that we asked the \fBUdpEchoClientApplication\fP to start sending packets at two seconds. Here we see confirmation that this is, indeed, happening. .sp The next section of the example trace (reference 2) tell us which trace source originated this event (expressed in the tracing namespace). You can think of the tracing namespace somewhat like you would a filesystem namespace. The root of the namespace is the \fBNodeList\fP\&. This corresponds to a container managed in the \fIns\-3\fP core code that contains all of the nodes that are created in a script. Just as a filesystem may have directories under the root, we may have node numbers in the \fBNodeList\fP\&. The string \fB/NodeList/0\fP therefore refers to the zeroth node in the \fBNodeList\fP which we typically think of as “node 0”. In each node there is a list of devices that have been installed. This list appears next in the namespace. You can see that this trace event comes from \fBDeviceList/0\fP which is the zeroth device installed in the node. .sp The next string, \fB$ns3::PointToPointNetDevice\fP tells you what kind of device is in the zeroth position of the device list for node zero. Recall that the operation \fB+\fP found at reference 00 meant that an enqueue operation happened on the transmit queue of the device. This is reflected in the final segments of the “trace path” which are \fBTxQueue/Enqueue\fP\&. .sp The remaining sections in the trace should be fairly intuitive. References 3\-4 indicate that the packet is encapsulated in the point\-to\-point protocol. References 5\-7 show that the packet has an IP version four header and has originated from IP address 10.1.1.1 and is destined for 10.1.1.2. References 8\-9 show that this packet has a UDP header and, finally, reference 10 shows that the payload is the expected 1024 bytes. .sp The next line in the trace file shows the same packet being dequeued from the transmit queue on the same node. .sp The Third line in the trace file shows the packet being received by the net device on the node with the echo server. I have reproduced that event below. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C r 2.25732 /NodeList/1/DeviceList/0/$ns3::PointToPointNetDevice/MacRx 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) .ft P .fi .UNINDENT .UNINDENT .sp Notice that the trace operation is now \fBr\fP and the simulation time has increased to 2.25732 seconds. If you have been following the tutorial steps closely this means that you have left the \fBDataRate\fP of the net devices and the channel \fBDelay\fP set to their default values. This time should be familiar as you have seen it before in a previous section. .sp The trace source namespace entry (reference 02) has changed to reflect that this event is coming from node 1 (\fB/NodeList/1\fP) and the packet reception trace source (\fB/MacRx\fP). It should be quite easy for you to follow the progress of the packet through the topology by looking at the rest of the traces in the file. .SS PCAP Tracing .sp The \fIns\-3\fP device helpers can also be used to create trace files in the \fB\&.pcap\fP format. The acronym pcap (usually written in lower case) stands for packet capture, and is actually an API that includes the definition of a \fB\&.pcap\fP file format. The most popular program that can read and display this format is Wireshark (formerly called Ethereal). However, there are many traffic trace analyzers that use this packet format. We encourage users to exploit the many tools available for analyzing pcap traces. In this tutorial, we concentrate on viewing pcap traces with tcpdump. .sp The code used to enable pcap tracing is a one\-liner. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C pointToPoint.EnablePcapAll ("myfirst"); .ft P .fi .UNINDENT .UNINDENT .sp Go ahead and insert this line of code after the ASCII tracing code we just added to \fBscratch/myfirst.cc\fP\&. Notice that we only passed the string “myfirst,” and not “myfirst.pcap” or something similar. This is because the parameter is a prefix, not a complete file name. The helper will actually create a trace file for every point\-to\-point device in the simulation. The file names will be built using the prefix, the node number, the device number and a “.pcap” suffix. .sp In our example script, we will eventually see files named “myfirst\-0\-0.pcap” and “myfirst\-1\-0.pcap” which are the pcap traces for node 0\-device 0 and node 1\-device 0, respectively. .sp Once you have added the line of code to enable pcap tracing, you can run the script in the usual way: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./waf \-\-run scratch/myfirst .ft P .fi .UNINDENT .UNINDENT .sp If you look at the top level directory of your distribution, you should now see three log files: \fBmyfirst.tr\fP is the ASCII trace file we have previously examined. \fBmyfirst\-0\-0.pcap\fP and \fBmyfirst\-1\-0.pcap\fP are the new pcap files we just generated. .SS Reading output with tcpdump .sp The easiest thing to do at this point will be to use \fBtcpdump\fP to look at the \fBpcap\fP files. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ 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 .ft P .fi .UNINDENT .UNINDENT .sp You can see in the dump of \fBmyfirst\-0\-0.pcap\fP (the client device) that the echo packet is sent at 2 seconds into the simulation. If you look at the second dump (\fBmyfirst\-1\-0.pcap\fP) you can see that packet being received at 2.257324 seconds. You see the packet being echoed back at 2.257324 seconds in the second dump, and finally, you see the packet being received back at the client in the first dump at 2.514648 seconds. .SS Reading output with Wireshark .sp If you are unfamiliar with Wireshark, there is a web site available from which you can download programs and documentation: \fI\%http://www.wireshark.org/\fP\&. .sp Wireshark is a graphical user interface which can be used for displaying these trace files. If you have Wireshark available, you can open each of the trace files and display the contents as if you had captured the packets using a \fIpacket sniffer\fP\&. .SH BUILDING TOPOLOGIES .SS Building a Bus Network Topology .sp In this section we are going to expand our mastery of \fIns\-3\fP network devices and channels to cover an example of a bus network. \fIns\-3\fP provides a net device and channel we call CSMA (Carrier Sense Multiple Access). .sp The \fIns\-3\fP CSMA device models a simple network in the spirit of Ethernet. A real Ethernet uses CSMA/CD (Carrier Sense Multiple Access with Collision Detection) scheme with exponentially increasing backoff to contend for the shared transmission medium. The \fIns\-3\fP CSMA device and channel models only a subset of this. .sp Just as we have seen point\-to\-point topology helper objects when constructing point\-to\-point topologies, we will see equivalent CSMA topology helpers in this section. The appearance and operation of these helpers should look quite familiar to you. .sp We provide an example script in our \fBexamples/tutorial\fP directory. This script builds on the \fBfirst.cc\fP script and adds a CSMA network to the point\-to\-point simulation we’ve already considered. Go ahead and open \fBexamples/tutorial/second.cc\fP in your favorite editor. You will have already seen enough \fIns\-3\fP code to understand most of what is going on in this example, but we will go over the entire script and examine some of the output. .sp Just as in the \fBfirst.cc\fP example (and in all ns\-3 examples) the file begins with an emacs mode line and some GPL boilerplate. .sp The actual code begins by loading module include files just as was done in the \fBfirst.cc\fP example. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C #include "ns3/core\-module.h" #include "ns3/network\-module.h" #include "ns3/csma\-module.h" #include "ns3/internet\-module.h" #include "ns3/point\-to\-point\-module.h" #include "ns3/applications\-module.h" #include "ns3/ipv4\-global\-routing\-helper.h" .ft P .fi .UNINDENT .UNINDENT .sp One thing that can be surprisingly useful is a small bit of ASCII art that shows a cartoon of the network topology constructed in the example. You will find a similar “drawing” in most of our examples. .sp In this case, you can see that we are going to extend our point\-to\-point example (the link between the nodes n0 and n1 below) by hanging a bus network off of the right side. Notice that this is the default network topology since you can actually vary the number of nodes created on the LAN. If you set nCsma to one, there will be a total of two nodes on the LAN (CSMA channel) — one required node and one “extra” node. By default there are three “extra” nodes as seen below: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C // Default Network Topology // // 10.1.1.0 // n0 \-\-\-\-\-\-\-\-\-\-\-\-\-\- n1 n2 n3 n4 // point\-to\-point | | | | // ================ // LAN 10.1.2.0 .ft P .fi .UNINDENT .UNINDENT .sp Then the ns\-3 namespace is \fBused\fP and a logging component is defined. This is all just as it was in \fBfirst.cc\fP, so there is nothing new yet. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C using namespace ns3; NS_LOG_COMPONENT_DEFINE ("SecondScriptExample"); .ft P .fi .UNINDENT .UNINDENT .sp The main program begins with a slightly different twist. We use a verbose flag to determine whether or not the \fBUdpEchoClientApplication\fP and \fBUdpEchoServerApplication\fP logging components are enabled. This flag defaults to true (the logging components are enabled) but allows us to turn off logging during regression testing of this example. .sp You will see some familiar code that will allow you to change the number of devices on the CSMA network via command line argument. We did something similar when we allowed the number of packets sent to be changed in the section on command line arguments. The last line makes sure you have at least one “extra” node. .sp The code consists of variations of previously covered API so you should be entirely comfortable with the following code at this point in the tutorial. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C bool verbose = true; uint32_t nCsma = 3; CommandLine cmd; cmd.AddValue ("nCsma", "Number of \e"extra\e" CSMA nodes/devices", nCsma); cmd.AddValue ("verbose", "Tell echo applications to log if true", verbose); cmd.Parse (argc, argv); if (verbose) { LogComponentEnable("UdpEchoClientApplication", LOG_LEVEL_INFO); LogComponentEnable("UdpEchoServerApplication", LOG_LEVEL_INFO); } nCsma = nCsma == 0 ? 1 : nCsma; .ft P .fi .UNINDENT .UNINDENT .sp The next step is to create two nodes that we will connect via the point\-to\-point link. The \fBNodeContainer\fP is used to do this just as was done in \fBfirst.cc\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C NodeContainer p2pNodes; p2pNodes.Create (2); .ft P .fi .UNINDENT .UNINDENT .sp Next, we declare another \fBNodeContainer\fP to hold the nodes that will be part of the bus (CSMA) network. First, we just instantiate the container object itself. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C NodeContainer csmaNodes; csmaNodes.Add (p2pNodes.Get (1)); csmaNodes.Create (nCsma); .ft P .fi .UNINDENT .UNINDENT .sp The next line of code \fBGets\fP the first node (as in having an index of one) from the point\-to\-point node container and adds it to the container of nodes that will get CSMA devices. The node in question is going to end up with a point\-to\-point device \fIand\fP a CSMA device. We then create a number of “extra” nodes that compose the remainder of the CSMA network. Since we already have one node in the CSMA network – the one that will have both a point\-to\-point and CSMA net device, the number of “extra” nodes means the number nodes you desire in the CSMA section minus one. .sp The next bit of code should be quite familiar by now. We instantiate a \fBPointToPointHelper\fP and set the associated default \fBAttributes\fP so that we create a five megabit per second transmitter on devices created using the helper and a two millisecond delay on channels created by the helper. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C PointToPointHelper pointToPoint; pointToPoint.SetDeviceAttribute ("DataRate", StringValue ("5Mbps")); pointToPoint.SetChannelAttribute ("Delay", StringValue ("2ms")); NetDeviceContainer p2pDevices; p2pDevices = pointToPoint.Install (p2pNodes); .ft P .fi .UNINDENT .UNINDENT .sp We then instantiate a \fBNetDeviceContainer\fP to keep track of the point\-to\-point net devices and we \fBInstall\fP devices on the point\-to\-point nodes. .sp We mentioned above that you were going to see a helper for CSMA devices and channels, and the next lines introduce them. The \fBCsmaHelper\fP works just like a \fBPointToPointHelper\fP, but it creates and connects CSMA devices and channels. In the case of a CSMA device and channel pair, notice that the data rate is specified by a \fIchannel\fP \fBAttribute\fP instead of a device \fBAttribute\fP\&. This is because a real CSMA network does not allow one to mix, for example, 10Base\-T and 100Base\-T devices on a given channel. We first set the data rate to 100 megabits per second, and then set the speed\-of\-light delay of the channel to 6560 nano\-seconds (arbitrarily chosen as 1 nanosecond per foot over a 2000 meter segment). Notice that you can set an \fBAttribute\fP using its native data type. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C CsmaHelper csma; csma.SetChannelAttribute ("DataRate", StringValue ("100Mbps")); csma.SetChannelAttribute ("Delay", TimeValue (NanoSeconds (6560))); NetDeviceContainer csmaDevices; csmaDevices = csma.Install (csmaNodes); .ft P .fi .UNINDENT .UNINDENT .sp Just as we created a \fBNetDeviceContainer\fP to hold the devices created by the \fBPointToPointHelper\fP we create a \fBNetDeviceContainer\fP to hold the devices created by our \fBCsmaHelper\fP\&. We call the \fBInstall\fP method of the \fBCsmaHelper\fP to install the devices into the nodes of the \fBcsmaNodes NodeContainer\fP\&. .sp We now have our nodes, devices and channels created, but we have no protocol stacks present. Just as in the \fBfirst.cc\fP script, we will use the \fBInternetStackHelper\fP to install these stacks. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C InternetStackHelper stack; stack.Install (p2pNodes.Get (0)); stack.Install (csmaNodes); .ft P .fi .UNINDENT .UNINDENT .sp Recall that we took one of the nodes from the \fBp2pNodes\fP container and added it to the \fBcsmaNodes\fP container. Thus we only need to install the stacks on the remaining \fBp2pNodes\fP node, and all of the nodes in the \fBcsmaNodes\fP container to cover all of the nodes in the simulation. .sp Just as in the \fBfirst.cc\fP example script, we are going to use the \fBIpv4AddressHelper\fP to assign IP addresses to our device interfaces. First we use the network 10.1.1.0 to create the two addresses needed for our two point\-to\-point devices. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Ipv4AddressHelper address; address.SetBase ("10.1.1.0", "255.255.255.0"); Ipv4InterfaceContainer p2pInterfaces; p2pInterfaces = address.Assign (p2pDevices); .ft P .fi .UNINDENT .UNINDENT .sp Recall that we save the created interfaces in a container to make it easy to pull out addressing information later for use in setting up the applications. .sp We now need to assign IP addresses to our CSMA device interfaces. The operation works just as it did for the point\-to\-point case, except we now are performing the operation on a container that has a variable number of CSMA devices — remember we made the number of CSMA devices changeable by command line argument. The CSMA devices will be associated with IP addresses from network number 10.1.2.0 in this case, as seen below. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C address.SetBase ("10.1.2.0", "255.255.255.0"); Ipv4InterfaceContainer csmaInterfaces; csmaInterfaces = address.Assign (csmaDevices); .ft P .fi .UNINDENT .UNINDENT .sp Now we have a topology built, but we need applications. This section is going to be fundamentally similar to the applications section of \fBfirst.cc\fP but we are going to instantiate the server on one of the nodes that has a CSMA device and the client on the node having only a point\-to\-point device. .sp First, we set up the echo server. We create a \fBUdpEchoServerHelper\fP and provide a required \fBAttribute\fP value to the constructor which is the server port number. Recall that this port can be changed later using the \fBSetAttribute\fP method if desired, but we require it to be provided to the constructor. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C UdpEchoServerHelper echoServer (9); ApplicationContainer serverApps = echoServer.Install (csmaNodes.Get (nCsma)); serverApps.Start (Seconds (1.0)); serverApps.Stop (Seconds (10.0)); .ft P .fi .UNINDENT .UNINDENT .sp Recall that the \fBcsmaNodes NodeContainer\fP contains one of the nodes created for the point\-to\-point network and \fBnCsma\fP “extra” nodes. What we want to get at is the last of the “extra” nodes. The zeroth entry of the \fBcsmaNodes\fP container will be the point\-to\-point node. The easy way to think of this, then, is if we create one “extra” CSMA node, then it will be at index one of the \fBcsmaNodes\fP container. By induction, if we create \fBnCsma\fP “extra” nodes the last one will be at index \fBnCsma\fP\&. You see this exhibited in the \fBGet\fP of the first line of code. .sp The client application is set up exactly as we did in the \fBfirst.cc\fP example script. Again, we provide required \fBAttributes\fP to the \fBUdpEchoClientHelper\fP in the constructor (in this case the remote address and port). We tell the client to send packets to the server we just installed on the last of the “extra” CSMA nodes. We install the client on the leftmost point\-to\-point node seen in the topology illustration. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C UdpEchoClientHelper echoClient (csmaInterfaces.GetAddress (nCsma), 9); echoClient.SetAttribute ("MaxPackets", UintegerValue (1)); echoClient.SetAttribute ("Interval", TimeValue (Seconds (1.0))); echoClient.SetAttribute ("PacketSize", UintegerValue (1024)); ApplicationContainer clientApps = echoClient.Install (p2pNodes.Get (0)); clientApps.Start (Seconds (2.0)); clientApps.Stop (Seconds (10.0)); .ft P .fi .UNINDENT .UNINDENT .sp Since we have actually built an internetwork here, we need some form of internetwork routing. \fIns\-3\fP provides what we call global routing to help you out. Global routing takes advantage of the fact that the entire internetwork is accessible in the simulation and runs through the all of the nodes created for the simulation — it does the hard work of setting up routing for you without having to configure routers. .sp Basically, what happens is that each node behaves as if it were an OSPF router that communicates instantly and magically with all other routers behind the scenes. Each node generates link advertisements and communicates them directly to a global route manager which uses this global information to construct the routing tables for each node. Setting up this form of routing is a one\-liner: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Ipv4GlobalRoutingHelper::PopulateRoutingTables (); .ft P .fi .UNINDENT .UNINDENT .sp Next we enable pcap tracing. The first line of code to enable pcap tracing in the point\-to\-point helper should be familiar to you by now. The second line enables pcap tracing in the CSMA helper and there is an extra parameter you haven’t encountered yet. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C pointToPoint.EnablePcapAll ("second"); csma.EnablePcap ("second", csmaDevices.Get (1), true); .ft P .fi .UNINDENT .UNINDENT .sp The CSMA network is a multi\-point\-to\-point network. This means that there can (and are in this case) multiple endpoints on a shared medium. Each of these endpoints has a net device associated with it. There are two basic alternatives to gathering trace information from such a network. One way is to create a trace file for each net device and store only the packets that are emitted or consumed by that net device. Another way is to pick one of the devices and place it in promiscuous mode. That single device then “sniffs” the network for all packets and stores them in a single pcap file. This is how \fBtcpdump\fP, for example, works. That final parameter tells the CSMA helper whether or not to arrange to capture packets in promiscuous mode. .sp In this example, we are going to select one of the devices on the CSMA network and ask it to perform a promiscuous sniff of the network, thereby emulating what \fBtcpdump\fP would do. If you were on a Linux machine you might do something like \fBtcpdump \-i eth0\fP to get the trace. In this case, we specify the device using \fBcsmaDevices.Get(1)\fP, which selects the first device in the container. Setting the final parameter to true enables promiscuous captures. .sp The last section of code just runs and cleans up the simulation just like the \fBfirst.cc\fP example. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Simulator::Run (); Simulator::Destroy (); return 0; } .ft P .fi .UNINDENT .UNINDENT .sp In order to run this example, copy the \fBsecond.cc\fP example script into the scratch directory and use waf to build just as you did with the \fBfirst.cc\fP example. If you are in the top\-level directory of the repository you just type, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ cp examples/tutorial/second.cc scratch/mysecond.cc $ ./waf .ft P .fi .UNINDENT .UNINDENT .sp Warning: We use the file \fBsecond.cc\fP as one of our regression tests to verify that it works exactly as we think it should in order to make your tutorial experience a positive one. This means that an executable named \fBsecond\fP already exists in the project. To avoid any confusion about what you are executing, please do the renaming to \fBmysecond.cc\fP suggested above. .sp If you are following the tutorial religiously (you are, aren’t you) you will still have the NS_LOG variable set, so go ahead and clear that variable and run the program. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ export NS_LOG= $ ./waf \-\-run scratch/mysecond .ft P .fi .UNINDENT .UNINDENT .sp Since we have set up the UDP echo applications to log just as we did in \fBfirst.cc\fP, you will see similar output when you run the script. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Waf: Entering directory \(ga/home/craigdo/repos/ns\-3\-allinone/ns\-3\-dev/build\(aq Waf: Leaving directory \(ga/home/craigdo/repos/ns\-3\-allinone/ns\-3\-dev/build\(aq \(aqbuild\(aq finished successfully (0.415s) Sent 1024 bytes to 10.1.2.4 Received 1024 bytes from 10.1.1.1 Received 1024 bytes from 10.1.2.4 .ft P .fi .UNINDENT .UNINDENT .sp Recall that the first message, “\fBSent 1024 bytes to 10.1.2.4\fP,” is the UDP echo client sending a packet to the server. In this case, the server is on a different network (10.1.2.0). The second message, “\fBReceived 1024 bytes from 10.1.1.1\fP,” is from the UDP echo server, generated when it receives the echo packet. The final message, “\fBReceived 1024 bytes from 10.1.2.4\fP,” is from the echo client, indicating that it has received its echo back from the server. .sp If you now go and look in the top level directory, you will find three trace files: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C second\-0\-0.pcap second\-1\-0.pcap second\-2\-0.pcap .ft P .fi .UNINDENT .UNINDENT .sp Let’s take a moment to look at the naming of these files. They all have the same form, \fB\-\-.pcap\fP\&. For example, the first file in the listing is \fBsecond\-0\-0.pcap\fP which is the pcap trace from node zero, device zero. This is the point\-to\-point net device on node zero. The file \fBsecond\-1\-0.pcap\fP is the pcap trace for device zero on node one, also a point\-to\-point net device; and the file \fBsecond\-2\-0.pcap\fP is the pcap trace for device zero on node two. .sp If you refer back to the topology illustration at the start of the section, you will see that node zero is the leftmost node of the point\-to\-point link and node one is the node that has both a point\-to\-point device and a CSMA device. You will see that node two is the first “extra” node on the CSMA network and its device zero was selected as the device to capture the promiscuous\-mode trace. .sp Now, let’s follow the echo packet through the internetwork. First, do a tcpdump of the trace file for the leftmost point\-to\-point node — node zero. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ tcpdump \-nn \-tt \-r second\-0\-0.pcap .ft P .fi .UNINDENT .UNINDENT .sp You should see the contents of the pcap file displayed: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C reading from file second\-0\-0.pcap, link\-type PPP (PPP) 2.000000 IP 10.1.1.1.49153 > 10.1.2.4.9: UDP, length 1024 2.017607 IP 10.1.2.4.9 > 10.1.1.1.49153: UDP, length 1024 .ft P .fi .UNINDENT .UNINDENT .sp The first line of the dump indicates that the link type is PPP (point\-to\-point) which we expect. You then see the echo packet leaving node zero via the device associated with IP address 10.1.1.1 headed for IP address 10.1.2.4 (the rightmost CSMA node). This packet will move over the point\-to\-point link and be received by the point\-to\-point net device on node one. Let’s take a look: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ tcpdump \-nn \-tt \-r second\-1\-0.pcap .ft P .fi .UNINDENT .UNINDENT .sp You should now see the pcap trace output of the other side of the point\-to\-point link: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C reading from file second\-1\-0.pcap, link\-type PPP (PPP) 2.003686 IP 10.1.1.1.49153 > 10.1.2.4.9: UDP, length 1024 2.013921 IP 10.1.2.4.9 > 10.1.1.1.49153: UDP, length 1024 .ft P .fi .UNINDENT .UNINDENT .sp Here we see that the link type is also PPP as we would expect. You see the packet from IP address 10.1.1.1 (that was sent at 2.000000 seconds) headed toward IP address 10.1.2.4 appear on this interface. Now, internally to this node, the packet will be forwarded to the CSMA interface and we should see it pop out on that device headed for its ultimate destination. .sp Remember that we selected node 2 as the promiscuous sniffer node for the CSMA network so let’s then look at second\-2\-0.pcap and see if its there. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ tcpdump \-nn \-tt \-r second\-2\-0.pcap .ft P .fi .UNINDENT .UNINDENT .sp You should now see the promiscuous dump of node two, device zero: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C reading from file second\-2\-0.pcap, link\-type EN10MB (Ethernet) 2.007698 ARP, Request who\-has 10.1.2.4 (ff:ff:ff:ff:ff:ff) tell 10.1.2.1, length 50 2.007710 ARP, Reply 10.1.2.4 is\-at 00:00:00:00:00:06, length 50 2.007803 IP 10.1.1.1.49153 > 10.1.2.4.9: UDP, length 1024 2.013815 ARP, Request who\-has 10.1.2.1 (ff:ff:ff:ff:ff:ff) tell 10.1.2.4, length 50 2.013828 ARP, Reply 10.1.2.1 is\-at 00:00:00:00:00:03, length 50 2.013921 IP 10.1.2.4.9 > 10.1.1.1.49153: UDP, length 1024 .ft P .fi .UNINDENT .UNINDENT .sp As you can see, the link type is now “Ethernet”. Something new has appeared, though. The bus network needs \fBARP\fP, the Address Resolution Protocol. Node one knows it needs to send the packet to IP address 10.1.2.4, but it doesn’t know the MAC address of the corresponding node. It broadcasts on the CSMA network (ff:ff:ff:ff:ff:ff) asking for the device that has IP address 10.1.2.4. In this case, the rightmost node replies saying it is at MAC address 00:00:00:00:00:06. Note that node two is not directly involved in this exchange, but is sniffing the network and reporting all of the traffic it sees. .sp This exchange is seen in the following lines, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C 2.007698 ARP, Request who\-has 10.1.2.4 (ff:ff:ff:ff:ff:ff) tell 10.1.2.1, length 50 2.007710 ARP, Reply 10.1.2.4 is\-at 00:00:00:00:00:06, length 50 .ft P .fi .UNINDENT .UNINDENT .sp Then node one, device one goes ahead and sends the echo packet to the UDP echo server at IP address 10.1.2.4. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C 2.007803 IP 10.1.1.1.49153 > 10.1.2.4.9: UDP, length 1024 .ft P .fi .UNINDENT .UNINDENT .sp The server receives the echo request and turns the packet around trying to send it back to the source. The server knows that this address is on another network that it reaches via IP address 10.1.2.1. This is because we initialized global routing and it has figured all of this out for us. But, the echo server node doesn’t know the MAC address of the first CSMA node, so it has to ARP for it just like the first CSMA node had to do. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C 2.013815 ARP, Request who\-has 10.1.2.1 (ff:ff:ff:ff:ff:ff) tell 10.1.2.4, length 50 2.013828 ARP, Reply 10.1.2.1 is\-at 00:00:00:00:00:03, length 50 .ft P .fi .UNINDENT .UNINDENT .sp The server then sends the echo back to the forwarding node. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C 2.013921 IP 10.1.2.4.9 > 10.1.1.1.49153: UDP, length 1024 .ft P .fi .UNINDENT .UNINDENT .sp Looking back at the rightmost node of the point\-to\-point link, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ tcpdump \-nn \-tt \-r second\-1\-0.pcap .ft P .fi .UNINDENT .UNINDENT .sp You can now see the echoed packet coming back onto the point\-to\-point link as the last line of the trace dump. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C reading from file second\-1\-0.pcap, link\-type PPP (PPP) 2.003686 IP 10.1.1.1.49153 > 10.1.2.4.9: UDP, length 1024 2.013921 IP 10.1.2.4.9 > 10.1.1.1.49153: UDP, length 1024 .ft P .fi .UNINDENT .UNINDENT .sp Lastly, you can look back at the node that originated the echo .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ tcpdump \-nn \-tt \-r second\-0\-0.pcap .ft P .fi .UNINDENT .UNINDENT .sp and see that the echoed packet arrives back at the source at 2.017607 seconds, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C reading from file second\-0\-0.pcap, link\-type PPP (PPP) 2.000000 IP 10.1.1.1.49153 > 10.1.2.4.9: UDP, length 1024 2.017607 IP 10.1.2.4.9 > 10.1.1.1.49153: UDP, length 1024 .ft P .fi .UNINDENT .UNINDENT .sp Finally, recall that we added the ability to control the number of CSMA devices in the simulation by command line argument. You can change this argument in the same way as when we looked at changing the number of packets echoed in the \fBfirst.cc\fP example. Try running the program with the number of “extra” devices set to four: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./waf \-\-run "scratch/mysecond \-\-nCsma=4" .ft P .fi .UNINDENT .UNINDENT .sp You should now see, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Waf: Entering directory \(ga/home/craigdo/repos/ns\-3\-allinone/ns\-3\-dev/build\(aq Waf: Leaving directory \(ga/home/craigdo/repos/ns\-3\-allinone/ns\-3\-dev/build\(aq \(aqbuild\(aq finished successfully (0.405s) At time 2s client sent 1024 bytes to 10.1.2.5 port 9 At time 2.0118s server received 1024 bytes from 10.1.1.1 port 49153 At time 2.0118s server sent 1024 bytes to 10.1.1.1 port 49153 At time 2.02461s client received 1024 bytes from 10.1.2.5 port 9 .ft P .fi .UNINDENT .UNINDENT .sp Notice that the echo server has now been relocated to the last of the CSMA nodes, which is 10.1.2.5 instead of the default case, 10.1.2.4. .sp It is possible that you may not be satisfied with a trace file generated by a bystander in the CSMA network. You may really want to get a trace from a single device and you may not be interested in any other traffic on the network. You can do this fairly easily. .sp Let’s take a look at \fBscratch/mysecond.cc\fP and add that code enabling us to be more specific. \fBns\-3\fP helpers provide methods that take a node number and device number as parameters. Go ahead and replace the \fBEnablePcap\fP calls with the calls below. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C pointToPoint.EnablePcap ("second", p2pNodes.Get (0)\->GetId (), 0); csma.EnablePcap ("second", csmaNodes.Get (nCsma)\->GetId (), 0, false); csma.EnablePcap ("second", csmaNodes.Get (nCsma\-1)\->GetId (), 0, false); .ft P .fi .UNINDENT .UNINDENT .sp We know that we want to create a pcap file with the base name “second” and we also know that the device of interest in both cases is going to be zero, so those parameters are not really interesting. .sp In order to get the node number, you have two choices: first, nodes are numbered in a monotonically increasing fashion starting from zero in the order in which you created them. One way to get a node number is to figure this number out “manually” by contemplating the order of node creation. If you take a look at the network topology illustration at the beginning of the file, we did this for you and you can see that the last CSMA node is going to be node number \fBnCsma + 1\fP\&. This approach can become annoyingly difficult in larger simulations. .sp An alternate way, which we use here, is to realize that the \fBNodeContainers\fP contain pointers to \fIns\-3\fP \fBNode\fP Objects. The \fBNode\fP Object has a method called \fBGetId\fP which will return that node’s ID, which is the node number we seek. Let’s go take a look at the Doxygen for the \fBNode\fP and locate that method, which is further down in the \fIns\-3\fP core code than we’ve seen so far; but sometimes you have to search diligently for useful things. .sp Go to the Doxygen documentation for your release (recall that you can find it on the project web site). You can get to the \fBNode\fP documentation by looking through at the “Classes” tab and scrolling down the “Class List” until you find \fBns3::Node\fP\&. Select \fBns3::Node\fP and you will be taken to the documentation for the \fBNode\fP class. If you now scroll down to the \fBGetId\fP method and select it, you will be taken to the detailed documentation for the method. Using the \fBGetId\fP method can make determining node numbers much easier in complex topologies. .sp Let’s clear the old trace files out of the top\-level directory to avoid confusion about what is going on, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ rm *.pcap $ rm *.tr .ft P .fi .UNINDENT .UNINDENT .sp If you build the new script and run the simulation setting \fBnCsma\fP to 100, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./waf \-\-run "scratch/mysecond \-\-nCsma=100" .ft P .fi .UNINDENT .UNINDENT .sp you will see the following output: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Waf: Entering directory \(ga/home/craigdo/repos/ns\-3\-allinone/ns\-3\-dev/build\(aq Waf: Leaving directory \(ga/home/craigdo/repos/ns\-3\-allinone/ns\-3\-dev/build\(aq \(aqbuild\(aq finished successfully (0.407s) At time 2s client sent 1024 bytes to 10.1.2.101 port 9 At time 2.0068s server received 1024 bytes from 10.1.1.1 port 49153 At time 2.0068s server sent 1024 bytes to 10.1.1.1 port 49153 At time 2.01761s client received 1024 bytes from 10.1.2.101 port 9 .ft P .fi .UNINDENT .UNINDENT .sp Note that the echo server is now located at 10.1.2.101 which corresponds to having 100 “extra” CSMA nodes with the echo server on the last one. If you list the pcap files in the top level directory you will see, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C second\-0\-0.pcap second\-100\-0.pcap second\-101\-0.pcap .ft P .fi .UNINDENT .UNINDENT .sp The trace file \fBsecond\-0\-0.pcap\fP is the “leftmost” point\-to\-point device which is the echo packet source. The file \fBsecond\-101\-0.pcap\fP corresponds to the rightmost CSMA device which is where the echo server resides. You may have noticed that the final parameter on the call to enable pcap tracing on the echo server node was false. This means that the trace gathered on that node was in non\-promiscuous mode. .sp To illustrate the difference between promiscuous and non\-promiscuous traces, we also requested a non\-promiscuous trace for the next\-to\-last node. Go ahead and take a look at the \fBtcpdump\fP for \fBsecond\-100\-0.pcap\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ tcpdump \-nn \-tt \-r second\-100\-0.pcap .ft P .fi .UNINDENT .UNINDENT .sp You can now see that node 100 is really a bystander in the echo exchange. The only packets that it receives are the ARP requests which are broadcast to the entire CSMA network. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C reading from file second\-100\-0.pcap, link\-type EN10MB (Ethernet) 2.006698 ARP, Request who\-has 10.1.2.101 (ff:ff:ff:ff:ff:ff) tell 10.1.2.1, length 50 2.013815 ARP, Request who\-has 10.1.2.1 (ff:ff:ff:ff:ff:ff) tell 10.1.2.101, length 50 .ft P .fi .UNINDENT .UNINDENT .sp Now take a look at the \fBtcpdump\fP for \fBsecond\-101\-0.pcap\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ tcpdump \-nn \-tt \-r second\-101\-0.pcap .ft P .fi .UNINDENT .UNINDENT .sp You can now see that node 101 is really the participant in the echo exchange. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C reading from file second\-101\-0.pcap, link\-type EN10MB (Ethernet) 2.006698 ARP, Request who\-has 10.1.2.101 (ff:ff:ff:ff:ff:ff) tell 10.1.2.1, length 50 2.006698 ARP, Reply 10.1.2.101 is\-at 00:00:00:00:00:67, length 50 2.006803 IP 10.1.1.1.49153 > 10.1.2.101.9: UDP, length 1024 2.013803 ARP, Request who\-has 10.1.2.1 (ff:ff:ff:ff:ff:ff) tell 10.1.2.101, length 50 2.013828 ARP, Reply 10.1.2.1 is\-at 00:00:00:00:00:03, length 50 2.013828 IP 10.1.2.101.9 > 10.1.1.1.49153: UDP, length 1024 .ft P .fi .UNINDENT .UNINDENT .SS Models, Attributes and Reality .sp This is a convenient place to make a small excursion and make an important point. It may or may not be obvious to you, but whenever one is using a simulation, it is important to understand exactly what is being modeled and what is not. It is tempting, for example, to think of the CSMA devices and channels used in the previous section as if they were real Ethernet devices; and to expect a simulation result to directly reflect what will happen in a real Ethernet. This is not the case. .sp A model is, by definition, an abstraction of reality. It is ultimately the responsibility of the simulation script author to determine the so\-called “range of accuracy” and “domain of applicability” of the simulation as a whole, and therefore its constituent parts. .sp In some cases, like \fBCsma\fP, it can be fairly easy to determine what is \fInot\fP modeled. By reading the model description (\fBcsma.h\fP) you can find that there is no collision detection in the CSMA model and decide on how applicable its use will be in your simulation or what caveats you may want to include with your results. In other cases, it can be quite easy to configure behaviors that might not agree with any reality you can go out and buy. It will prove worthwhile to spend some time investigating a few such instances, and how easily you can swerve outside the bounds of reality in your simulations. .sp As you have seen, \fIns\-3\fP provides \fBAttributes\fP which a user can easily set to change model behavior. Consider two of the \fBAttributes\fP of the \fBCsmaNetDevice\fP: \fBMtu\fP and \fBEncapsulationMode\fP\&. The \fBMtu\fP attribute indicates the Maximum Transmission Unit to the device. This is the size of the largest Protocol Data Unit (PDU) that the device can send. .sp The MTU defaults to 1500 bytes in the \fBCsmaNetDevice\fP\&. This default corresponds to a number found in RFC 894, “A Standard for the Transmission of IP Datagrams over Ethernet Networks.” The number is actually derived from the maximum packet size for 10Base5 (full\-spec Ethernet) networks – 1518 bytes. If you subtract the DIX encapsulation overhead for Ethernet packets (18 bytes) you will end up with a maximum possible data size (MTU) of 1500 bytes. One can also find that the \fBMTU\fP for IEEE 802.3 networks is 1492 bytes. This is because LLC/SNAP encapsulation adds an extra eight bytes of overhead to the packet. In both cases, the underlying hardware can only send 1518 bytes, but the data size is different. .sp In order to set the encapsulation mode, the \fBCsmaNetDevice\fP provides an \fBAttribute\fP called \fBEncapsulationMode\fP which can take on the values \fBDix\fP or \fBLlc\fP\&. These correspond to Ethernet and LLC/SNAP framing respectively. .sp If one leaves the \fBMtu\fP at 1500 bytes and changes the encapsulation mode to \fBLlc\fP, the result will be a network that encapsulates 1500 byte PDUs with LLC/SNAP framing resulting in packets of 1526 bytes, which would be illegal in many networks, since they can transmit a maximum of 1518 bytes per packet. This would most likely result in a simulation that quite subtly does not reflect the reality you might be expecting. .sp Just to complicate the picture, there exist jumbo frames (1500 < MTU <= 9000 bytes) and super\-jumbo (MTU > 9000 bytes) frames that are not officially sanctioned by IEEE but are available in some high\-speed (Gigabit) networks and NICs. One could leave the encapsulation mode set to \fBDix\fP, and set the \fBMtu\fP \fBAttribute\fP on a \fBCsmaNetDevice\fP to 64000 bytes – even though an associated \fBCsmaChannel DataRate\fP was set at 10 megabits per second. This would essentially model an Ethernet switch made out of vampire\-tapped 1980s\-style 10Base5 networks that support super\-jumbo datagrams. This is certainly not something that was ever made, nor is likely to ever be made, but it is quite easy for you to configure. .sp In the previous example, you used the command line to create a simulation that had 100 \fBCsma\fP nodes. You could have just as easily created a simulation with 500 nodes. If you were actually modeling that 10Base5 vampire\-tap network, the maximum length of a full\-spec Ethernet cable is 500 meters, with a minimum tap spacing of 2.5 meters. That means there could only be 200 taps on a real network. You could have quite easily built an illegal network in that way as well. This may or may not result in a meaningful simulation depending on what you are trying to model. .sp Similar situations can occur in many places in \fIns\-3\fP and in any simulator. For example, you may be able to position nodes in such a way that they occupy the same space at the same time, or you may be able to configure amplifiers or noise levels that violate the basic laws of physics. .sp \fIns\-3\fP generally favors flexibility, and many models will allow freely setting \fBAttributes\fP without trying to enforce any arbitrary consistency or particular underlying spec. .sp The thing to take home from this is that \fIns\-3\fP is going to provide a super\-flexible base for you to experiment with. It is up to you to understand what you are asking the system to do and to make sure that the simulations you create have some meaning and some connection with a reality defined by you. .SS Building a Wireless Network Topology .sp In this section we are going to further expand our knowledge of \fIns\-3\fP network devices and channels to cover an example of a wireless network. \fIns\-3\fP provides a set of 802.11 models that attempt to provide an accurate MAC\-level implementation of the 802.11 specification and a “not\-so\-slow” PHY\-level model of the 802.11a specification. .sp Just as we have seen both point\-to\-point and CSMA topology helper objects when constructing point\-to\-point topologies, we will see equivalent \fBWifi\fP topology helpers in this section. The appearance and operation of these helpers should look quite familiar to you. .sp We provide an example script in our \fBexamples/tutorial\fP directory. This script builds on the \fBsecond.cc\fP script and adds a Wi\-Fi network. Go ahead and open \fBexamples/tutorial/third.cc\fP in your favorite editor. You will have already seen enough \fIns\-3\fP code to understand most of what is going on in this example, but there are a few new things, so we will go over the entire script and examine some of the output. .sp Just as in the \fBsecond.cc\fP example (and in all \fIns\-3\fP examples) the file begins with an emacs mode line and some GPL boilerplate. .sp Take a look at the ASCII art (reproduced below) that shows the default network topology constructed in the example. You can see that we are going to further extend our example by hanging a wireless network off of the left side. Notice that this is a default network topology since you can actually vary the number of nodes created on the wired and wireless networks. Just as in the \fBsecond.cc\fP script case, if you change \fBnCsma\fP, it will give you a number of “extra” CSMA nodes. Similarly, you can set \fBnWifi\fP to control how many \fBSTA\fP (station) nodes are created in the simulation. There will always be one \fBAP\fP (access point) node on the wireless network. By default there are three “extra” CSMA nodes and three wireless \fBSTA\fP nodes. .sp The code begins by loading module include files just as was done in the \fBsecond.cc\fP example. There are a couple of new includes corresponding to the wifi module and the mobility module which we will discuss below. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C #include "ns3/core\-module.h" #include "ns3/point\-to\-point\-module.h" #include "ns3/network\-module.h" #include "ns3/applications\-module.h" #include "ns3/wifi\-module.h" #include "ns3/mobility\-module.h" #include "ns3/csma\-module.h" #include "ns3/internet\-module.h" .ft P .fi .UNINDENT .UNINDENT .sp The network topology illustration follows: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C // Default Network Topology // // Wifi 10.1.3.0 // AP // * * * * // | | | | 10.1.1.0 // n5 n6 n7 n0 \-\-\-\-\-\-\-\-\-\-\-\-\-\- n1 n2 n3 n4 // point\-to\-point | | | | // ================ // LAN 10.1.2.0 .ft P .fi .UNINDENT .UNINDENT .sp You can see that we are adding a new network device to the node on the left side of the point\-to\-point link that becomes the access point for the wireless network. A number of wireless STA nodes are created to fill out the new 10.1.3.0 network as shown on the left side of the illustration. .sp After the illustration, the \fBns\-3\fP namespace is \fBused\fP and a logging component is defined. This should all be quite familiar by now. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C using namespace ns3; NS_LOG_COMPONENT_DEFINE ("ThirdScriptExample"); .ft P .fi .UNINDENT .UNINDENT .sp The main program begins just like \fBsecond.cc\fP by adding some command line parameters for enabling or disabling logging components and for changing the number of devices created. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C bool verbose = true; uint32_t nCsma = 3; uint32_t nWifi = 3; CommandLine cmd; cmd.AddValue ("nCsma", "Number of \e"extra\e" CSMA nodes/devices", nCsma); cmd.AddValue ("nWifi", "Number of wifi STA devices", nWifi); cmd.AddValue ("verbose", "Tell echo applications to log if true", verbose); cmd.Parse (argc,argv); if (verbose) { LogComponentEnable("UdpEchoClientApplication", LOG_LEVEL_INFO); LogComponentEnable("UdpEchoServerApplication", LOG_LEVEL_INFO); } .ft P .fi .UNINDENT .UNINDENT .sp Just as in all of the previous examples, the next step is to create two nodes that we will connect via the point\-to\-point link. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C NodeContainer p2pNodes; p2pNodes.Create (2); .ft P .fi .UNINDENT .UNINDENT .sp Next, we see an old friend. We instantiate a \fBPointToPointHelper\fP and set the associated default \fBAttributes\fP so that we create a five megabit per second transmitter on devices created using the helper and a two millisecond delay on channels created by the helper. We then \fBInstall\fP the devices on the nodes and the channel between them. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C PointToPointHelper pointToPoint; pointToPoint.SetDeviceAttribute ("DataRate", StringValue ("5Mbps")); pointToPoint.SetChannelAttribute ("Delay", StringValue ("2ms")); NetDeviceContainer p2pDevices; p2pDevices = pointToPoint.Install (p2pNodes); .ft P .fi .UNINDENT .UNINDENT .sp Next, we declare another \fBNodeContainer\fP to hold the nodes that will be part of the bus (CSMA) network. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C NodeContainer csmaNodes; csmaNodes.Add (p2pNodes.Get (1)); csmaNodes.Create (nCsma); .ft P .fi .UNINDENT .UNINDENT .sp The next line of code \fBGets\fP the first node (as in having an index of one) from the point\-to\-point node container and adds it to the container of nodes that will get CSMA devices. The node in question is going to end up with a point\-to\-point device and a CSMA device. We then create a number of “extra” nodes that compose the remainder of the CSMA network. .sp We then instantiate a \fBCsmaHelper\fP and set its \fBAttributes\fP as we did in the previous example. We create a \fBNetDeviceContainer\fP to keep track of the created CSMA net devices and then we \fBInstall\fP CSMA devices on the selected nodes. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C CsmaHelper csma; csma.SetChannelAttribute ("DataRate", StringValue ("100Mbps")); csma.SetChannelAttribute ("Delay", TimeValue (NanoSeconds (6560))); NetDeviceContainer csmaDevices; csmaDevices = csma.Install (csmaNodes); .ft P .fi .UNINDENT .UNINDENT .sp Next, we are going to create the nodes that will be part of the Wi\-Fi network. We are going to create a number of “station” nodes as specified by the command line argument, and we are going to use the “leftmost” node of the point\-to\-point link as the node for the access point. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C NodeContainer wifiStaNodes; wifiStaNodes.Create (nWifi); NodeContainer wifiApNode = p2pNodes.Get (0); .ft P .fi .UNINDENT .UNINDENT .sp The next bit of code constructs the wifi devices and the interconnection channel between these wifi nodes. First, we configure the PHY and channel helpers: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C YansWifiChannelHelper channel = YansWifiChannelHelper::Default (); YansWifiPhyHelper phy = YansWifiPhyHelper::Default (); .ft P .fi .UNINDENT .UNINDENT .sp For simplicity, this code uses the default PHY layer configuration and channel models which are documented in the API doxygen documentation for the \fBYansWifiChannelHelper::Default\fP and \fBYansWifiPhyHelper::Default\fP methods. Once these objects are created, we create a channel object and associate it to our PHY layer object manager to make sure that all the PHY layer objects created by the \fBYansWifiPhyHelper\fP share the same underlying channel, that is, they share the same wireless medium and can communicate and interfere: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C phy.SetChannel (channel.Create ()); .ft P .fi .UNINDENT .UNINDENT .sp Once the PHY helper is configured, we can focus on the MAC layer. Here we choose to work with non\-Qos MACs. WifiMacHelper object is used to set MAC parameters. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C WifiHelper wifi; wifi.SetRemoteStationManager ("ns3::AarfWifiManager"); WifiMacHelper mac; .ft P .fi .UNINDENT .UNINDENT .sp The \fBSetRemoteStationManager\fP method tells the helper the type of rate control algorithm to use. Here, it is asking the helper to use the AARF algorithm — details are, of course, available in Doxygen. .sp Next, we configure the type of MAC, the SSID of the infrastructure network we want to setup and make sure that our stations don’t perform active probing: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Ssid ssid = Ssid ("ns\-3\-ssid"); mac.SetType ("ns3::StaWifiMac", "Ssid", SsidValue (ssid), "ActiveProbing", BooleanValue (false)); .ft P .fi .UNINDENT .UNINDENT .sp This code first creates an 802.11 service set identifier (SSID) object that will be used to set the value of the “Ssid” \fBAttribute\fP of the MAC layer implementation. The particular kind of MAC layer that will be created by the helper is specified by \fBAttribute\fP as being of the “ns3::StaWifiMac” type. “QosSupported” \fBAttribute\fP is set to false by default for \fBWifiMacHelper\fP objects. The combination of these two configurations means that the MAC instance next created will be a non\-QoS non\-AP station (STA) in an infrastructure BSS (i.e., a BSS with an AP). Finally, the “ActiveProbing” \fBAttribute\fP is set to false. This means that probe requests will not be sent by MACs created by this helper. .sp Once all the station\-specific parameters are fully configured, both at the MAC and PHY layers, we can invoke our now\-familiar \fBInstall\fP method to create the Wi\-Fi devices of these stations: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C NetDeviceContainer staDevices; staDevices = wifi.Install (phy, mac, wifiStaNodes); .ft P .fi .UNINDENT .UNINDENT .sp We have configured Wi\-Fi for all of our STA nodes, and now we need to configure the AP (access point) node. We begin this process by changing the default \fBAttributes\fP of the \fBWifiMacHelper\fP to reflect the requirements of the AP. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C mac.SetType ("ns3::ApWifiMac", "Ssid", SsidValue (ssid)); .ft P .fi .UNINDENT .UNINDENT .sp In this case, the \fBWifiMacHelper\fP is going to create MAC layers of the “ns3::ApWifiMac”, the latter specifying that a MAC instance configured as an AP should be created. We do not change the default setting of “QosSupported” \fBAttribute\fP, so it remains false \- disabling 802.11e/WMM\-style QoS support at created APs. .sp The next lines create the single AP which shares the same set of PHY\-level \fBAttributes\fP (and channel) as the stations: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C NetDeviceContainer apDevices; apDevices = wifi.Install (phy, mac, wifiApNode); .ft P .fi .UNINDENT .UNINDENT .sp Now, we are going to add mobility models. We want the STA nodes to be mobile, wandering around inside a bounding box, and we want to make the AP node stationary. We use the \fBMobilityHelper\fP to make this easy for us. First, we instantiate a \fBMobilityHelper\fP object and set some \fBAttributes\fP controlling the “position allocator” functionality. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C MobilityHelper mobility; mobility.SetPositionAllocator ("ns3::GridPositionAllocator", "MinX", DoubleValue (0.0), "MinY", DoubleValue (0.0), "DeltaX", DoubleValue (5.0), "DeltaY", DoubleValue (10.0), "GridWidth", UintegerValue (3), "LayoutType", StringValue ("RowFirst")); .ft P .fi .UNINDENT .UNINDENT .sp This code tells the mobility helper to use a two\-dimensional grid to initially place the STA nodes. Feel free to explore the Doxygen for class \fBns3::GridPositionAllocator\fP to see exactly what is being done. .sp We have arranged our nodes on an initial grid, but now we need to tell them how to move. We choose the \fBRandomWalk2dMobilityModel\fP which has the nodes move in a random direction at a random speed around inside a bounding box. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C mobility.SetMobilityModel ("ns3::RandomWalk2dMobilityModel", "Bounds", RectangleValue (Rectangle (\-50, 50, \-50, 50))); .ft P .fi .UNINDENT .UNINDENT .sp We now tell the \fBMobilityHelper\fP to install the mobility models on the STA nodes. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C mobility.Install (wifiStaNodes); .ft P .fi .UNINDENT .UNINDENT .sp We want the access point to remain in a fixed position during the simulation. We accomplish this by setting the mobility model for this node to be the \fBns3::ConstantPositionMobilityModel\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel"); mobility.Install (wifiApNode); .ft P .fi .UNINDENT .UNINDENT .sp We now have our nodes, devices and channels created, and mobility models chosen for the Wi\-Fi nodes, but we have no protocol stacks present. Just as we have done previously many times, we will use the \fBInternetStackHelper\fP to install these stacks. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C InternetStackHelper stack; stack.Install (csmaNodes); stack.Install (wifiApNode); stack.Install (wifiStaNodes); .ft P .fi .UNINDENT .UNINDENT .sp Just as in the \fBsecond.cc\fP example script, we are going to use the \fBIpv4AddressHelper\fP to assign IP addresses to our device interfaces. First we use the network 10.1.1.0 to create the two addresses needed for our two point\-to\-point devices. Then we use network 10.1.2.0 to assign addresses to the CSMA network and then we assign addresses from network 10.1.3.0 to both the STA devices and the AP on the wireless network. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Ipv4AddressHelper address; address.SetBase ("10.1.1.0", "255.255.255.0"); Ipv4InterfaceContainer p2pInterfaces; p2pInterfaces = address.Assign (p2pDevices); address.SetBase ("10.1.2.0", "255.255.255.0"); Ipv4InterfaceContainer csmaInterfaces; csmaInterfaces = address.Assign (csmaDevices); address.SetBase ("10.1.3.0", "255.255.255.0"); address.Assign (staDevices); address.Assign (apDevices); .ft P .fi .UNINDENT .UNINDENT .sp We put the echo server on the “rightmost” node in the illustration at the start of the file. We have done this before. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C UdpEchoServerHelper echoServer (9); ApplicationContainer serverApps = echoServer.Install (csmaNodes.Get (nCsma)); serverApps.Start (Seconds (1.0)); serverApps.Stop (Seconds (10.0)); .ft P .fi .UNINDENT .UNINDENT .sp And we put the echo client on the last STA node we created, pointing it to the server on the CSMA network. We have also seen similar operations before. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C UdpEchoClientHelper echoClient (csmaInterfaces.GetAddress (nCsma), 9); echoClient.SetAttribute ("MaxPackets", UintegerValue (1)); echoClient.SetAttribute ("Interval", TimeValue (Seconds (1.0))); echoClient.SetAttribute ("PacketSize", UintegerValue (1024)); ApplicationContainer clientApps = echoClient.Install (wifiStaNodes.Get (nWifi \- 1)); clientApps.Start (Seconds (2.0)); clientApps.Stop (Seconds (10.0)); .ft P .fi .UNINDENT .UNINDENT .sp Since we have built an internetwork here, we need to enable internetwork routing just as we did in the \fBsecond.cc\fP example script. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Ipv4GlobalRoutingHelper::PopulateRoutingTables (); .ft P .fi .UNINDENT .UNINDENT .sp One thing that can surprise some users is the fact that the simulation we just created will never “naturally” stop. This is because we asked the wireless access point to generate beacons. It will generate beacons forever, and this will result in simulator events being scheduled into the future indefinitely, so we must tell the simulator to stop even though it may have beacon generation events scheduled. The following line of code tells the simulator to stop so that we don’t simulate beacons forever and enter what is essentially an endless loop. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Simulator::Stop (Seconds (10.0)); .ft P .fi .UNINDENT .UNINDENT .sp We create just enough tracing to cover all three networks: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C pointToPoint.EnablePcapAll ("third"); phy.EnablePcap ("third", apDevices.Get (0)); csma.EnablePcap ("third", csmaDevices.Get (0), true); .ft P .fi .UNINDENT .UNINDENT .sp These three lines of code will start pcap tracing on both of the point\-to\-point nodes that serves as our backbone, will start a promiscuous (monitor) mode trace on the Wi\-Fi network, and will start a promiscuous trace on the CSMA network. This will let us see all of the traffic with a minimum number of trace files. .sp Finally, we actually run the simulation, clean up and then exit the program. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Simulator::Run (); Simulator::Destroy (); return 0; } .ft P .fi .UNINDENT .UNINDENT .sp In order to run this example, you have to copy the \fBthird.cc\fP example script into the scratch directory and use Waf to build just as you did with the \fBsecond.cc\fP example. If you are in the top\-level directory of the repository you would type, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ cp examples/tutorial/third.cc scratch/mythird.cc $ ./waf $ ./waf \-\-run scratch/mythird .ft P .fi .UNINDENT .UNINDENT .sp Again, since we have set up the UDP echo applications just as we did in the \fBsecond.cc\fP script, you will see similar output. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Waf: Entering directory \(ga/home/craigdo/repos/ns\-3\-allinone/ns\-3\-dev/build\(aq Waf: Leaving directory \(ga/home/craigdo/repos/ns\-3\-allinone/ns\-3\-dev/build\(aq \(aqbuild\(aq finished successfully (0.407s) At time 2s client sent 1024 bytes to 10.1.2.4 port 9 At time 2.01796s server received 1024 bytes from 10.1.3.3 port 49153 At time 2.01796s server sent 1024 bytes to 10.1.3.3 port 49153 At time 2.03364s client received 1024 bytes from 10.1.2.4 port 9 .ft P .fi .UNINDENT .UNINDENT .sp Recall that the first message, \fBSent 1024 bytes to 10.1.2.4\fP,” is the UDP echo client sending a packet to the server. In this case, the client is on the wireless network (10.1.3.0). The second message, “\fBReceived 1024 bytes from 10.1.3.3\fP,” is from the UDP echo server, generated when it receives the echo packet. The final message, “\fBReceived 1024 bytes from 10.1.2.4\fP,” is from the echo client, indicating that it has received its echo back from the server. .sp If you now go and look in the top level directory, you will find four trace files from this simulation, two from node zero and two from node one: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C third\-0\-0.pcap third\-0\-1.pcap third\-1\-0.pcap third\-1\-1.pcap .ft P .fi .UNINDENT .UNINDENT .sp The file “third\-0\-0.pcap” corresponds to the point\-to\-point device on node zero – the left side of the “backbone”. The file “third\-1\-0.pcap” corresponds to the point\-to\-point device on node one – the right side of the “backbone”. The file “third\-0\-1.pcap” will be the promiscuous (monitor mode) trace from the Wi\-Fi network and the file “third\-1\-1.pcap” will be the promiscuous trace from the CSMA network. Can you verify this by inspecting the code? .sp Since the echo client is on the Wi\-Fi network, let’s start there. Let’s take a look at the promiscuous (monitor mode) trace we captured on that network. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ tcpdump \-nn \-tt \-r third\-0\-1.pcap .ft P .fi .UNINDENT .UNINDENT .sp You should see some wifi\-looking contents you haven’t seen here before: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C reading from file third\-0\-1.pcap, link\-type IEEE802_11 (802.11) 0.000025 Beacon (ns\-3\-ssid) [6.0* 9.0 12.0 18.0 24.0 36.0 48.0 54.0 Mbit] IBSS 0.000308 Assoc Request (ns\-3\-ssid) [6.0 9.0 12.0 18.0 24.0 36.0 48.0 54.0 Mbit] 0.000324 Acknowledgment RA:00:00:00:00:00:08 0.000402 Assoc Response AID(0) :: Successful 0.000546 Acknowledgment RA:00:00:00:00:00:0a 0.000721 Assoc Request (ns\-3\-ssid) [6.0 9.0 12.0 18.0 24.0 36.0 48.0 54.0 Mbit] 0.000737 Acknowledgment RA:00:00:00:00:00:07 0.000824 Assoc Response AID(0) :: Successful 0.000968 Acknowledgment RA:00:00:00:00:00:0a 0.001134 Assoc Request (ns\-3\-ssid) [6.0 9.0 12.0 18.0 24.0 36.0 48.0 54.0 Mbit] 0.001150 Acknowledgment RA:00:00:00:00:00:09 0.001273 Assoc Response AID(0) :: Successful 0.001417 Acknowledgment RA:00:00:00:00:00:0a 0.102400 Beacon (ns\-3\-ssid) [6.0* 9.0 12.0 18.0 24.0 36.0 48.0 54.0 Mbit] IBSS 0.204800 Beacon (ns\-3\-ssid) [6.0* 9.0 12.0 18.0 24.0 36.0 48.0 54.0 Mbit] IBSS 0.307200 Beacon (ns\-3\-ssid) [6.0* 9.0 12.0 18.0 24.0 36.0 48.0 54.0 Mbit] IBSS .ft P .fi .UNINDENT .UNINDENT .sp You can see that the link type is now 802.11 as you would expect. You can probably understand what is going on and find the IP echo request and response packets in this trace. We leave it as an exercise to completely parse the trace dump. .sp Now, look at the pcap file of the left side of the point\-to\-point link, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ tcpdump \-nn \-tt \-r third\-0\-0.pcap .ft P .fi .UNINDENT .UNINDENT .sp Again, you should see some familiar looking contents: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C reading from file third\-0\-0.pcap, link\-type PPP (PPP) 2.008151 IP 10.1.3.3.49153 > 10.1.2.4.9: UDP, length 1024 2.026758 IP 10.1.2.4.9 > 10.1.3.3.49153: UDP, length 1024 .ft P .fi .UNINDENT .UNINDENT .sp This is the echo packet going from left to right (from Wi\-Fi to CSMA) and back again across the point\-to\-point link. .sp Now, look at the pcap file of the right side of the point\-to\-point link, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ tcpdump \-nn \-tt \-r third\-1\-0.pcap .ft P .fi .UNINDENT .UNINDENT .sp Again, you should see some familiar looking contents: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C reading from file third\-1\-0.pcap, link\-type PPP (PPP) 2.011837 IP 10.1.3.3.49153 > 10.1.2.4.9: UDP, length 1024 2.023072 IP 10.1.2.4.9 > 10.1.3.3.49153: UDP, length 1024 .ft P .fi .UNINDENT .UNINDENT .sp This is also the echo packet going from left to right (from Wi\-Fi to CSMA) and back again across the point\-to\-point link with slightly different timings as you might expect. .sp The echo server is on the CSMA network, let’s look at the promiscuous trace there: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ tcpdump \-nn \-tt \-r third\-1\-1.pcap .ft P .fi .UNINDENT .UNINDENT .sp You should see some familiar looking contents: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C reading from file third\-1\-1.pcap, link\-type EN10MB (Ethernet) 2.017837 ARP, Request who\-has 10.1.2.4 (ff:ff:ff:ff:ff:ff) tell 10.1.2.1, length 50 2.017861 ARP, Reply 10.1.2.4 is\-at 00:00:00:00:00:06, length 50 2.017861 IP 10.1.3.3.49153 > 10.1.2.4.9: UDP, length 1024 2.022966 ARP, Request who\-has 10.1.2.1 (ff:ff:ff:ff:ff:ff) tell 10.1.2.4, length 50 2.022966 ARP, Reply 10.1.2.1 is\-at 00:00:00:00:00:03, length 50 2.023072 IP 10.1.2.4.9 > 10.1.3.3.49153: UDP, length 1024 .ft P .fi .UNINDENT .UNINDENT .sp This should be easily understood. If you’ve forgotten, go back and look at the discussion in \fBsecond.cc\fP\&. This is the same sequence. .sp Now, we spent a lot of time setting up mobility models for the wireless network and so it would be a shame to finish up without even showing that the STA nodes are actually moving around during the simulation. Let’s do this by hooking into the \fBMobilityModel\fP course change trace source. This is just a sneak peek into the detailed tracing section which is coming up, but this seems a very nice place to get an example in. .sp As mentioned in the “Tweaking ns\-3” section, the \fIns\-3\fP tracing system is divided into trace sources and trace sinks, and we provide functions to connect the two. We will use the mobility model predefined course change trace source to originate the trace events. We will need to write a trace sink to connect to that source that will display some pretty information for us. Despite its reputation as being difficult, it’s really quite simple. Just before the main program of the \fBscratch/mythird.cc\fP script (i.e., just after the \fBNS_LOG_COMPONENT_DEFINE\fP statement), add the following function: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C void CourseChange (std::string context, Ptr model) { Vector position = model\->GetPosition (); NS_LOG_UNCOND (context << " x = " << position.x << ", y = " << position.y); } .ft P .fi .UNINDENT .UNINDENT .sp This code just pulls the position information from the mobility model and unconditionally logs the x and y position of the node. We are going to arrange for this function to be called every time the wireless node with the echo client changes its position. We do this using the \fBConfig::Connect\fP function. Add the following lines of code to the script just before the \fBSimulator::Run\fP call. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C std::ostringstream oss; oss << "/NodeList/" << wifiStaNodes.Get (nWifi \- 1)\->GetId () << "/$ns3::MobilityModel/CourseChange"; Config::Connect (oss.str (), MakeCallback (&CourseChange)); .ft P .fi .UNINDENT .UNINDENT .sp What we do here is to create a string containing the tracing namespace path of the event to which we want to connect. First, we have to figure out which node it is we want using the \fBGetId\fP method as described earlier. In the case of the default number of CSMA and wireless nodes, this turns out to be node seven and the tracing namespace path to the mobility model would look like, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C /NodeList/7/$ns3::MobilityModel/CourseChange .ft P .fi .UNINDENT .UNINDENT .sp Based on the discussion in the tracing section, you may infer that this trace path references the seventh node in the global NodeList. It specifies what is called an aggregated object of type \fBns3::MobilityModel\fP\&. The dollar sign prefix implies that the MobilityModel is aggregated to node seven. The last component of the path means that we are hooking into the “CourseChange” event of that model. .sp We make a connection between the trace source in node seven with our trace sink by calling \fBConfig::Connect\fP and passing this namespace path. Once this is done, every course change event on node seven will be hooked into our trace sink, which will in turn print out the new position. .sp If you now run the simulation, you will see the course changes displayed as they happen. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C \(aqbuild\(aq finished successfully (5.989s) /NodeList/7/$ns3::MobilityModel/CourseChange x = 10, y = 0 /NodeList/7/$ns3::MobilityModel/CourseChange x = 10.3841, y = 0.923277 /NodeList/7/$ns3::MobilityModel/CourseChange x = 10.2049, y = 1.90708 /NodeList/7/$ns3::MobilityModel/CourseChange x = 10.8136, y = 1.11368 /NodeList/7/$ns3::MobilityModel/CourseChange x = 10.8452, y = 2.11318 /NodeList/7/$ns3::MobilityModel/CourseChange x = 10.9797, y = 3.10409 At time 2s client sent 1024 bytes to 10.1.2.4 port 9 At time 2.01796s server received 1024 bytes from 10.1.3.3 port 49153 At time 2.01796s server sent 1024 bytes to 10.1.3.3 port 49153 At time 2.03364s client received 1024 bytes from 10.1.2.4 port 9 /NodeList/7/$ns3::MobilityModel/CourseChange x = 11.3273, y = 4.04175 /NodeList/7/$ns3::MobilityModel/CourseChange x = 12.013, y = 4.76955 /NodeList/7/$ns3::MobilityModel/CourseChange x = 12.4317, y = 5.67771 /NodeList/7/$ns3::MobilityModel/CourseChange x = 11.4607, y = 5.91681 /NodeList/7/$ns3::MobilityModel/CourseChange x = 12.0155, y = 6.74878 /NodeList/7/$ns3::MobilityModel/CourseChange x = 13.0076, y = 6.62336 /NodeList/7/$ns3::MobilityModel/CourseChange x = 12.6285, y = 5.698 /NodeList/7/$ns3::MobilityModel/CourseChange x = 13.32, y = 4.97559 /NodeList/7/$ns3::MobilityModel/CourseChange x = 13.1134, y = 3.99715 /NodeList/7/$ns3::MobilityModel/CourseChange x = 13.8359, y = 4.68851 /NodeList/7/$ns3::MobilityModel/CourseChange x = 13.5953, y = 3.71789 /NodeList/7/$ns3::MobilityModel/CourseChange x = 12.7595, y = 4.26688 /NodeList/7/$ns3::MobilityModel/CourseChange x = 11.7629, y = 4.34913 /NodeList/7/$ns3::MobilityModel/CourseChange x = 11.2292, y = 5.19485 /NodeList/7/$ns3::MobilityModel/CourseChange x = 10.2344, y = 5.09394 /NodeList/7/$ns3::MobilityModel/CourseChange x = 9.3601, y = 4.60846 /NodeList/7/$ns3::MobilityModel/CourseChange x = 8.40025, y = 4.32795 /NodeList/7/$ns3::MobilityModel/CourseChange x = 9.14292, y = 4.99761 /NodeList/7/$ns3::MobilityModel/CourseChange x = 9.08299, y = 5.99581 /NodeList/7/$ns3::MobilityModel/CourseChange x = 8.26068, y = 5.42677 /NodeList/7/$ns3::MobilityModel/CourseChange x = 8.35917, y = 6.42191 /NodeList/7/$ns3::MobilityModel/CourseChange x = 7.66805, y = 7.14466 /NodeList/7/$ns3::MobilityModel/CourseChange x = 6.71414, y = 6.84456 /NodeList/7/$ns3::MobilityModel/CourseChange x = 6.42489, y = 7.80181 .ft P .fi .UNINDENT .UNINDENT .SS Queues in ns\-3 .sp The selection of queueing disciplines in \fIns\-3\fP can have a large impact on performance, and it is important for users to understand what is installed by default and how to change the defaults and observe the performance. .sp Architecturally, \fIns\-3\fP separates the device layer from the IP layers or traffic control layers of an Internet host. Since recent releases of \fIns\-3\fP, outgoing packets traverse two queueing layers before reaching the channel object. The first queueing layer encountered is what is called the ‘traffic control layer’ in \fIns\-3\fP; here, active queue management (RFC7567) and prioritization due to quality\-of\-service (QoS) takes place in a device\-independent manner through the use of queueing disciplines. The second queueing layer is typically found in the NetDevice objects. Different devices (e.g. LTE, Wi\-Fi) have different implementations of these queues. This two\-layer approach mirrors what is found in practice, (software queues providing prioritization, and hardware queues specific to a link type). In practice, it may be even more complex than this. For instance, address resolution protocols have a small queue. Wi\-Fi in Linux has four layers of queueing (\fI\%https://lwn.net/Articles/705884/\fP). .sp The traffic control layer is effective only if it is notified by the NetDevice when the device queue is full, so that the traffic control layer can stop sending packets to the NetDevice. Otherwise, the backlog of the queueing disciplines is always null and they are ineffective. Currently, flow control, i.e., the ability of notifying the traffic control layer, is supported by the following NetDevices, which use Queue objects (or objects of Queue subclasses) to store their packets: .INDENT 0.0 .IP \(bu 2 Point\-To\-Point .IP \(bu 2 Csma .IP \(bu 2 Wi\-Fi .IP \(bu 2 SimpleNetDevice .UNINDENT .sp The performance of queueing disciplines is highly impacted by the size of the queues used by the NetDevices. Currently, queues by default in \fIns\-3\fP are not autotuned for the configured link properties (bandwidth, delay), and are typically the simplest variants (e.g. FIFO scheduling with drop\-tail behavior). However, the size of the queues can be dynamically adjusted by enabling BQL (Byte Queue Limits), the algorithm implemented in the Linux kernel to adjust the size of the device queues to fight bufferbloat while avoiding starvation. Currently, BQL is supported by the NetDevices that support flow control. An analysis of the impact of the size of the device queues on the effectiveness of the queueing disciplines conducted by means of \fIns\-3\fP simulations and real experiments is reported in: .sp P. Imputato and S. Avallone. An analysis of the impact of network device buffers on packet schedulers through experiments and simulations. Simulation Modelling Practice and Theory, 80(Supplement C):1–18, January 2018. DOI: 10.1016/j.simpat.2017.09.008 .SS Available queueing models in \fIns\-3\fP .sp At the traffic\-control layer, these are the options: .INDENT 0.0 .IP \(bu 2 PFifoFastQueueDisc: The default maximum size is 1000 packets .IP \(bu 2 FifoQueueDisc: The default maximum size is 1000 packets .IP \(bu 2 RedQueueDisc: The default maximum size is 25 packets .IP \(bu 2 CoDelQueueDisc: The default maximum size is 1500 kilobytes .IP \(bu 2 FqCoDelQueueDisc: The default maximum size is 10240 packets .IP \(bu 2 PieQueueDisc: The default maximum size is 25 packets .IP \(bu 2 MqQueueDisc: This queue disc has no limits on its capacity .IP \(bu 2 TbfQueueDisc: The default maximum size is 1000 packets .UNINDENT .sp By default, a pfifo_fast queueing discipline is installed on a NetDevice when an IPv4 or IPv6 address is assigned to an interface associated with the NetDevice, unless a queueing discipline has been already installed on the NetDevice. .sp At the device layer, there are device specific queues: .INDENT 0.0 .IP \(bu 2 PointToPointNetDevice: The default configuration (as set by the helper) is to install a DropTail queue of default size (100 packets) .IP \(bu 2 CsmaNetDevice: The default configuration (as set by the helper) is to install a DropTail queue of default size (100 packets) .IP \(bu 2 WiFiNetDevice: The default configuration is to install a DropTail queue of default size (100 packets) for non\-QoS stations and four DropTail queues of default size (100 packets) for QoS stations .IP \(bu 2 SimpleNetDevice: The default configuration is to install a DropTail queue of default size (100 packets) .IP \(bu 2 LTENetDevice: Queueing occurs at the RLC layer (RLC UM default buffer is 10 * 1024 bytes, RLC AM does not have a buffer limit). .IP \(bu 2 UanNetDevice: There is a default 10 packet queue at the MAC layer .UNINDENT .SS Changing from the defaults .INDENT 0.0 .IP \(bu 2 The type of queue used by a NetDevice can be usually modified through the device helper: .INDENT 2.0 .INDENT 3.5 .sp .nf .ft C NodeContainer nodes; nodes.Create (2); PointToPointHelper p2p; p2p.SetQueue ("ns3::DropTailQueue", "MaxSize", StringValue ("50p")); NetDeviceContainer devices = p2p.Install (nodes); .ft P .fi .UNINDENT .UNINDENT .IP \(bu 2 The type of queue disc installed on a NetDevice can be modified through the traffic control helper: .INDENT 2.0 .INDENT 3.5 .sp .nf .ft C InternetStackHelper stack; stack.Install (nodes); TrafficControlHelper tch; tch.SetRootQueueDisc ("ns3::CoDelQueueDisc", "MaxSize", StringValue ("1000p")); tch.Install (devices); .ft P .fi .UNINDENT .UNINDENT .IP \(bu 2 BQL can be enabled on a device that supports it through the traffic control helper: .INDENT 2.0 .INDENT 3.5 .sp .nf .ft C InternetStackHelper stack; stack.Install (nodes); TrafficControlHelper tch; tch.SetRootQueueDisc ("ns3::CoDelQueueDisc", "MaxSize", StringValue ("1000p")); tch.SetQueueLimits ("ns3::DynamicQueueLimits", "HoldTime", StringValue ("4ms")); tch.Install (devices); .ft P .fi .UNINDENT .UNINDENT .UNINDENT .SH TRACING .SS Background .sp As mentioned in \fI\%Using the Tracing System\fP, the whole point of running an \fIns\-3\fP simulation is to generate output for study. You have two basic strategies to obtain output from \fIns\-3\fP: using generic pre\-defined bulk output mechanisms and parsing their content to extract interesting information; or somehow developing an output mechanism that conveys exactly (and perhaps only) the information wanted. .sp Using pre\-defined bulk output mechanisms has the advantage of not requiring any changes to \fIns\-3\fP, but it may require writing scripts to parse and filter for data of interest. Often, PCAP or \fBNS_LOG\fP output messages are gathered during simulation runs and separately run through scripts that use \fBgrep\fP, \fBsed\fP or \fBawk\fP to parse the messages and reduce and transform the data to a manageable form. Programs must be written to do the transformation, so this does not come for free. \fBNS_LOG\fP output is not considered part of the \fIns\-3\fP API, and can change without warning between releases. In addition, \fBNS_LOG\fP output is only available in debug builds, so relying on it imposes a performance penalty. Of course, if the information of interest does not exist in any of the pre\-defined output mechanisms, this approach fails. .sp If you need to add some tidbit of information to the pre\-defined bulk mechanisms, this can certainly be done; and if you use one of the \fIns\-3\fP mechanisms, you may get your code added as a contribution. .sp \fIns\-3\fP provides another mechanism, called Tracing, that avoids some of the problems inherent in the bulk output mechanisms. It has several important advantages. First, you can reduce the amount of data you have to manage by only tracing the events of interest to you (for large simulations, dumping everything to disk for post\-processing can create I/O bottlenecks). Second, if you use this method, you can control the format of the output directly so you avoid the postprocessing step with \fBsed\fP, \fBawk\fP, \fBperl\fP or \fBpython\fP scripts. If you desire, your output can be formatted directly into a form acceptable by gnuplot, for example (see also \fI\%GnuplotHelper\fP). You can add hooks in the core which can then be accessed by other users, but which will produce no information unless explicitly asked to do so. For these reasons, we believe that the \fIns\-3\fP tracing system is the best way to get information out of a simulation and is also therefore one of the most important mechanisms to understand in \fIns\-3\fP\&. .SS Blunt Instruments .sp There are many ways to get information out of a program. The most straightforward way is to just print the information directly to the standard output, as in: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C #include \&... void SomeFunction (void) { uint32_t x = SOME_INTERESTING_VALUE; ... std::cout << "The value of x is " << x << std::endl; ... } .ft P .fi .UNINDENT .UNINDENT .sp Nobody is going to prevent you from going deep into the core of \fIns\-3\fP and adding print statements. This is insanely easy to do and, after all, you have complete control of your own \fIns\-3\fP branch. This will probably not turn out to be very satisfactory in the long term, though. .sp As the number of print statements increases in your programs, the task of dealing with the large number of outputs will become more and more complicated. Eventually, you may feel the need to control what information is being printed in some way, perhaps by turning on and off certain categories of prints, or increasing or decreasing the amount of information you want. If you continue down this path you may discover that you have re\-implemented the \fBNS_LOG\fP mechanism (see \fI\%Using the Logging Module\fP). In order to avoid that, one of the first things you might consider is using \fBNS_LOG\fP itself. .sp We mentioned above that one way to get information out of \fIns\-3\fP is to parse existing \fBNS_LOG\fP output for interesting information. If you discover that some tidbit of information you need is not present in existing log output, you could edit the core of \fIns\-3\fP and simply add your interesting information to the output stream. Now, this is certainly better than adding your own print statements since it follows \fIns\-3\fP coding conventions and could potentially be useful to other people as a patch to the existing core. .sp Let’s pick a random example. If you wanted to add more logging to the \fIns\-3\fP TCP socket (\fBtcp\-socket\-base.cc\fP) you could just add a new message down in the implementation. Notice that in \fBTcpSocketBase::ProcessEstablished ()\fP there is no log message for the reception of a SYN+ACK in ESTABLISHED state. You could simply add one, changing the code. Here is the original: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C /* Received a packet upon ESTABLISHED state. This function is mimicking the role of tcp_rcv_established() in tcp_input.c in Linux kernel. */ void TcpSocketBase::ProcessEstablished (Ptr packet, const TcpHeader& tcpHeader) { NS_LOG_FUNCTION (this << tcpHeader); ... else if (tcpflags == (TcpHeader::SYN | TcpHeader::ACK)) { // No action for received SYN+ACK, it is probably a duplicated packet } ... .ft P .fi .UNINDENT .UNINDENT .sp To log the SYN+ACK case, you can add a new \fBNS_LOG_LOGIC\fP in the \fBif\fP statement body: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C /* Received a packet upon ESTABLISHED state. This function is mimicking the role of tcp_rcv_established() in tcp_input.c in Linux kernel. */ void TcpSocketBase::ProcessEstablished (Ptr packet, const TcpHeader& tcpHeader) { NS_LOG_FUNCTION (this << tcpHeader); ... else if (tcpflags == (TcpHeader::SYN | TcpHeader::ACK)) { // No action for received SYN+ACK, it is probably a duplicated packet NS_LOG_LOGIC ("TcpSocketBase " << this << " ignoring SYN+ACK"); } ... .ft P .fi .UNINDENT .UNINDENT .sp This may seem fairly simple and satisfying at first glance, but something to consider is that you will be writing code to add \fBNS_LOG\fP statements and you will also have to write code (as in \fBgrep\fP, \fBsed\fP or \fBawk\fP scripts) to parse the log output in order to isolate your information. This is because even though you have some control over what is output by the logging system, you only have control down to the log component level, which is typically an entire source code file. .sp If you are adding code to an existing module, you will also have to live with the output that every other developer has found interesting. You may find that in order to get the small amount of information you need, you may have to wade through huge amounts of extraneous messages that are of no interest to you. You may be forced to save huge log files to disk and process them down to a few lines whenever you want to do anything. .sp Since there are no guarantees in \fIns\-3\fP about the stability of \fBNS_LOG\fP output, you may also discover that pieces of log output which you depend on disappear or change between releases. If you depend on the structure of the output, you may find other messages being added or deleted which may affect your parsing code. .sp Finally, \fBNS_LOG\fP output is only available in debug builds, you can’t get log output from optimized builds, which run about twice as fast. Relying on \fBNS_LOG\fP imposes a performance penalty. .sp For these reasons, we consider prints to \fBstd::cout\fP and \fBNS_LOG\fP messages to be quick and dirty ways to get more information out of \fIns\-3\fP, but not suitable for serious work. .sp It is desirable to have a stable facility using stable APIs that allow one to reach into the core system and only get the information required. It is desirable to be able to do this without having to change and recompile the core system. Even better would be a system that notified user code when an item of interest changed or an interesting event happened so the user doesn’t have to actively poke around in the system looking for things. .sp The \fIns\-3\fP tracing system is designed to work along those lines and is well\-integrated with the \fI\%Attribute\fP and \fI\%Config\fP subsystems allowing for relatively simple use scenarios. .SS Overview .sp The \fIns\-3\fP tracing system is built on the concepts of independent tracing sources and tracing sinks, along with a uniform mechanism for connecting sources to sinks. .sp Trace sources are entities that can signal events that happen in a simulation and provide access to interesting underlying data. For example, a trace source could indicate when a packet is received by a net device and provide access to the packet contents for interested trace sinks. A trace source might also indicate when an interesting state change happens in a model. For example, the congestion window of a TCP model is a prime candidate for a trace source. Every time the congestion window changes connected trace sinks are notified with the old and new value. .sp Trace sources are not useful by themselves; they must be connected to other pieces of code that actually do something useful with the information provided by the source. The entities that consume trace information are called trace sinks. Trace sources are generators of data and trace sinks are consumers. This explicit division allows for large numbers of trace sources to be scattered around the system in places which model authors believe might be useful. Inserting trace sources introduces a very small execution overhead. .sp There can be zero or more consumers of trace events generated by a trace source. One can think of a trace source as a kind of point\-to\-multipoint information link. Your code looking for trace events from a particular piece of core code could happily coexist with other code doing something entirely different from the same information. .sp Unless a user connects a trace sink to one of these sources, nothing is output. By using the tracing system, both you and other people hooked to the same trace source are getting exactly what they want and only what they want out of the system. Neither of you are impacting any other user by changing what information is output by the system. If you happen to add a trace source, your work as a good open\-source citizen may allow other users to provide new utilities that are perhaps very useful overall, without making any changes to the \fIns\-3\fP core. .SS Simple Example .sp Let’s take a few minutes and walk through a simple tracing example. We are going to need a little background on Callbacks to understand what is happening in the example, so we have to take a small detour right away. .SS Callbacks .sp The goal of the Callback system in \fIns\-3\fP is to allow one piece of code to call a function (or method in C++) without any specific inter\-module dependency. This ultimately means you need some kind of indirection – you treat the address of the called function as a variable. This variable is called a pointer\-to\-function variable. The relationship between function and pointer\-to\-function is really no different that that of object and pointer\-to\-object. .sp In C the canonical example of a pointer\-to\-function is a pointer\-to\-function\-returning\-integer (PFI). For a PFI taking one \fBint\fP parameter, this could be declared like, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C int (*pfi)(int arg) = 0; .ft P .fi .UNINDENT .UNINDENT .sp (But read the \fI\%C++\-FAQ Section 33\fP before writing code like this!) What you get from this is a variable named simply \fBpfi\fP that is initialized to the value 0. If you want to initialize this pointer to something meaningful, you need to have a function with a matching signature. In this case, you could provide a function that looks like: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C int MyFunction (int arg) {} .ft P .fi .UNINDENT .UNINDENT .sp If you have this target, you can initialize the variable to point to your function: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C pfi = MyFunction; .ft P .fi .UNINDENT .UNINDENT .sp You can then call MyFunction indirectly using the more suggestive form of the call: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C int result = (*pfi) (1234); .ft P .fi .UNINDENT .UNINDENT .sp This is suggestive since it looks like you are dereferencing the function pointer just like you would dereference any pointer. Typically, however, people take advantage of the fact that the compiler knows what is going on and will just use a shorter form: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C int result = pfi (1234); .ft P .fi .UNINDENT .UNINDENT .sp This looks like you are calling a function named \fBpfi\fP, but the compiler is smart enough to know to call through the variable \fBpfi\fP indirectly to the function \fBMyFunction\fP\&. .sp Conceptually, this is almost exactly how the tracing system works. Basically, a trace sink \fIis\fP a callback. When a trace sink expresses interest in receiving trace events, it adds itself as a Callback to a list of Callbacks internally held by the trace source. When an interesting event happens, the trace source invokes its \fBoperator(...)\fP providing zero or more arguments. The \fBoperator(...)\fP eventually wanders down into the system and does something remarkably like the indirect call you just saw, providing zero or more parameters, just as the call to \fBpfi\fP above passed one parameter to the target function \fBMyFunction\fP\&. .sp The important difference that the tracing system adds is that for each trace source there is an internal list of Callbacks. Instead of just making one indirect call, a trace source may invoke multiple Callbacks. When a trace sink expresses interest in notifications from a trace source, it basically just arranges to add its own function to the callback list. .sp If you are interested in more details about how this is actually arranged in \fIns\-3\fP, feel free to peruse the Callback section of the \fIns\-3\fP Manual. .SS Walkthrough: \fBfourth.cc\fP .sp We have provided some code to implement what is really the simplest example of tracing that can be assembled. You can find this code in the tutorial directory as \fBfourth.cc\fP\&. Let’s walk through it: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C /* \-*\- Mode:C++; c\-file\-style:"gnu"; indent\-tabs\-mode:nil; \-*\- */ /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111\-1307 USA */ #include "ns3/object.h" #include "ns3/uinteger.h" #include "ns3/traced\-value.h" #include "ns3/trace\-source\-accessor.h" #include using namespace ns3; .ft P .fi .UNINDENT .UNINDENT .sp Most of this code should be quite familiar to you. As mentioned above, the trace system makes heavy use of the Object and Attribute systems, so you will need to include them. The first two includes above bring in the declarations for those systems explicitly. You could use the core module header to get everything at once, but we do the includes explicitly here to illustrate how simple this all really is. .sp The file, \fBtraced\-value.h\fP brings in the required declarations for tracing of data that obeys value semantics. In general, value semantics just means that you can pass the object itself around, rather than passing the address of the object. What this all really means is that you will be able to trace all changes made to a TracedValue in a really simple way. .sp Since the tracing system is integrated with Attributes, and Attributes work with Objects, there must be an \fIns\-3\fP \fBObject\fP for the trace source to live in. The next code snippet declares and defines a simple Object we can work with. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C class MyObject : public Object { public: static TypeId GetTypeId (void) { static TypeId tid = TypeId ("MyObject") .SetParent (Object::GetTypeId ()) .SetGroupName ("MyGroup") .AddConstructor () .AddTraceSource ("MyInteger", "An integer value to trace.", MakeTraceSourceAccessor (&MyObject::m_myInt), "ns3::TracedValueCallback::Int32") ; return tid; } MyObject () {} TracedValue m_myInt; }; .ft P .fi .UNINDENT .UNINDENT .sp The two important lines of code, above, with respect to tracing are the \fB\&.AddTraceSource\fP and the \fBTracedValue\fP declaration of \fBm_myInt\fP\&. .sp The \fB\&.AddTraceSource\fP provides the “hooks” used for connecting the trace source to the outside world through the Config system. The first argument is a name for this trace source, which makes it visible in the Config system. The second argument is a help string. Now look at the third argument, in fact focus on the \fIargument\fP of the third argument: \fB&MyObject::m_myInt\fP\&. This is the TracedValue which is being added to the class; it is always a class data member. (The final argument is the name of a \fBtypedef\fP for the TracedValue type, as a string. This is used to generate documentation for the correct Callback function signature, which is useful especially for more general types of Callbacks.) .sp The \fBTracedValue<>\fP declaration provides the infrastructure that drives the callback process. Any time the underlying value is changed the TracedValue mechanism will provide both the old and the new value of that variable, in this case an \fBint32_t\fP value. The trace sink function \fBtraceSink\fP for this TracedValue will need the signature .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C void (* traceSink)(int32_t oldValue, int32_t newValue); .ft P .fi .UNINDENT .UNINDENT .sp All trace sinks hooking this trace source must have this signature. We’ll discuss below how you can determine the required callback signature in other cases. .sp Sure enough, continuing through \fBfourth.cc\fP we see: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C void IntTrace (int32_t oldValue, int32_t newValue) { std::cout << "Traced " << oldValue << " to " << newValue << std::endl; } .ft P .fi .UNINDENT .UNINDENT .sp This is the definition of a matching trace sink. It corresponds directly to the callback function signature. Once it is connected, this function will be called whenever the \fBTracedValue\fP changes. .sp We have now seen the trace source and the trace sink. What remains is code to connect the source to the sink, which happens in \fBmain\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C int main (int argc, char *argv[]) { Ptr myObject = CreateObject (); myObject\->TraceConnectWithoutContext ("MyInteger", MakeCallback(&IntTrace)); myObject\->m_myInt = 1234; } .ft P .fi .UNINDENT .UNINDENT .sp Here we first create the MyObject instance in which the trace source lives. .sp The next step, the \fBTraceConnectWithoutContext\fP, forms the connection between the trace source and the trace sink. The first argument is just the trace source name “MyInteger” we saw above. Notice the \fBMakeCallback\fP template function. This function does the magic required to create the underlying \fIns\-3\fP Callback object and associate it with the function \fBIntTrace\fP\&. \fBTraceConnect\fP makes the association between your provided function and overloaded \fBoperator()\fP in the traced variable referred to by the “MyInteger” Attribute. After this association is made, the trace source will “fire” your provided callback function. .sp The code to make all of this happen is, of course, non\-trivial, but the essence is that you are arranging for something that looks just like the \fBpfi()\fP example above to be called by the trace source. The declaration of the \fBTracedValue m_myInt;\fP in the Object itself performs the magic needed to provide the overloaded assignment operators that will use the \fBoperator()\fP to actually invoke the Callback with the desired parameters. The \fB\&.AddTraceSource\fP performs the magic to connect the Callback to the Config system, and \fBTraceConnectWithoutContext\fP performs the magic to connect your function to the trace source, which is specified by Attribute name. .sp Let’s ignore the bit about context for now. .sp Finally, the line assigning a value to \fBm_myInt\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C myObject\->m_myInt = 1234; .ft P .fi .UNINDENT .UNINDENT .sp should be interpreted as an invocation of \fBoperator=\fP on the member variable \fBm_myInt\fP with the integer \fB1234\fP passed as a parameter. .sp Since \fBm_myInt\fP is a \fBTracedValue\fP, this operator is defined to execute a callback that returns void and takes two integer values as parameters — an old value and a new value for the integer in question. That is exactly the function signature for the callback function we provided — \fBIntTrace\fP\&. .sp To summarize, a trace source is, in essence, a variable that holds a list of callbacks. A trace sink is a function used as the target of a callback. The Attribute and object type information systems are used to provide a way to connect trace sources to trace sinks. The act of “hitting” a trace source is executing an operator on the trace source which fires callbacks. This results in the trace sink callbacks who registering interest in the source being called with the parameters provided by the source. .sp If you now build and run this example, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./waf \-\-run fourth .ft P .fi .UNINDENT .UNINDENT .sp you will see the output from the \fBIntTrace\fP function execute as soon as the trace source is hit: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Traced 0 to 1234 .ft P .fi .UNINDENT .UNINDENT .sp When we executed the code, \fBmyObject\->m_myInt = 1234;\fP, the trace source fired and automatically provided the before and after values to the trace sink. The function \fBIntTrace\fP then printed this to the standard output. .SS Connect with Config .sp The \fBTraceConnectWithoutContext\fP call shown above in the simple example is actually very rarely used in the system. More typically, the \fBConfig\fP subsystem is used to select a trace source in the system using what is called a \fIConfig path\fP\&. We saw an example of this in the previous section where we hooked the “CourseChange” event when we were experimenting with \fBthird.cc\fP\&. .sp Recall that we defined a trace sink to print course change information from the mobility models of our simulation. It should now be a lot more clear to you what this function is doing: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C void CourseChange (std::string context, Ptr model) { Vector position = model\->GetPosition (); NS_LOG_UNCOND (context << " x = " << position.x << ", y = " << position.y); } .ft P .fi .UNINDENT .UNINDENT .sp When we connected the “CourseChange” trace source to the above trace sink, we used a Config path to specify the source when we arranged a connection between the pre\-defined trace source and the new trace sink: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C std::ostringstream oss; oss << "/NodeList/" << wifiStaNodes.Get (nWifi \- 1)\->GetId () << "/$ns3::MobilityModel/CourseChange"; Config::Connect (oss.str (), MakeCallback (&CourseChange)); .ft P .fi .UNINDENT .UNINDENT .sp Let’s try and make some sense of what is sometimes considered relatively mysterious code. For the purposes of discussion, assume that the Node number returned by the \fBGetId()\fP is “7”. In this case, the path above turns out to be .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C "/NodeList/7/$ns3::MobilityModel/CourseChange" .ft P .fi .UNINDENT .UNINDENT .sp The last segment of a config path must be an \fBAttribute\fP of an \fBObject\fP\&. In fact, if you had a pointer to the \fBObject\fP that has the “CourseChange” \fBAttribute\fP handy, you could write this just like we did in the previous example. You know by now that we typically store pointers to our \fBNodes\fP in a NodeContainer. In the \fBthird.cc\fP example, the Nodes of interest are stored in the \fBwifiStaNodes\fP NodeContainer. In fact, while putting the path together, we used this container to get a \fBPtr\fP which we used to call \fBGetId()\fP\&. We could have used this \fBPtr\fP to call a Connect method directly: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Ptr theObject = wifiStaNodes.Get (nWifi \- 1); theObject\->TraceConnectWithoutContext ("CourseChange", MakeCallback (&CourseChange)); .ft P .fi .UNINDENT .UNINDENT .sp In the \fBthird.cc\fP example, we actually wanted an additional “context” to be delivered along with the Callback parameters (which will be explained below) so we could actually use the following equivalent code: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Ptr theObject = wifiStaNodes.Get (nWifi \- 1); theObject\->TraceConnect ("CourseChange", MakeCallback (&CourseChange)); .ft P .fi .UNINDENT .UNINDENT .sp It turns out that the internal code for \fBConfig::ConnectWithoutContext\fP and \fBConfig::Connect\fP actually find a \fBPtr\fP and call the appropriate \fBTraceConnect\fP method at the lowest level. .sp The \fBConfig\fP functions take a path that represents a chain of \fBObject\fP pointers. Each segment of a path corresponds to an Object Attribute. The last segment is the Attribute of interest, and prior segments must be typed to contain or find Objects. The \fBConfig\fP code parses and “walks” this path until it gets to the final segment of the path. It then interprets the last segment as an \fBAttribute\fP on the last Object it found while walking the path. The \fBConfig\fP functions then call the appropriate \fBTraceConnect\fP or \fBTraceConnectWithoutContext\fP method on the final Object. Let’s see what happens in a bit more detail when the above path is walked. .sp The leading “/” character in the path refers to a so\-called namespace. One of the predefined namespaces in the config system is “NodeList” which is a list of all of the nodes in the simulation. Items in the list are referred to by indices into the list, so “/NodeList/7” refers to the eighth Node in the list of nodes created during the simulation (recall indices start at \fI0’). This reference is actually a \(ga\(gaPtr\(ga\fP and so is a subclass of an \fBns3::Object\fP\&. .sp As described in the Object Model section of the \fIns\-3\fP Manual, we make widespread use of object aggregation. This allows us to form an association between different Objects without building a complicated inheritance tree or predeciding what objects will be part of a Node. Each Object in an Aggregation can be reached from the other Objects. .sp In our example the next path segment being walked begins with the “$” character. This indicates to the config system that the segment is the name of an object type, so a \fBGetObject\fP call should be made looking for that type. It turns out that the \fBMobilityHelper\fP used in \fBthird.cc\fP arranges to Aggregate, or associate, a mobility model to each of the wireless \fBNodes\fP\&. When you add the “$” you are asking for another Object that has presumably been previously aggregated. You can think of this as switching pointers from the original Ptr as specified by “/NodeList/7” to its associated mobility model — which is of type \fBns3::MobilityModel\fP\&. If you are familiar with \fBGetObject\fP, we have asked the system to do the following: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Ptr mobilityModel = node\->GetObject () .ft P .fi .UNINDENT .UNINDENT .sp We are now at the last Object in the path, so we turn our attention to the Attributes of that Object. The \fBMobilityModel\fP class defines an Attribute called “CourseChange”. You can see this by looking at the source code in \fBsrc/mobility/model/mobility\-model.cc\fP and searching for “CourseChange” in your favorite editor. You should find .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C \&.AddTraceSource ("CourseChange", "The value of the position and/or velocity vector changed", MakeTraceSourceAccessor (&MobilityModel::m_courseChangeTrace), "ns3::MobilityModel::CourseChangeCallback") .ft P .fi .UNINDENT .UNINDENT .sp which should look very familiar at this point. .sp If you look for the corresponding declaration of the underlying traced variable in \fBmobility\-model.h\fP you will find .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C TracedCallback > m_courseChangeTrace; .ft P .fi .UNINDENT .UNINDENT .sp The type declaration \fBTracedCallback\fP identifies \fBm_courseChangeTrace\fP as a special list of Callbacks that can be hooked using the Config functions described above. The \fBtypedef\fP for the callback function signature is also defined in the header file: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C typedef void (* CourseChangeCallback)(Ptr * model); .ft P .fi .UNINDENT .UNINDENT .sp The \fBMobilityModel\fP class is designed to be a base class providing a common interface for all of the specific subclasses. If you search down to the end of the file, you will see a method defined called \fBNotifyCourseChange()\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C void MobilityModel::NotifyCourseChange (void) const { m_courseChangeTrace(this); } .ft P .fi .UNINDENT .UNINDENT .sp Derived classes will call into this method whenever they do a course change to support tracing. This method invokes \fBoperator()\fP on the underlying \fBm_courseChangeTrace\fP, which will, in turn, invoke all of the registered Callbacks, calling all of the trace sinks that have registered interest in the trace source by calling a Config function. .sp So, in the \fBthird.cc\fP example we looked at, whenever a course change is made in one of the \fBRandomWalk2dMobilityModel\fP instances installed, there will be a \fBNotifyCourseChange()\fP call which calls up into the \fBMobilityModel\fP base class. As seen above, this invokes \fBoperator()\fP on \fBm_courseChangeTrace\fP, which in turn, calls any registered trace sinks. In the example, the only code registering an interest was the code that provided the Config path. Therefore, the \fBCourseChange\fP function that was hooked from Node number seven will be the only Callback called. .sp The final piece of the puzzle is the “context”. Recall that we saw an output looking something like the following from \fBthird.cc\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C /NodeList/7/$ns3::MobilityModel/CourseChange x = 7.27897, y = 2.22677 .ft P .fi .UNINDENT .UNINDENT .sp The first part of the output is the context. It is simply the path through which the config code located the trace source. In the case we have been looking at there can be any number of trace sources in the system corresponding to any number of nodes with mobility models. There needs to be some way to identify which trace source is actually the one that fired the Callback. The easy way is to connect with \fBConfig::Connect\fP, instead of \fBConfig::ConnectWithoutContext\fP\&. .SS Finding Sources .sp The first question that inevitably comes up for new users of the Tracing system is, \fI“Okay, I know that there must be trace sources in the simulation core, but how do I find out what trace sources are available to me?”\fP .sp The second question is, \fI“Okay, I found a trace source, how do I figure out the Config path to use when I connect to it?”\fP .sp The third question is, \fI“Okay, I found a trace source and the Config path, how do I figure out what the return type and formal arguments of my callback function need to be?”\fP .sp The fourth question is, \fI“Okay, I typed that all in and got this incredibly bizarre error message, what in the world does it mean?”\fP .sp We’ll address each of these in turn. .SS Available Sources .sp \fIOkay, I know that there must be trace sources in the simulation core, but how do I find out what trace sources are available to me?\fP .sp The answer to the first question is found in the \fIns\-3\fP API documentation. If you go to the project web site, \fI\%ns\-3 project\fP, you will find a link to “Documentation” in the navigation bar. If you select this link, you will be taken to our documentation page. There is a link to “Latest Release” that will take you to the documentation for the latest stable release of \fIns\-3\fP\&. If you select the “API Documentation” link, you will be taken to the \fIns\-3\fP API documentation page. .sp In the sidebar you should see a hierarchy that begins .INDENT 0.0 .IP \(bu 2 ns\-3 .UNINDENT .INDENT 0.0 .INDENT 3.5 .INDENT 0.0 .IP \(bu 2 ns\-3 Documentation .IP \(bu 2 All TraceSources .IP \(bu 2 All Attributes .IP \(bu 2 All GlobalValues .UNINDENT .UNINDENT .UNINDENT .sp The list of interest to us here is “All TraceSources”. Go ahead and select that link. You will see, perhaps not too surprisingly, a list of all of the trace sources available in \fIns\-3\fP\&. .sp As an example, scroll down to \fBns3::MobilityModel\fP\&. You will find an entry for .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C CourseChange: The value of the position and/or velocity vector changed .ft P .fi .UNINDENT .UNINDENT .sp You should recognize this as the trace source we used in the \fBthird.cc\fP example. Perusing this list will be helpful. .SS Config Paths .sp \fIOkay, I found a trace source, how do I figure out the Config path to use when I connect to it?\fP .sp If you know which object you are interested in, the “Detailed Description” section for the class will list all available trace sources. For example, starting from the list of “All TraceSources,” click on the \fBns3::MobilityModel\fP link, which will take you to the documentation for the \fBMobilityModel\fP class. Almost at the top of the page is a one line brief description of the class, ending in a link “More…”. Click on this link to skip the API summary and go to the “Detailed Description” of the class. At the end of the description will be (up to) three lists: .INDENT 0.0 .IP \(bu 2 \fBConfig Paths\fP: a list of typical Config paths for this class. .IP \(bu 2 \fBAttributes\fP: a list of all attributes supplied by this class. .IP \(bu 2 \fBTraceSources\fP: a list of all TraceSources available from this class. .UNINDENT .sp First we’ll discuss the Config paths. .sp Let’s assume that you have just found the “CourseChange” trace source in the “All TraceSources” list and you want to figure out how to connect to it. You know that you are using (again, from the \fBthird.cc\fP example) an \fBns3::RandomWalk2dMobilityModel\fP\&. So either click on the class name in the “All TraceSources” list, or find \fBns3::RandomWalk2dMobilityModel\fP in the “Class List”. Either way you should now be looking at the “ns3::RandomWalk2dMobilityModel Class Reference” page. .sp If you now scroll down to the “Detailed Description” section, after the summary list of class methods and attributes (or just click on the “More…” link at the end of the class brief description at the top of the page) you will see the overall documentation for the class. Continuing to scroll down, find the “Config Paths” list: .INDENT 0.0 .INDENT 3.5 \fBConfig Paths\fP .sp \fBns3::RandomWalk2dMobilityModel\fP is accessible through the following paths with \fBConfig::Set\fP and \fBConfig::Connect\fP: .INDENT 0.0 .IP \(bu 2 “/NodeList/[i]/$ns3::MobilityModel/$ns3::RandomWalk2dMobilityModel” .UNINDENT .UNINDENT .UNINDENT .sp The documentation tells you how to get to the \fBRandomWalk2dMobilityModel\fP Object. Compare the string above with the string we actually used in the example code: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C "/NodeList/7/$ns3::MobilityModel" .ft P .fi .UNINDENT .UNINDENT .sp The difference is due to the fact that two \fBGetObject\fP calls are implied in the string found in the documentation. The first, for \fB$ns3::MobilityModel\fP will query the aggregation for the base class. The second implied \fBGetObject\fP call, for \fB$ns3::RandomWalk2dMobilityModel\fP, is used to cast the base class to the concrete implementation class. The documentation shows both of these operations for you. It turns out that the actual trace source you are looking for is found in the base class. .sp Look further down in the “Detailed Description” section for the list of trace sources. You will find .INDENT 0.0 .INDENT 3.5 No TraceSources are defined for this type. .sp \fBTraceSources defined in parent class \(ga\(gans3::MobilityModel\(ga\(ga\fP .INDENT 0.0 .IP \(bu 2 \fBCourseChange\fP: The value of the position and/or velocity vector changed. .sp Callback signature: \fBns3::MobilityModel::CourseChangeCallback\fP .UNINDENT .UNINDENT .UNINDENT .sp This is exactly what you need to know. The trace source of interest is found in \fBns3::MobilityModel\fP (which you knew anyway). The interesting thing this bit of API Documentation tells you is that you don’t need that extra cast in the config path above to get to the concrete class, since the trace source is actually in the base class. Therefore the additional \fBGetObject\fP is not required and you simply use the path: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C "/NodeList/[i]/$ns3::MobilityModel" .ft P .fi .UNINDENT .UNINDENT .sp which perfectly matches the example path: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C "/NodeList/7/$ns3::MobilityModel" .ft P .fi .UNINDENT .UNINDENT .sp As an aside, another way to find the Config path is to \fBgrep\fP around in the \fIns\-3\fP codebase for someone who has already figured it out. You should always try to copy someone else’s working code before you start to write your own. Try something like: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ find . \-name \(aq*.cc\(aq | xargs grep CourseChange | grep Connect .ft P .fi .UNINDENT .UNINDENT .sp and you may find your answer along with working code. For example, in this case, \fBsrc/mobility/examples/main\-random\-topology.cc\fP has something just waiting for you to use: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Config::Connect ("/NodeList/*/$ns3::MobilityModel/CourseChange", MakeCallback (&CourseChange)); .ft P .fi .UNINDENT .UNINDENT .sp We’ll return to this example in a moment. .SS Callback Signatures .sp \fIOkay, I found a trace source and the Config path, how do I figure out what the return type and formal arguments of my callback function need to be?\fP .sp The easiest way is to examine the callback signature \fBtypedef\fP, which is given in the “Callback signature” of the trace source in the “Detailed Description” for the class, as shown above. .sp Repeating the “CourseChange” trace source entry from \fBns3::RandomWalk2dMobilityModel\fP we have: .INDENT 0.0 .INDENT 3.5 .INDENT 0.0 .IP \(bu 2 \fBCourseChange\fP: The value of the position and/or velocity vector changed. .sp Callback signature: \fBns3::MobilityModel::CourseChangeCallback\fP .UNINDENT .UNINDENT .UNINDENT .sp The callback signature is given as a link to the relevant \fBtypedef\fP, where we find .INDENT 0.0 .INDENT 3.5 \fBtypedef void (* CourseChangeCallback)(std::string context, Ptr * model);\fP .sp \fBTracedCallback\fP signature for course change notifications. .sp If the callback is connected using \fBConnectWithoutContext\fP omit the \fBcontext\fP argument from the signature. .sp \fBParameters\fP: .INDENT 0.0 .INDENT 3.5 .nf [in] context The context string supplied by the Trace source. [in] model The MobilityModel which is changing course. .fi .sp .UNINDENT .UNINDENT .UNINDENT .UNINDENT .sp As above, to see this in use \fBgrep\fP around in the \fIns\-3\fP codebase for an example. The example above, from \fBsrc/mobility/examples/main\-random\-topology.cc\fP, connects the “CourseChange” trace source to the \fBCourseChange\fP function in the same file: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C static void CourseChange (std::string context, Ptr model) { ... } .ft P .fi .UNINDENT .UNINDENT .sp Notice that this function: .INDENT 0.0 .IP \(bu 2 Takes a “context” string argument, which we’ll describe in a minute. (If the callback is connected using the \fBConnectWithoutContext\fP function the \fBcontext\fP argument will be omitted.) .IP \(bu 2 Has the \fBMobilityModel\fP supplied as the last argument (or only argument if \fBConnectWithoutContext\fP is used). .IP \(bu 2 Returns \fBvoid\fP\&. .UNINDENT .sp If, by chance, the callback signature hasn’t been documented, and there are no examples to work from, determining the right callback function signature can be, well, challenging to actually figure out from the source code. .sp Before embarking on a walkthrough of the code, I’ll be kind and just tell you a simple way to figure this out: The return value of your callback will always be \fBvoid\fP\&. The formal parameter list for a \fBTracedCallback\fP can be found from the template parameter list in the declaration. Recall that for our current example, this is in \fBmobility\-model.h\fP, where we have previously found: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C TracedCallback > m_courseChangeTrace; .ft P .fi .UNINDENT .UNINDENT .sp There is a one\-to\-one correspondence between the template parameter list in the declaration and the formal arguments of the callback function. Here, there is one template parameter, which is a \fBPtr\fP\&. This tells you that you need a function that returns void and takes a \fBPtr\fP\&. For example: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C void CourseChange (Ptr model) { ... } .ft P .fi .UNINDENT .UNINDENT .sp That’s all you need if you want to \fBConfig::ConnectWithoutContext\fP\&. If you want a context, you need to \fBConfig::Connect\fP and use a Callback function that takes a string context, then the template arguments: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C void CourseChange (std::string context, Ptr model) { ... } .ft P .fi .UNINDENT .UNINDENT .sp If you want to ensure that your \fBCourseChangeCallback\fP function is only visible in your local file, you can add the keyword \fBstatic\fP and come up with: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C static void CourseChange (std::string path, Ptr model) { ... } .ft P .fi .UNINDENT .UNINDENT .sp which is exactly what we used in the \fBthird.cc\fP example. .SS Implementation .sp This section is entirely optional. It is going to be a bumpy ride, especially for those unfamiliar with the details of templates. However, if you get through this, you will have a very good handle on a lot of the \fIns\-3\fP low level idioms. .sp So, again, let’s figure out what signature of callback function is required for the “CourseChange” trace source. This is going to be painful, but you only need to do this once. After you get through this, you will be able to just look at a \fBTracedCallback\fP and understand it. .sp The first thing we need to look at is the declaration of the trace source. Recall that this is in \fBmobility\-model.h\fP, where we have previously found: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C TracedCallback > m_courseChangeTrace; .ft P .fi .UNINDENT .UNINDENT .sp This declaration is for a template. The template parameter is inside the angle\-brackets, so we are really interested in finding out what that \fBTracedCallback<>\fP is. If you have absolutely no idea where this might be found, \fBgrep\fP is your friend. .sp We are probably going to be interested in some kind of declaration in the \fIns\-3\fP source, so first change into the \fBsrc\fP directory. Then, we know this declaration is going to have to be in some kind of header file, so just \fBgrep\fP for it using: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ find . \-name \(aq*.h\(aq | xargs grep TracedCallback .ft P .fi .UNINDENT .UNINDENT .sp You’ll see 303 lines fly by (I piped this through \fBwc\fP to see how bad it was). Although that may seem like a lot, that’s not really a lot. Just pipe the output through \fBmore\fP and start scanning through it. On the first page, you will see some very suspiciously template\-looking stuff. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C TracedCallback::TracedCallback () TracedCallback::ConnectWithoutContext (c ... TracedCallback::Connect (const CallbackB ... TracedCallback::DisconnectWithoutContext ... TracedCallback::Disconnect (const Callba ... TracedCallback::operator() (void) const ... TracedCallback::operator() (T1 a1) const ... TracedCallback::operator() (T1 a1, T2 a2 ... TracedCallback::operator() (T1 a1, T2 a2 ... TracedCallback::operator() (T1 a1, T2 a2 ... TracedCallback::operator() (T1 a1, T2 a2 ... TracedCallback::operator() (T1 a1, T2 a2 ... TracedCallback::operator() (T1 a1, T2 a2 ... .ft P .fi .UNINDENT .UNINDENT .sp It turns out that all of this comes from the header file \fBtraced\-callback.h\fP which sounds very promising. You can then take a look at \fBmobility\-model.h\fP and see that there is a line which confirms this hunch: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C #include "ns3/traced\-callback.h" .ft P .fi .UNINDENT .UNINDENT .sp Of course, you could have gone at this from the other direction and started by looking at the includes in \fBmobility\-model.h\fP and noticing the include of \fBtraced\-callback.h\fP and inferring that this must be the file you want. .sp In either case, the next step is to take a look at \fBsrc/core/model/traced\-callback.h\fP in your favorite editor to see what is happening. .sp You will see a comment at the top of the file that should be comforting: .INDENT 0.0 .INDENT 3.5 An ns3::TracedCallback has almost exactly the same API as a normal ns3::Callback but instead of forwarding calls to a single function (as an ns3::Callback normally does), it forwards calls to a chain of ns3::Callback. .UNINDENT .UNINDENT .sp This should sound very familiar and let you know you are on the right track. .sp Just after this comment, you will find .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C template class TracedCallback { ... .ft P .fi .UNINDENT .UNINDENT .sp This tells you that TracedCallback is a templated class. It has eight possible type parameters with default values. Go back and compare this with the declaration you are trying to understand: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C TracedCallback > m_courseChangeTrace; .ft P .fi .UNINDENT .UNINDENT .sp The \fBtypename T1\fP in the templated class declaration corresponds to the \fBPtr\fP in the declaration above. All of the other type parameters are left as defaults. Looking at the constructor really doesn’t tell you much. The one place where you have seen a connection made between your Callback function and the tracing system is in the \fBConnect\fP and \fBConnectWithoutContext\fP functions. If you scroll down, you will see a \fBConnectWithoutContext\fP method here: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C template void TracedCallback::ConnectWithoutContext ... { Callback cb; cb.Assign (callback); m_callbackList.push_back (cb); } .ft P .fi .UNINDENT .UNINDENT .sp You are now in the belly of the beast. When the template is instantiated for the declaration above, the compiler will replace \fBT1\fP with \fBPtr\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C void TracedCallback::ConnectWithoutContext ... cb { Callback > cb; cb.Assign (callback); m_callbackList.push_back (cb); } .ft P .fi .UNINDENT .UNINDENT .sp You can now see the implementation of everything we’ve been talking about. The code creates a Callback of the right type and assigns your function to it. This is the equivalent of the \fBpfi = MyFunction\fP we discussed at the start of this section. The code then adds the Callback to the list of Callbacks for this source. The only thing left is to look at the definition of Callback. Using the same \fBgrep\fP trick as we used to find \fBTracedCallback\fP, you will be able to find that the file \fB\&./core/callback.h\fP is the one we need to look at. .sp If you look down through the file, you will see a lot of probably almost incomprehensible template code. You will eventually come to some API Documentation for the Callback template class, though. Fortunately, there is some English: .INDENT 0.0 .INDENT 3.5 \fBCallback\fP template class. .sp This class template implements the Functor Design Pattern. It is used to declare the type of a \fBCallback\fP: .INDENT 0.0 .IP \(bu 2 the first non\-optional template argument represents the return type of the callback. .IP \(bu 2 the remaining (optional) template arguments represent the type of the subsequent arguments to the callback. .IP \(bu 2 up to nine arguments are supported. .UNINDENT .UNINDENT .UNINDENT .sp We are trying to figure out what the .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Callback > cb; .ft P .fi .UNINDENT .UNINDENT .sp declaration means. Now we are in a position to understand that the first (non\-optional) template argument, \fBvoid\fP, represents the return type of the Callback. The second (optional) template argument, \fBPtr\fP represents the type of the first argument to the callback. .sp The Callback in question is your function to receive the trace events. From this you can infer that you need a function that returns \fBvoid\fP and takes a \fBPtr\fP\&. For example, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C void CourseChangeCallback (Ptr model) { ... } .ft P .fi .UNINDENT .UNINDENT .sp That’s all you need if you want to \fBConfig::ConnectWithoutContext\fP\&. If you want a context, you need to \fBConfig::Connect\fP and use a Callback function that takes a string context. This is because the \fBConnect\fP function will provide the context for you. You’ll need: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C void CourseChangeCallback (std::string context, Ptr model) { ... } .ft P .fi .UNINDENT .UNINDENT .sp If you want to ensure that your \fBCourseChangeCallback\fP is only visible in your local file, you can add the keyword \fBstatic\fP and come up with: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C static void CourseChangeCallback (std::string path, Ptr model) { ... } .ft P .fi .UNINDENT .UNINDENT .sp which is exactly what we used in the \fBthird.cc\fP example. Perhaps you should now go back and reread the previous section (Take My Word for It). .sp If you are interested in more details regarding the implementation of Callbacks, feel free to take a look at the \fIns\-3\fP manual. They are one of the most frequently used constructs in the low\-level parts of \fIns\-3\fP\&. It is, in my opinion, a quite elegant thing. .SS TracedValues .sp Earlier in this section, we presented a simple piece of code that used a \fBTracedValue\fP to demonstrate the basics of the tracing code. We just glossed over the what a TracedValue really is and how to find the return type and formal arguments for the callback. .sp As we mentioned, the file, \fBtraced\-value.h\fP brings in the required declarations for tracing of data that obeys value semantics. In general, value semantics just means that you can pass the object itself around, rather than passing the address of the object. We extend that requirement to include the full set of assignment\-style operators that are pre\-defined for plain\-old\-data (POD) types: .INDENT 0.0 .INDENT 3.5 .TS center; |l|l|. _ T{ \fBoperator=\fP (assignment) T} _ T{ \fBoperator*=\fP T} T{ \fBoperator/=\fP T} _ T{ \fBoperator+=\fP T} T{ \fBoperator\-=\fP T} _ T{ \fBoperator++\fP (both prefix and postfix) T} _ T{ \fBoperator\-\-\fP (both prefix and postfix) T} _ T{ \fBoperator<<=\fP T} T{ \fBoperator>>=\fP T} _ T{ \fBoperator&=\fP T} T{ \fBoperator|=\fP T} _ T{ \fBoperator%=\fP T} T{ \fBoperator^=\fP T} _ .TE .UNINDENT .UNINDENT .sp What this all really means is that you will be able to trace all changes made using those operators to a C++ object which has value semantics. .sp The \fBTracedValue<>\fP declaration we saw above provides the infrastructure that overloads the operators mentioned above and drives the callback process. On use of any of the operators above with a \fBTracedValue\fP it will provide both the old and the new value of that variable, in this case an \fBint32_t\fP value. By inspection of the \fBTracedValue\fP declaration, we know the trace sink function will have arguments \fB(int32_t oldValue, int32_t newValue)\fP\&. The return type for a \fBTracedValue\fP callback function is always \fBvoid\fP, so the expected callback signature for the sink function \fBtraceSink\fP will be: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C void (* traceSink)(int32_t oldValue, int32_t newValue); .ft P .fi .UNINDENT .UNINDENT .sp The \fB\&.AddTraceSource\fP in the \fBGetTypeId\fP method provides the “hooks” used for connecting the trace source to the outside world through the Config system. We already discussed the first three arguments to \fBAddTraceSource\fP: the Attribute name for the Config system, a help string, and the address of the TracedValue class data member. .sp The final string argument, “ns3::TracedValueCallback::Int32” in the example, is the name of a \fBtypedef\fP for the callback function signature. We require these signatures to be defined, and give the fully qualified type name to \fBAddTraceSource\fP, so the API documentation can link a trace source to the function signature. For TracedValue the signature is straightforward; for TracedCallbacks we’ve already seen the API docs really help. .SS Real Example .sp Let’s do an example taken from one of the best\-known books on TCP around. “TCP/IP Illustrated, Volume 1: The Protocols,” by W. Richard Stevens is a classic. I just flipped the book open and ran across a nice plot of both the congestion window and sequence numbers versus time on page 366. Stevens calls this, “Figure 21.10. Value of cwnd and send sequence number while data is being transmitted.” Let’s just recreate the cwnd part of that plot in \fIns\-3\fP using the tracing system and \fBgnuplot\fP\&. .SS Available Sources .sp The first thing to think about is how we want to get the data out. What is it that we need to trace? So let’s consult “All Trace Sources” list to see what we have to work with. Recall that this is found in the \fIns\-3\fP API Documentation. If you scroll through the list, you will eventually find: .INDENT 0.0 .INDENT 3.5 \fBns3::TcpSocketBase\fP .INDENT 0.0 .IP \(bu 2 \fBCongestionWindow\fP: The TCP connection’s congestion window .IP \(bu 2 \fBSlowStartThreshold\fP: TCP slow start threshold (bytes) .UNINDENT .UNINDENT .UNINDENT .sp It turns out that the \fIns\-3\fP TCP implementation lives (mostly) in the file \fBsrc/internet/model/tcp\-socket\-base.cc\fP while congestion control variants are in files such as \fBsrc/internet/model/tcp\-bic.cc\fP\&. If you don’t know this \fIa priori\fP, you can use the recursive \fBgrep\fP trick: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ find . \-name \(aq*.cc\(aq | xargs grep \-i tcp .ft P .fi .UNINDENT .UNINDENT .sp You will find page after page of instances of tcp pointing you to that file. .sp Bringing up the class documentation for \fBTcpSocketBase\fP and skipping to the list of TraceSources you will find .INDENT 0.0 .INDENT 3.5 \fBTraceSources\fP .INDENT 0.0 .IP \(bu 2 \fBCongestionWindow\fP: The TCP connection’s congestion window .sp Callback signature: \fBns3::TracedValueCallback::Uint32\fP .UNINDENT .UNINDENT .UNINDENT .sp Clicking on the callback \fBtypedef\fP link we see the signature you now know to expect: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C typedef void(* ns3::TracedValueCallback::Int32)(int32_t oldValue, int32_t newValue) .ft P .fi .UNINDENT .UNINDENT .sp You should now understand this code completely. If we have a pointer to the \fBTcpSocketBase\fP object, we can \fBTraceConnect\fP to the “CongestionWindow” trace source if we provide an appropriate callback target. This is the same kind of trace source that we saw in the simple example at the start of this section, except that we are talking about \fBuint32_t\fP instead of \fBint32_t\fP\&. And we know that we have to provide a callback function with that signature. .SS Finding Examples .sp It’s always best to try and find working code laying around that you can modify, rather than starting from scratch. So the first order of business now is to find some code that already hooks the “CongestionWindow” trace source and see if we can modify it. As usual, \fBgrep\fP is your friend: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ find . \-name \(aq*.cc\(aq | xargs grep CongestionWindow .ft P .fi .UNINDENT .UNINDENT .sp This will point out a couple of promising candidates: \fBexamples/tcp/tcp\-large\-transfer.cc\fP and \fBsrc/test/ns3tcp/ns3tcp\-cwnd\-test\-suite.cc\fP\&. .sp We haven’t visited any of the test code yet, so let’s take a look there. You will typically find that test code is fairly minimal, so this is probably a very good bet. Open \fBsrc/test/ns3tcp/ns3tcp\-cwnd\-test\-suite.cc\fP in your favorite editor and search for “CongestionWindow”. You will find, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C ns3TcpSocket\->TraceConnectWithoutContext ("CongestionWindow", MakeCallback (&Ns3TcpCwndTestCase1::CwndChange, this)); .ft P .fi .UNINDENT .UNINDENT .sp This should look very familiar to you. We mentioned above that if we had a pointer to the \fBTcpSocketBase\fP, we could \fBTraceConnect\fP to the “CongestionWindow” trace source. That’s exactly what we have here; so it turns out that this line of code does exactly what we want. Let’s go ahead and extract the code we need from this function (\fBNs3TcpCwndTestCase1::DoRun (void)\fP). If you look at this function, you will find that it looks just like an \fIns\-3\fP script. It turns out that is exactly what it is. It is a script run by the test framework, so we can just pull it out and wrap it in \fBmain\fP instead of in \fBDoRun\fP\&. Rather than walk through this, step, by step, we have provided the file that results from porting this test back to a native \fIns\-3\fP script – \fBexamples/tutorial/fifth.cc\fP\&. .SS Dynamic Trace Sources .sp The \fBfifth.cc\fP example demonstrates an extremely important rule that you must understand before using any kind of trace source: you must ensure that the target of a \fBConfig::Connect\fP command exists before trying to use it. This is no different than saying an object must be instantiated before trying to call it. Although this may seem obvious when stated this way, it does trip up many people trying to use the system for the first time. .sp Let’s return to basics for a moment. There are three basic execution phases that exist in any \fIns\-3\fP script. The first phase is sometimes called “Configuration Time” or “Setup Time,” and exists during the period when the \fBmain\fP function of your script is running, but before \fBSimulator::Run\fP is called. The second phase is sometimes called “Simulation Time” and exists during the time period when \fBSimulator::Run\fP is actively executing its events. After it completes executing the simulation, \fBSimulator::Run\fP will return control back to the \fBmain\fP function. When this happens, the script enters what can be called the “Teardown Phase,” which is when the structures and objects created during setup are taken apart and released. .sp Perhaps the most common mistake made in trying to use the tracing system is assuming that entities constructed dynamically \fIduring simulation time\fP are available during configuration time. In particular, an \fIns\-3\fP \fBSocket\fP is a dynamic object often created by \fBApplications\fP to communicate between \fBNodes\fP\&. An \fIns\-3\fP \fBApplication\fP always has a “Start Time” and a “Stop Time” associated with it. In the vast majority of cases, an \fBApplication\fP will not attempt to create a dynamic object until its \fBStartApplication\fP method is called at some “Start Time”. This is to ensure that the simulation is completely configured before the app tries to do anything (what would happen if it tried to connect to a Node that didn’t exist yet during configuration time?). As a result, during the configuration phase you can’t connect a trace source to a trace sink if one of them is created dynamically during the simulation. .sp The two solutions to this conundrum are .INDENT 0.0 .IP 1. 3 Create a simulator event that is run after the dynamic object is created and hook the trace when that event is executed; or .IP 2. 3 Create the dynamic object at configuration time, hook it then, and give the object to the system to use during simulation time. .UNINDENT .sp We took the second approach in the \fBfifth.cc\fP example. This decision required us to create the \fBMyApp\fP \fBApplication\fP, the entire purpose of which is to take a \fBSocket\fP as a parameter. .SS Walkthrough: \fBfifth.cc\fP .sp Now, let’s take a look at the example program we constructed by dissecting the congestion window test. Open \fBexamples/tutorial/fifth.cc\fP in your favorite editor. You should see some familiar looking code: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C /* \-*\- Mode:C++; c\-file\-style:"gnu"; indent\-tabs\-mode:nil; \-*\- */ /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Include., 59 Temple Place, Suite 330, Boston, MA 02111\-1307 USA */ #include #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"); .ft P .fi .UNINDENT .UNINDENT .sp This has all been covered, so we won’t rehash it. The next lines of source are the network illustration and a comment addressing the problem described above with \fBSocket\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C // =========================================================================== // // node 0 node 1 // +\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ +\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ // | ns\-3 TCP | | ns\-3 TCP | // +\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ +\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ // | 10.1.1.1 | | 10.1.1.2 | // +\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ +\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ // | point\-to\-point | | point\-to\-point | // +\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ +\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ // | | // +\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ // 5 Mbps, 2 ms // // // We want to look at changes in the ns\-3 TCP congestion window. We need // to crank up a flow and hook the CongestionWindow attribute on the socket // of the sender. Normally one would use an on\-off application to generate a // flow, but this has a couple of problems. First, the socket of the on\-off // application is not created until Application Start time, so we wouldn\(aqt be // able to hook the socket (now) at configuration time. Second, even if we // could arrange a call after start time, the socket is not public so we // couldn\(aqt get at it. // // So, we can cook up a simple version of the on\-off application that does what // we want. On the plus side we don\(aqt need all of the complexity of the on\-off // application. On the minus side, we don\(aqt have a helper, so we have to get // a little more involved in the details, but this is trivial. // // So first, we create a socket and do the trace connect on it; then we pass // this socket into the constructor of our simple application which we then // install in the source node. // =========================================================================== // .ft P .fi .UNINDENT .UNINDENT .sp This should also be self\-explanatory. .sp The next part is the declaration of the \fBMyApp\fP \fBApplication\fP that we put together to allow the \fBSocket\fP to be created at configuration time. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C class MyApp : public Application { public: MyApp (); virtual ~MyApp(); void Setup (Ptr 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 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; }; .ft P .fi .UNINDENT .UNINDENT .sp You can see that this class inherits from the \fIns\-3\fP \fBApplication\fP class. Take a look at \fBsrc/network/model/application.h\fP if you are interested in what is inherited. The \fBMyApp\fP class is obligated to override the \fBStartApplication\fP and \fBStopApplication\fP methods. These methods are automatically called when \fBMyApp\fP is required to start and stop sending data during the simulation. .SS Starting/Stopping Applications .sp It is worthwhile to spend a bit of time explaining how events actually get started in the system. This is another fairly deep explanation, and can be ignored if you aren’t planning on venturing down into the guts of the system. It is useful, however, in that the discussion touches on how some very important parts of \fIns\-3\fP work and exposes some important idioms. If you are planning on implementing new models, you probably want to understand this section. .sp The most common way to start pumping events is to start an \fBApplication\fP\&. This is done as the result of the following (hopefully) familiar lines of an \fIns\-3\fP script: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C ApplicationContainer apps = ... apps.Start (Seconds (1.0)); apps.Stop (Seconds (10.0)); .ft P .fi .UNINDENT .UNINDENT .sp The application container code (see \fBsrc/network/helper/application\-container.h\fP if you are interested) loops through its contained applications and calls, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C app\->SetStartTime (startTime); .ft P .fi .UNINDENT .UNINDENT .sp as a result of the \fBapps.Start\fP call and .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C app\->SetStopTime (stopTime); .ft P .fi .UNINDENT .UNINDENT .sp as a result of the \fBapps.Stop\fP call. .sp The ultimate result of these calls is that we want to have the simulator automatically make calls into our \fBApplications\fP to tell them when to start and stop. In the case of \fBMyApp\fP, it inherits from class \fBApplication\fP and overrides \fBStartApplication\fP, and \fBStopApplication\fP\&. These are the functions that will be called by the simulator at the appropriate time. In the case of \fBMyApp\fP you will find that \fBMyApp::StartApplication\fP does the initial \fBBind\fP, and \fBConnect\fP on the socket, and then starts data flowing by calling \fBMyApp::SendPacket\fP\&. \fBMyApp::StopApplication\fP stops generating packets by cancelling any pending send events then closes the socket. .sp One of the nice things about \fIns\-3\fP is that you can completely ignore the implementation details of how your \fBApplication\fP is “automagically” called by the simulator at the correct time. But since we have already ventured deep into \fIns\-3\fP already, let’s go for it. .sp If you look at \fBsrc/network/model/application.cc\fP you will find that the \fBSetStartTime\fP method of an \fBApplication\fP just sets the member variable \fBm_startTime\fP and the \fBSetStopTime\fP method just sets \fBm_stopTime\fP\&. From there, without some hints, the trail will probably end. .sp The key to picking up the trail again is to know that there is a global list of all of the nodes in the system. Whenever you create a node in a simulation, a pointer to that Node is added to the global \fBNodeList\fP\&. .sp Take a look at \fBsrc/network/model/node\-list.cc\fP and search for \fBNodeList::Add\fP\&. The public static implementation calls into a private implementation called \fBNodeListPriv::Add\fP\&. This is a relatively common idom in \fIns\-3\fP\&. So, take a look at \fBNodeListPriv::Add\fP\&. There you will find, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Simulator::ScheduleWithContext (index, TimeStep (0), &Node::Initialize, node); .ft P .fi .UNINDENT .UNINDENT .sp This tells you that whenever a Node is created in a simulation, as a side\-effect, a call to that node’s \fBInitialize\fP method is scheduled for you that happens at time zero. Don’t read too much into that name, yet. It doesn’t mean that the Node is going to start doing anything, it can be interpreted as an informational call into the Node telling it that the simulation has started, not a call for action telling the Node to start doing something. .sp So, \fBNodeList::Add\fP indirectly schedules a call to \fBNode::Initialize\fP at time zero to advise a new Node that the simulation has started. If you look in \fBsrc/network/model/node.h\fP you will, however, not find a method called \fBNode::Initialize\fP\&. It turns out that the \fBInitialize\fP method is inherited from class \fBObject\fP\&. All objects in the system can be notified when the simulation starts, and objects of class Node are just one kind of those objects. .sp Take a look at \fBsrc/core/model/object.cc\fP next and search for \fBObject::Initialize\fP\&. This code is not as straightforward as you might have expected since \fIns\-3\fP \fBObjects\fP support aggregation. The code in \fBObject::Initialize\fP then loops through all of the objects that have been aggregated together and calls their \fBDoInitialize\fP method. This is another idiom that is very common in \fIns\-3\fP, sometimes called the “template design pattern.”: a public non\-virtual API method, which stays constant across implementations, and that calls a private virtual implementation method that is inherited and implemented by subclasses. The names are typically something like \fBMethodName\fP for the public API and \fBDoMethodName\fP for the private API. .sp This tells us that we should look for a \fBNode::DoInitialize\fP method in \fBsrc/network/model/node.cc\fP for the method that will continue our trail. If you locate the code, you will find a method that loops through all of the devices in the Node and then all of the applications in the Node calling \fBdevice\->Initialize\fP and \fBapplication\->Initialize\fP respectively. .sp You may already know that classes \fBDevice\fP and \fBApplication\fP both inherit from class \fBObject\fP and so the next step will be to look at what happens when \fBApplication::DoInitialize\fP is called. Take a look at \fBsrc/network/model/application.cc\fP and you will find: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C void Application::DoInitialize (void) { m_startEvent = Simulator::Schedule (m_startTime, &Application::StartApplication, this); if (m_stopTime != TimeStep (0)) { m_stopEvent = Simulator::Schedule (m_stopTime, &Application::StopApplication, this); } Object::DoInitialize (); } .ft P .fi .UNINDENT .UNINDENT .sp Here, we finally come to the end of the trail. If you have kept it all straight, when you implement an \fIns\-3\fP \fBApplication\fP, your new application inherits from class \fBApplication\fP\&. You override the \fBStartApplication\fP and \fBStopApplication\fP methods and provide mechanisms for starting and stopping the flow of data out of your new \fBApplication\fP\&. When a Node is created in the simulation, it is added to a global \fBNodeList\fP\&. The act of adding a Node to this \fBNodeList\fP causes a simulator event to be scheduled for time zero which calls the \fBNode::Initialize\fP method of the newly added Node to be called when the simulation starts. Since a Node inherits from \fBObject\fP, this calls the \fBObject::Initialize\fP method on the Node which, in turn, calls the \fBDoInitialize\fP methods on all of the \fBObjects\fP aggregated to the Node (think mobility models). Since the Node \fBObject\fP has overridden \fBDoInitialize\fP, that method is called when the simulation starts. The \fBNode::DoInitialize\fP method calls the \fBInitialize\fP methods of all of the \fBApplications\fP on the node. Since \fBApplications\fP are also \fBObjects\fP, this causes \fBApplication::DoInitialize\fP to be called. When \fBApplication::DoInitialize\fP is called, it schedules events for the \fBStartApplication\fP and \fBStopApplication\fP calls on the \fBApplication\fP\&. These calls are designed to start and stop the flow of data from the \fBApplication\fP .sp This has been another fairly long journey, but it only has to be made once, and you now understand another very deep piece of \fIns\-3\fP\&. .SS The MyApp Application .sp The \fBMyApp\fP \fBApplication\fP needs a constructor and a destructor, of course: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C 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; } .ft P .fi .UNINDENT .UNINDENT .sp The existence of the next bit of code is the whole reason why we wrote this \fBApplication\fP in the first place. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C void MyApp::Setup (Ptr 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; } .ft P .fi .UNINDENT .UNINDENT .sp This code should be pretty self\-explanatory. We are just initializing member variables. The important one from the perspective of tracing is the \fBPtr socket\fP which we needed to provide to the application during configuration time. Recall that we are going to create the \fBSocket\fP as a \fBTcpSocket\fP (which is implemented by \fBTcpSocketBase\fP) and hook its “CongestionWindow” trace source before passing it to the \fBSetup\fP method. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C void MyApp::StartApplication (void) { m_running = true; m_packetsSent = 0; m_socket\->Bind (); m_socket\->Connect (m_peer); SendPacket (); } .ft P .fi .UNINDENT .UNINDENT .sp The above code is the overridden implementation \fBApplication::StartApplication\fP that will be automatically called by the simulator to start our \fBApplication\fP running at the appropriate time. You can see that it does a \fBSocket\fP \fBBind\fP operation. If you are familiar with Berkeley Sockets this shouldn’t be a surprise. It performs the required work on the local side of the connection just as you might expect. The following \fBConnect\fP will do what is required to establish a connection with the TCP at \fBAddress\fP m_peer. It should now be clear why we need to defer a lot of this to simulation time, since the \fBConnect\fP is going to need a fully functioning network to complete. After the \fBConnect\fP, the \fBApplication\fP then starts creating simulation events by calling \fBSendPacket\fP\&. .sp The next bit of code explains to the \fBApplication\fP how to stop creating simulation events. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C void MyApp::StopApplication (void) { m_running = false; if (m_sendEvent.IsRunning ()) { Simulator::Cancel (m_sendEvent); } if (m_socket) { m_socket\->Close (); } } .ft P .fi .UNINDENT .UNINDENT .sp Every time a simulation event is scheduled, an \fBEvent\fP is created. If the \fBEvent\fP is pending execution or executing, its method \fBIsRunning\fP will return \fBtrue\fP\&. In this code, if \fBIsRunning()\fP returns true, we \fBCancel\fP the event which removes it from the simulator event queue. By doing this, we break the chain of events that the \fBApplication\fP is using to keep sending its \fBPackets\fP and the \fBApplication\fP goes quiet. After we quiet the \fBApplication\fP we \fBClose\fP the socket which tears down the TCP connection. .sp The socket is actually deleted in the destructor when the \fBm_socket = 0\fP is executed. This removes the last reference to the underlying Ptr which causes the destructor of that Object to be called. .sp Recall that \fBStartApplication\fP called \fBSendPacket\fP to start the chain of events that describes the \fBApplication\fP behavior. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C void MyApp::SendPacket (void) { Ptr packet = Create (m_packetSize); m_socket\->Send (packet); if (++m_packetsSent < m_nPackets) { ScheduleTx (); } } .ft P .fi .UNINDENT .UNINDENT .sp Here, you see that \fBSendPacket\fP does just that. It creates a \fBPacket\fP and then does a \fBSend\fP which, if you know Berkeley Sockets, is probably just what you expected to see. .sp It is the responsibility of the \fBApplication\fP to keep scheduling the chain of events, so the next lines call \fBScheduleTx\fP to schedule another transmit event (a \fBSendPacket\fP) until the \fBApplication\fP decides it has sent enough. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C void MyApp::ScheduleTx (void) { if (m_running) { Time tNext (Seconds (m_packetSize * 8 / static_cast (m_dataRate.GetBitRate ()))); m_sendEvent = Simulator::Schedule (tNext, &MyApp::SendPacket, this); } } .ft P .fi .UNINDENT .UNINDENT .sp Here, you see that \fBScheduleTx\fP does exactly that. If the \fBApplication\fP is running (if \fBStopApplication\fP has not been called) it will schedule a new event, which calls \fBSendPacket\fP again. The alert reader will spot something that also trips up new users. The data rate of an \fBApplication\fP is just that. It has nothing to do with the data rate of an underlying \fBChannel\fP\&. This is the rate at which the \fBApplication\fP produces bits. It does not take into account any overhead for the various protocols or channels that it uses to transport the data. If you set the data rate of an \fBApplication\fP to the same data rate as your underlying \fBChannel\fP you will eventually get a buffer overflow. .SS Trace Sinks .sp The whole point of this exercise is to get trace callbacks from TCP indicating the congestion window has been updated. The next piece of code implements the corresponding trace sink: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C static void CwndChange (uint32_t oldCwnd, uint32_t newCwnd) { NS_LOG_UNCOND (Simulator::Now ().GetSeconds () << "\et" << newCwnd); } .ft P .fi .UNINDENT .UNINDENT .sp This should be very familiar to you now, so we won’t dwell on the details. This function just logs the current simulation time and the new value of the congestion window every time it is changed. You can probably imagine that you could load the resulting output into a graphics program (gnuplot or Excel) and immediately see a nice graph of the congestion window behavior over time. .sp We added a new trace sink to show where packets are dropped. We are going to add an error model to this code also, so we wanted to demonstrate this working. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C static void RxDrop (Ptr p) { NS_LOG_UNCOND ("RxDrop at " << Simulator::Now ().GetSeconds ()); } .ft P .fi .UNINDENT .UNINDENT .sp This trace sink will be connected to the “PhyRxDrop” trace source of the point\-to\-point NetDevice. This trace source fires when a packet is dropped by the physical layer of a \fBNetDevice\fP\&. If you take a small detour to the source (\fBsrc/point\-to\-point/model/point\-to\-point\-net\-device.cc\fP) you will see that this trace source refers to \fBPointToPointNetDevice::m_phyRxDropTrace\fP\&. If you then look in \fBsrc/point\-to\-point/model/point\-to\-point\-net\-device.h\fP for this member variable, you will find that it is declared as a \fBTracedCallback >\fP\&. This should tell you that the callback target should be a function that returns void and takes a single parameter which is a \fBPtr\fP (assuming we use \fBConnectWithoutContext\fP) – just what we have above. .SS Main Program .sp The following code should be very familiar to you by now: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C 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); .ft P .fi .UNINDENT .UNINDENT .sp This creates two nodes with a point\-to\-point channel between them, just as shown in the illustration at the start of the file. .sp The next few lines of code show something new. If we trace a connection that behaves perfectly, we will end up with a monotonically increasing congestion window. To see any interesting behavior, we really want to introduce link errors which will drop packets, cause duplicate ACKs and trigger the more interesting behaviors of the congestion window. .sp \fIns\-3\fP provides \fBErrorModel\fP objects which can be attached to \fBChannels\fP\&. We are using the \fBRateErrorModel\fP which allows us to introduce errors into a \fBChannel\fP at a given \fIrate\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Ptr em = CreateObject (); em\->SetAttribute ("ErrorRate", DoubleValue (0.00001)); devices.Get (1)\->SetAttribute ("ReceiveErrorModel", PointerValue (em)); .ft P .fi .UNINDENT .UNINDENT .sp The above code instantiates a \fBRateErrorModel\fP Object, and we set the “ErrorRate” \fBAttribute\fP to the desired value. We then set the resulting instantiated \fBRateErrorModel\fP as the error model used by the point\-to\-point \fBNetDevice\fP\&. This will give us some retransmissions and make our plot a little more interesting. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C InternetStackHelper stack; stack.Install (nodes); Ipv4AddressHelper address; address.SetBase ("10.1.1.0", "255.255.255.252"); Ipv4InterfaceContainer interfaces = address.Assign (devices); .ft P .fi .UNINDENT .UNINDENT .sp The above code should be familiar. It installs internet stacks on our two nodes and creates interfaces and assigns IP addresses for the point\-to\-point devices. .sp Since we are using TCP, we need something on the destination Node to receive TCP connections and data. The \fBPacketSink\fP \fBApplication\fP is commonly used in \fIns\-3\fP for that purpose. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C uint16_t sinkPort = 8080; Address sinkAddress (InetSocketAddress(interfaces.GetAddress (1), sinkPort)); PacketSinkHelper packetSinkHelper ("ns3::TcpSocketFactory", InetSocketAddress (Ipv4Address::GetAny (), sinkPort)); ApplicationContainer sinkApps = packetSinkHelper.Install (nodes.Get (1)); sinkApps.Start (Seconds (0.)); sinkApps.Stop (Seconds (20.)); .ft P .fi .UNINDENT .UNINDENT .sp This should all be familiar, with the exception of, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C PacketSinkHelper packetSinkHelper ("ns3::TcpSocketFactory", InetSocketAddress (Ipv4Address::GetAny (), sinkPort)); .ft P .fi .UNINDENT .UNINDENT .sp This code instantiates a \fBPacketSinkHelper\fP and tells it to create sockets using the class \fBns3::TcpSocketFactory\fP\&. This class implements a design pattern called “object factory” which is a commonly used mechanism for specifying a class used to create objects in an abstract way. Here, instead of having to create the objects themselves, you provide the \fBPacketSinkHelper\fP a string that specifies a \fBTypeId\fP string used to create an object which can then be used, in turn, to create instances of the Objects created by the factory. .sp The remaining parameter tells the \fBApplication\fP which address and port it should \fBBind\fP to. .sp The next two lines of code will create the socket and connect the trace source. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Ptr ns3TcpSocket = Socket::CreateSocket (nodes.Get (0), TcpSocketFactory::GetTypeId ()); ns3TcpSocket\->TraceConnectWithoutContext ("CongestionWindow", MakeCallback (&CwndChange)); .ft P .fi .UNINDENT .UNINDENT .sp The first statement calls the static member function \fBSocket::CreateSocket\fP and provides a Node and an explicit \fBTypeId\fP for the object factory used to create the socket. This is a slightly lower level call than the \fBPacketSinkHelper\fP call above, and uses an explicit C++ type instead of one referred to by a string. Otherwise, it is conceptually the same thing. .sp Once the \fBTcpSocket\fP is created and attached to the Node, we can use \fBTraceConnectWithoutContext\fP to connect the CongestionWindow trace source to our trace sink. .sp Recall that we coded an \fBApplication\fP so we could take that \fBSocket\fP we just made (during configuration time) and use it in simulation time. We now have to instantiate that \fBApplication\fP\&. We didn’t go to any trouble to create a helper to manage the \fBApplication\fP so we are going to have to create and install it “manually”. This is actually quite easy: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Ptr app = CreateObject (); app\->Setup (ns3TcpSocket, sinkAddress, 1040, 1000, DataRate ("1Mbps")); nodes.Get (0)\->AddApplication (app); app\->Start (Seconds (1.)); app\->Stop (Seconds (20.)); .ft P .fi .UNINDENT .UNINDENT .sp The first line creates an \fBObject\fP of type \fBMyApp\fP – our \fBApplication\fP\&. The second line tells the \fBApplication\fP what \fBSocket\fP to use, what address to connect to, how much data to send at each send event, how many send events to generate and the rate at which to produce data from those events. .sp Next, we manually add the \fBMyApp Application\fP to the source Node and explicitly call the \fBStart\fP and \fBStop\fP methods on the \fBApplication\fP to tell it when to start and stop doing its thing. .sp We need to actually do the connect from the receiver point\-to\-point \fBNetDevice\fP drop event to our \fBRxDrop\fP callback now. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C devices.Get (1)\->TraceConnectWithoutContext("PhyRxDrop", MakeCallback (&RxDrop)); .ft P .fi .UNINDENT .UNINDENT .sp It should now be obvious that we are getting a reference to the receiving \fBNode NetDevice\fP from its container and connecting the trace source defined by the attribute “PhyRxDrop” on that device to the trace sink \fBRxDrop\fP\&. .sp Finally, we tell the simulator to override any \fBApplications\fP and just stop processing events at 20 seconds into the simulation. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Simulator::Stop (Seconds(20)); Simulator::Run (); Simulator::Destroy (); return 0; } .ft P .fi .UNINDENT .UNINDENT .sp Recall that as soon as \fBSimulator::Run\fP is called, configuration time ends, and simulation time begins. All of the work we orchestrated by creating the \fBApplication\fP and teaching it how to connect and send data actually happens during this function call. .sp As soon as \fBSimulator::Run\fP returns, the simulation is complete and we enter the teardown phase. In this case, \fBSimulator::Destroy\fP takes care of the gory details and we just return a success code after it completes. .SS Running \fBfifth.cc\fP .sp Since we have provided the file \fBfifth.cc\fP for you, if you have built your distribution (in debug mode since it uses \fBNS_LOG\fP – recall that optimized builds optimize out \fBNS_LOG\fP) it will be waiting for you to run. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./waf \-\-run fifth Waf: Entering directory \(ga/home/craigdo/repos/ns\-3\-allinone\-dev/ns\-3\-dev/build\(aq Waf: Leaving directory \(ga/home/craigdo/repos/ns\-3\-allinone\-dev/ns\-3\-dev/build\(aq \(aqbuild\(aq finished successfully (0.684s) 1 536 1.0093 1072 1.01528 1608 1.02167 2144 \&... 1.11319 8040 1.12151 8576 1.12983 9112 RxDrop at 1.13696 \&... .ft P .fi .UNINDENT .UNINDENT .sp You can probably see immediately a downside of using prints of any kind in your traces. We get those extraneous waf messages printed all over our interesting information along with those RxDrop messages. We will remedy that soon, but I’m sure you can’t wait to see the results of all of this work. Let’s redirect that output to a file called \fBcwnd.dat\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./waf \-\-run fifth > cwnd.dat 2>&1 .ft P .fi .UNINDENT .UNINDENT .sp Now edit up “cwnd.dat” in your favorite editor and remove the waf build status and drop lines, leaving only the traced data (you could also comment out the \fBTraceConnectWithoutContext("PhyRxDrop", MakeCallback (&RxDrop));\fP in the script to get rid of the drop prints just as easily. .sp You can now run gnuplot (if you have it installed) and tell it to generate some pretty pictures: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ gnuplot gnuplot> set terminal png size 640,480 gnuplot> set output "cwnd.png" gnuplot> plot "cwnd.dat" using 1:2 title \(aqCongestion Window\(aq with linespoints gnuplot> exit .ft P .fi .UNINDENT .UNINDENT .sp You should now have a graph of the congestion window versus time sitting in the file “cwnd.png” that looks like: .INDENT 0.0 .INDENT 2.5 [image] .UNINDENT .UNINDENT .SS Using Mid\-Level Helpers .sp In the previous section, we showed how to hook a trace source and get hopefully interesting information out of a simulation. Perhaps you will recall that we called logging to the standard output using \fBstd::cout\fP a “blunt instrument” much earlier in this chapter. We also wrote about how it was a problem having to parse the log output in order to isolate interesting information. It may have occurred to you that we just spent a lot of time implementing an example that exhibits all of the problems we purport to fix with the \fIns\-3\fP tracing system! You would be correct. But, bear with us. We’re not done yet. .sp One of the most important things we want to do is to have the ability to easily control the amount of output coming out of the simulation; and we also want to save those data to a file so we can refer back to it later. We can use the mid\-level trace helpers provided in \fIns\-3\fP to do just that and complete the picture. .sp We provide a script that writes the cwnd change and drop events developed in the example \fBfifth.cc\fP to disk in separate files. The cwnd changes are stored as a tab\-separated ASCII file and the drop events are stored in a PCAP file. The changes to make this happen are quite small. .SS Walkthrough: \fBsixth.cc\fP .sp Let’s take a look at the changes required to go from \fBfifth.cc\fP to \fBsixth.cc\fP\&. Open \fBexamples/tutorial/sixth.cc\fP in your favorite editor. You can see the first change by searching for CwndChange. You will find that we have changed the signatures for the trace sinks and have added a single line to each sink that writes the traced information to a stream representing a file. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C static void CwndChange (Ptr stream, uint32_t oldCwnd, uint32_t newCwnd) { NS_LOG_UNCOND (Simulator::Now ().GetSeconds () << "\et" << newCwnd); *stream\->GetStream () << Simulator::Now ().GetSeconds () << "\et" << oldCwnd << "\et" << newCwnd << std::endl; } static void RxDrop (Ptr file, Ptr p) { NS_LOG_UNCOND ("RxDrop at " << Simulator::Now ().GetSeconds ()); file\->Write(Simulator::Now(), p); } .ft P .fi .UNINDENT .UNINDENT .sp We have added a “stream” parameter to the \fBCwndChange\fP trace sink. This is an object that holds (keeps safely alive) a C++ output stream. It turns out that this is a very simple object, but one that manages lifetime issues for the stream and solves a problem that even experienced C++ users run into. It turns out that the copy constructor for \fBstd::ostream\fP is marked private. This means that \fBstd::ostreams\fP do not obey value semantics and cannot be used in any mechanism that requires the stream to be copied. This includes the \fIns\-3\fP callback system, which as you may recall, requires objects that obey value semantics. Further notice that we have added the following line in the \fBCwndChange\fP trace sink implementation: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C *stream\->GetStream () << Simulator::Now ().GetSeconds () << "\et" << oldCwnd << "\et" << newCwnd << std::endl; .ft P .fi .UNINDENT .UNINDENT .sp This would be very familiar code if you replaced \fB*stream\->GetStream ()\fP with \fBstd::cout\fP, as in: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C std::cout << Simulator::Now ().GetSeconds () << "\et" << oldCwnd << "\et" << newCwnd << std::endl; .ft P .fi .UNINDENT .UNINDENT .sp This illustrates that the \fBPtr\fP is really just carrying around a \fBstd::ofstream\fP for you, and you can use it here like any other output stream. .sp A similar situation happens in \fBRxDrop\fP except that the object being passed around (a \fBPtr\fP) represents a PCAP file. There is a one\-liner in the trace sink to write a timestamp and the contents of the packet being dropped to the PCAP file: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C file\->Write(Simulator::Now(), p); .ft P .fi .UNINDENT .UNINDENT .sp Of course, if we have objects representing the two files, we need to create them somewhere and also cause them to be passed to the trace sinks. If you look in the \fBmain\fP function, you will find new code to do just that: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C AsciiTraceHelper asciiTraceHelper; Ptr stream = asciiTraceHelper.CreateFileStream ("sixth.cwnd"); ns3TcpSocket\->TraceConnectWithoutContext ("CongestionWindow", MakeBoundCallback (&CwndChange, stream)); \&... PcapHelper pcapHelper; Ptr file = pcapHelper.CreateFile ("sixth.pcap", std::ios::out, PcapHelper::DLT_PPP); devices.Get (1)\->TraceConnectWithoutContext("PhyRxDrop", MakeBoundCallback (&RxDrop, file)); .ft P .fi .UNINDENT .UNINDENT .sp In the first section of the code snippet above, we are creating the ASCII trace file, creating an object responsible for managing it and using a variant of the callback creation function to arrange for the object to be passed to the sink. Our ASCII trace helpers provide a rich set of functions to make using text (ASCII) files easy. We are just going to illustrate the use of the file stream creation function here. .sp The \fBCreateFileStream\fP function is basically going to instantiate a \fBstd::ofstream\fP object and create a new file (or truncate an existing file). This \fBstd::ofstream\fP is packaged up in an \fIns\-3\fP object for lifetime management and copy constructor issue resolution. .sp We then take this \fIns\-3\fP object representing the file and pass it to \fBMakeBoundCallback()\fP\&. This function creates a callback just like \fBMakeCallback()\fP, but it “binds” a new value to the callback. This value is added as the first argument to the callback before it is called. .sp Essentially, \fBMakeBoundCallback(&CwndChange, stream)\fP causes the trace source to add the additional “stream” parameter to the front of the formal parameter list before invoking the callback. This changes the required signature of the \fBCwndChange\fP sink to match the one shown above, which includes the “extra” parameter \fBPtr stream\fP\&. .sp In the second section of code in the snippet above, we instantiate a \fBPcapHelper\fP to do the same thing for our PCAP trace file that we did with the \fBAsciiTraceHelper\fP\&. The line of code, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Ptr file = pcapHelper.CreateFile ("sixth.pcap", "w", PcapHelper::DLT_PPP); .ft P .fi .UNINDENT .UNINDENT .sp creates a PCAP file named “sixth.pcap” with file mode “w”. This means that the new file is truncated (contents deleted) if an existing file with that name is found. The final parameter is the “data link type” of the new PCAP file. These are the same as the PCAP library data link types defined in \fBbpf.h\fP if you are familiar with PCAP. In this case, \fBDLT_PPP\fP indicates that the PCAP file is going to contain packets prefixed with point to point headers. This is true since the packets are coming from our point\-to\-point device driver. Other common data link types are DLT_EN10MB (10 MB Ethernet) appropriate for csma devices and DLT_IEEE802_11 (IEEE 802.11) appropriate for wifi devices. These are defined in \fBsrc/network/helper/trace\-helper.h\fP if you are interested in seeing the list. The entries in the list match those in \fBbpf.h\fP but we duplicate them to avoid a PCAP source dependence. .sp A \fIns\-3\fP object representing the PCAP file is returned from \fBCreateFile\fP and used in a bound callback exactly as it was in the ASCII case. .sp An important detour: It is important to notice that even though both of these objects are declared in very similar ways, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Ptr file ... Ptr stream ... .ft P .fi .UNINDENT .UNINDENT .sp The underlying objects are entirely different. For example, the \fBPtr\fP is a smart pointer to an \fIns\-3\fP Object that is a fairly heavyweight thing that supports Attributes and is integrated into the Config system. The \fBPtr\fP, on the other hand, is a smart pointer to a reference counted object that is a very lightweight thing. Remember to look at the object you are referencing before making any assumptions about the “powers” that object may have. .sp For example, take a look at \fBsrc/network/utils/pcap\-file\-wrapper.h\fP in the distribution and notice, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C class PcapFileWrapper : public Object .ft P .fi .UNINDENT .UNINDENT .sp that class \fBPcapFileWrapper\fP is an \fIns\-3\fP Object by virtue of its inheritance. Then look at \fBsrc/network/model/output\-stream\-wrapper.h\fP and notice, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C class OutputStreamWrapper : public SimpleRefCount .ft P .fi .UNINDENT .UNINDENT .sp that this object is not an \fIns\-3\fP Object at all, it is “merely” a C++ object that happens to support intrusive reference counting. .sp The point here is that just because you read \fBPtr\fP it does not necessarily mean that \fBsomething\fP is an \fIns\-3\fP Object on which you can hang \fIns\-3\fP Attributes, for example. .sp Now, back to the example. If you build and run this example, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ ./waf \-\-run sixth .ft P .fi .UNINDENT .UNINDENT .sp you will see the same messages appear as when you ran “fifth”, but two new files will appear in the top\-level directory of your \fIns\-3\fP distribution. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C sixth.cwnd sixth.pcap .ft P .fi .UNINDENT .UNINDENT .sp Since “sixth.cwnd” is an ASCII text file, you can view it with \fBcat\fP or your favorite file viewer. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C 1 0 536 1.0093 536 1072 1.01528 1072 1608 1.02167 1608 2144 \&... 9.69256 5149 5204 9.89311 5204 5259 .ft P .fi .UNINDENT .UNINDENT .sp You have a tab separated file with a timestamp, an old congestion window and a new congestion window suitable for directly importing into your plot program. There are no extraneous prints in the file, no parsing or editing is required. .sp Since “sixth.pcap” is a PCAP file, you can fiew it with \fBtcpdump\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C reading from file sixth.pcap, link\-type PPP (PPP) 1.136956 IP 10.1.1.1.49153 > 10.1.1.2.8080: Flags [.], seq 17177:17681, ack 1, win 32768, options [TS val 1133 ecr 1127,eol], length 504 1.403196 IP 10.1.1.1.49153 > 10.1.1.2.8080: Flags [.], seq 33280:33784, ack 1, win 32768, options [TS val 1399 ecr 1394,eol], length 504 \&... 7.426220 IP 10.1.1.1.49153 > 10.1.1.2.8080: Flags [.], seq 785704:786240, ack 1, win 32768, options [TS val 7423 ecr 7421,eol], length 536 9.630693 IP 10.1.1.1.49153 > 10.1.1.2.8080: Flags [.], seq 882688:883224, ack 1, win 32768, options [TS val 9620 ecr 9618,eol], length 536 .ft P .fi .UNINDENT .UNINDENT .sp You have a PCAP file with the packets that were dropped in the simulation. There are no other packets present in the file and there is nothing else present to make life difficult. .sp It’s been a long journey, but we are now at a point where we can appreciate the \fIns\-3\fP tracing system. We have pulled important events out of the middle of a TCP implementation and a device driver. We stored those events directly in files usable with commonly known tools. We did this without modifying any of the core code involved, and we did this in only 18 lines of code: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C static void CwndChange (Ptr stream, uint32_t oldCwnd, uint32_t newCwnd) { NS_LOG_UNCOND (Simulator::Now ().GetSeconds () << "\et" << newCwnd); *stream\->GetStream () << Simulator::Now ().GetSeconds () << "\et" << oldCwnd << "\et" << newCwnd << std::endl; } \&... AsciiTraceHelper asciiTraceHelper; Ptr stream = asciiTraceHelper.CreateFileStream ("sixth.cwnd"); ns3TcpSocket\->TraceConnectWithoutContext ("CongestionWindow", MakeBoundCallback (&CwndChange, stream)); \&... static void RxDrop (Ptr file, Ptr p) { NS_LOG_UNCOND ("RxDrop at " << Simulator::Now ().GetSeconds ()); file\->Write(Simulator::Now(), p); } \&... PcapHelper pcapHelper; Ptr file = pcapHelper.CreateFile ("sixth.pcap", "w", PcapHelper::DLT_PPP); devices.Get (1)\->TraceConnectWithoutContext("PhyRxDrop", MakeBoundCallback (&RxDrop, file)); .ft P .fi .UNINDENT .UNINDENT .SS Trace Helpers .sp The \fIns\-3\fP trace helpers provide a rich environment for configuring and selecting different trace events and writing them to files. In previous sections, primarily \fI\%Building Topologies\fP, we have seen several varieties of the trace helper methods designed for use inside other (device) helpers. .sp Perhaps you will recall seeing some of these variations: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C pointToPoint.EnablePcapAll ("second"); pointToPoint.EnablePcap ("second", p2pNodes.Get (0)\->GetId (), 0); csma.EnablePcap ("third", csmaDevices.Get (0), true); pointToPoint.EnableAsciiAll (ascii.CreateFileStream ("myfirst.tr")); .ft P .fi .UNINDENT .UNINDENT .sp What may not be obvious, though, is that there is a consistent model for all of the trace\-related methods found in the system. We will now take a little time and take a look at the “big picture”. .sp There are currently two primary use cases of the tracing helpers in \fIns\-3\fP: device helpers and protocol helpers. Device helpers look at the problem of specifying which traces should be enabled through a (node, device) pair. For example, you may want to specify that PCAP tracing should be enabled on a particular device on a specific node. This follows from the \fIns\-3\fP device conceptual model, and also the conceptual models of the various device helpers. Following naturally from this, the files created follow a \fB\-\-\fP naming convention. .sp Protocol helpers look at the problem of specifying which traces should be enabled through a protocol and interface pair. This follows from the \fIns\-3\fP protocol stack conceptual model, and also the conceptual models of internet stack helpers. Naturally, the trace files should follow a \fB\-\-\fP naming convention. .sp The trace helpers therefore fall naturally into a two\-dimensional taxonomy. There are subtleties that prevent all four classes from behaving identically, but we do strive to make them all work as similarly as possible; and whenever possible there are analogs for all methods in all classes. .INDENT 0.0 .INDENT 3.5 .TS center; |l|l|l|. _ T{ T} T{ PCAP T} T{ ASCII T} _ T{ Device Helper T} T{ \echeckmark T} T{ \echeckmark T} _ T{ Protocol Helper T} T{ \echeckmark T} T{ \echeckmark T} _ .TE .UNINDENT .UNINDENT .sp We use an approach called a \fBmixin\fP to add tracing functionality to our helper classes. A \fBmixin\fP is a class that provides functionality when it is inherited by a subclass. Inheriting from a mixin is not considered a form of specialization but is really a way to collect functionality. .sp Let’s take a quick look at all four of these cases and their respective \fBmixins\fP\&. .SS Device Helpers .SS PCAP .sp The goal of these helpers is to make it easy to add a consistent PCAP trace facility to an \fIns\-3\fP device. We want all of the various flavors of PCAP tracing to work the same across all devices, so the methods of these helpers are inherited by device helpers. Take a look at \fBsrc/network/helper/trace\-helper.h\fP if you want to follow the discussion while looking at real code. .sp The class \fBPcapHelperForDevice\fP is a \fBmixin\fP provides the high level functionality for using PCAP tracing in an \fIns\-3\fP device. Every device must implement a single virtual method inherited from this class. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C virtual void EnablePcapInternal (std::string prefix, Ptr nd, bool promiscuous, bool explicitFilename) = 0; .ft P .fi .UNINDENT .UNINDENT .sp The signature of this method reflects the device\-centric view of the situation at this level. All of the public methods inherited from class \fBPcapUserHelperForDevice\fP reduce to calling this single device\-dependent implementation method. For example, the lowest level PCAP method, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C void EnablePcap (std::string prefix, Ptr nd, bool promiscuous = false, bool explicitFilename = false); .ft P .fi .UNINDENT .UNINDENT .sp will call the device implementation of \fBEnablePcapInternal\fP directly. All other public PCAP tracing methods build on this implementation to provide additional user\-level functionality. What this means to the user is that all device helpers in the system will have all of the PCAP trace methods available; and these methods will all work in the same way across devices if the device implements \fBEnablePcapInternal\fP correctly. .SS Methods .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C void EnablePcap (std::string prefix, Ptr nd, bool promiscuous = false, bool explicitFilename = false); void EnablePcap (std::string prefix, std::string ndName, bool promiscuous = false, bool explicitFilename = false); void EnablePcap (std::string prefix, NetDeviceContainer d, bool promiscuous = false); void EnablePcap (std::string prefix, NodeContainer n, bool promiscuous = false); void EnablePcap (std::string prefix, uint32_t nodeid, uint32_t deviceid, bool promiscuous = false); void EnablePcapAll (std::string prefix, bool promiscuous = false); .ft P .fi .UNINDENT .UNINDENT .sp In each of the methods shown above, there is a default parameter called \fBpromiscuous\fP that defaults to \fBfalse\fP\&. This parameter indicates that the trace should not be gathered in promiscuous mode. If you do want your traces to include all traffic seen by the device (and if the device supports a promiscuous mode) simply add a true parameter to any of the calls above. For example, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Ptr nd; \&... helper.EnablePcap ("prefix", nd, true); .ft P .fi .UNINDENT .UNINDENT .sp will enable promiscuous mode captures on the \fBNetDevice\fP specified by \fBnd\fP\&. .sp The first two methods also include a default parameter called \fBexplicitFilename\fP that will be discussed below. .sp You are encouraged to peruse the API Documentation for class \fBPcapHelperForDevice\fP to find the details of these methods; but to summarize … .INDENT 0.0 .IP \(bu 2 You can enable PCAP tracing on a particular node/net\-device pair by providing a \fBPtr\fP to an \fBEnablePcap\fP method. The \fBPtr\fP is implicit since the net device must belong to exactly one Node. For example, .INDENT 2.0 .INDENT 3.5 .sp .nf .ft C Ptr nd; \&... helper.EnablePcap ("prefix", nd); .ft P .fi .UNINDENT .UNINDENT .IP \(bu 2 You can enable PCAP tracing on a particular node/net\-device pair by providing a \fBstd::string\fP representing an object name service string to an \fBEnablePcap\fP method. The \fBPtr\fP is looked up from the name string. Again, the \fB\fP is implicit since the named net device must belong to exactly one Node. For example, .INDENT 2.0 .INDENT 3.5 .sp .nf .ft C Names::Add ("server" ...); Names::Add ("server/eth0" ...); \&... helper.EnablePcap ("prefix", "server/ath0"); .ft P .fi .UNINDENT .UNINDENT .IP \(bu 2 You can enable PCAP tracing on a collection of node/net\-device pairs by providing a \fBNetDeviceContainer\fP\&. For each \fBNetDevice\fP in the container the type is checked. For each device of the proper type (the same type as is managed by the device helper), tracing is enabled. Again, the \fB\fP is implicit since the found net device must belong to exactly one Node. For example, .INDENT 2.0 .INDENT 3.5 .sp .nf .ft C NetDeviceContainer d = ...; \&... helper.EnablePcap ("prefix", d); .ft P .fi .UNINDENT .UNINDENT .IP \(bu 2 You can enable PCAP tracing on a collection of node/net\-device pairs by providing a \fBNodeContainer\fP\&. For each Node in the \fBNodeContainer\fP its attached \fBNetDevices\fP are iterated. For each \fBNetDevice\fP attached to each Node in the container, the type of that device is checked. For each device of the proper type (the same type as is managed by the device helper), tracing is enabled. .INDENT 2.0 .INDENT 3.5 .sp .nf .ft C NodeContainer n; \&... helper.EnablePcap ("prefix", n); .ft P .fi .UNINDENT .UNINDENT .IP \(bu 2 You can enable PCAP tracing on the basis of Node ID and device ID as well as with explicit \fBPtr\fP\&. Each Node in the system has an integer Node ID and each device connected to a Node has an integer device ID. .INDENT 2.0 .INDENT 3.5 .sp .nf .ft C helper.EnablePcap ("prefix", 21, 1); .ft P .fi .UNINDENT .UNINDENT .IP \(bu 2 Finally, you can enable PCAP tracing for all devices in the system, with the same type as that managed by the device helper. .INDENT 2.0 .INDENT 3.5 .sp .nf .ft C helper.EnablePcapAll ("prefix"); .ft P .fi .UNINDENT .UNINDENT .UNINDENT .SS Filenames .sp Implicit in the method descriptions above is the construction of a complete filename by the implementation method. By convention, PCAP traces in the \fIns\-3\fP system are of the form \fB\-\-.pcap\fP .sp As previously mentioned, every Node in the system will have a system\-assigned Node id; and every device will have an interface index (also called a device id) relative to its node. By default, then, a PCAP trace file created as a result of enabling tracing on the first device of Node 21 using the prefix “prefix” would be \fBprefix\-21\-1.pcap\fP\&. .sp You can always use the \fIns\-3\fP object name service to make this more clear. For example, if you use the object name service to assign the name “server” to Node 21, the resulting PCAP trace file name will automatically become, \fBprefix\-server\-1.pcap\fP and if you also assign the name “eth0” to the device, your PCAP file name will automatically pick this up and be called \fBprefix\-server\-eth0.pcap\fP\&. .sp Finally, two of the methods shown above, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C void EnablePcap (std::string prefix, Ptr nd, bool promiscuous = false, bool explicitFilename = false); void EnablePcap (std::string prefix, std::string ndName, bool promiscuous = false, bool explicitFilename = false); .ft P .fi .UNINDENT .UNINDENT .sp have a default parameter called \fBexplicitFilename\fP\&. When set to true, this parameter disables the automatic filename completion mechanism and allows you to create an explicit filename. This option is only available in the methods which enable PCAP tracing on a single device. .sp For example, in order to arrange for a device helper to create a single promiscuous PCAP capture file of a specific name \fBmy\-pcap\-file.pcap\fP on a given device, one could: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Ptr nd; \&... helper.EnablePcap ("my\-pcap\-file.pcap", nd, true, true); .ft P .fi .UNINDENT .UNINDENT .sp The first \fBtrue\fP parameter enables promiscuous mode traces and the second tells the helper to interpret the \fBprefix\fP parameter as a complete filename. .SS ASCII .sp The behavior of the ASCII trace helper \fBmixin\fP is substantially similar to the PCAP version. Take a look at \fBsrc/network/helper/trace\-helper.h\fP if you want to follow the discussion while looking at real code. .sp The class \fBAsciiTraceHelperForDevice\fP adds the high level functionality for using ASCII tracing to a device helper class. As in the PCAP case, every device must implement a single virtual method inherited from the ASCII trace \fBmixin\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C virtual void EnableAsciiInternal (Ptr stream, std::string prefix, Ptr nd, bool explicitFilename) = 0; .ft P .fi .UNINDENT .UNINDENT .sp The signature of this method reflects the device\-centric view of the situation at this level; and also the fact that the helper may be writing to a shared output stream. All of the public ASCII\-trace\-related methods inherited from class \fBAsciiTraceHelperForDevice\fP reduce to calling this single device\- dependent implementation method. For example, the lowest level ascii trace methods, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C void EnableAscii (std::string prefix, Ptr nd, bool explicitFilename = false); void EnableAscii (Ptr stream, Ptr nd); .ft P .fi .UNINDENT .UNINDENT .sp will call the device implementation of \fBEnableAsciiInternal\fP directly, providing either a valid prefix or stream. All other public ASCII tracing methods will build on these low\-level functions to provide additional user\-level functionality. What this means to the user is that all device helpers in the system will have all of the ASCII trace methods available; and these methods will all work in the same way across devices if the devices implement \fBEnableAsciiInternal\fP correctly. .SS Methods .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C void EnableAscii (std::string prefix, Ptr nd, bool explicitFilename = false); void EnableAscii (Ptr stream, Ptr nd); void EnableAscii (std::string prefix, std::string ndName, bool explicitFilename = false); void EnableAscii (Ptr stream, std::string ndName); void EnableAscii (std::string prefix, NetDeviceContainer d); void EnableAscii (Ptr stream, NetDeviceContainer d); void EnableAscii (std::string prefix, NodeContainer n); void EnableAscii (Ptr stream, NodeContainer n); void EnableAsciiAll (std::string prefix); void EnableAsciiAll (Ptr stream); void EnableAscii (std::string prefix, uint32_t nodeid, uint32_t deviceid, bool explicitFilename); void EnableAscii (Ptr stream, uint32_t nodeid, uint32_t deviceid); .ft P .fi .UNINDENT .UNINDENT .sp You are encouraged to peruse the API Documentation for class \fBAsciiTraceHelperForDevice\fP to find the details of these methods; but to summarize … .INDENT 0.0 .IP \(bu 2 There are twice as many methods available for ASCII tracing as there were for PCAP tracing. This is because, in addition to the PCAP\-style model where traces from each unique node/device pair are written to a unique file, we support a model in which trace information for many node/device pairs is written to a common file. This means that the \-\- file name generation mechanism is replaced by a mechanism to refer to a common file; and the number of API methods is doubled to allow all combinations. .IP \(bu 2 Just as in PCAP tracing, you can enable ASCII tracing on a particular (node, net\-device) pair by providing a \fBPtr\fP to an \fBEnableAscii\fP method. The \fBPtr\fP is implicit since the net device must belong to exactly one Node. For example, .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Ptr nd; \&... helper.EnableAscii ("prefix", nd); .ft P .fi .UNINDENT .UNINDENT .INDENT 0.0 .IP \(bu 2 The first four methods also include a default parameter called \fBexplicitFilename\fP that operate similar to equivalent parameters in the PCAP case. .sp In this case, no trace contexts are written to the ASCII trace file since they would be redundant. The system will pick the file name to be created using the same rules as described in the PCAP section, except that the file will have the suffix \fB\&.tr\fP instead of \fB\&.pcap\fP\&. .IP \(bu 2 If you want to enable ASCII tracing on more than one net device and have all traces sent to a single file, you can do that as well by using an object to refer to a single file. We have already seen this in the “cwnd” example above: .INDENT 2.0 .INDENT 3.5 .sp .nf .ft C Ptr nd1; Ptr nd2; \&... Ptr stream = asciiTraceHelper.CreateFileStream ("trace\-file\-name.tr"); \&... helper.EnableAscii (stream, nd1); helper.EnableAscii (stream, nd2); .ft P .fi .UNINDENT .UNINDENT .sp In this case, trace contexts \fIare\fP written to the ASCII trace file since they are required to disambiguate traces from the two devices. Note that since the user is completely specifying the file name, the string should include the \fB,tr\fP suffix for consistency. .IP \(bu 2 You can enable ASCII tracing on a particular (node, net\-device) pair by providing a \fBstd::string\fP representing an object name service string to an \fBEnablePcap\fP method. The \fBPtr\fP is looked up from the name string. Again, the \fB\fP is implicit since the named net device must belong to exactly one Node. For example, .INDENT 2.0 .INDENT 3.5 .sp .nf .ft C Names::Add ("client" ...); Names::Add ("client/eth0" ...); Names::Add ("server" ...); Names::Add ("server/eth0" ...); \&... helper.EnableAscii ("prefix", "client/eth0"); helper.EnableAscii ("prefix", "server/eth0"); .ft P .fi .UNINDENT .UNINDENT .sp This would result in two files named \fBprefix\-client\-eth0.tr\fP and \fBprefix\-server\-eth0.tr\fP with traces for each device in the respective trace file. Since all of the \fBEnableAscii\fP functions are overloaded to take a stream wrapper, you can use that form as well: .INDENT 2.0 .INDENT 3.5 .sp .nf .ft C Names::Add ("client" ...); Names::Add ("client/eth0" ...); Names::Add ("server" ...); Names::Add ("server/eth0" ...); \&... Ptr stream = asciiTraceHelper.CreateFileStream ("trace\-file\-name.tr"); \&... helper.EnableAscii (stream, "client/eth0"); helper.EnableAscii (stream, "server/eth0"); .ft P .fi .UNINDENT .UNINDENT .sp This would result in a single trace file called \fBtrace\-file\-name.tr\fP that contains all of the trace events for both devices. The events would be disambiguated by trace context strings. .IP \(bu 2 You can enable ASCII tracing on a collection of (node, net\-device) pairs by providing a \fBNetDeviceContainer\fP\&. For each \fBNetDevice\fP in the container the type is checked. For each device of the proper type (the same type as is managed by the device helper), tracing is enabled. Again, the \fB\fP is implicit since the found net device must belong to exactly one Node. For example, .INDENT 2.0 .INDENT 3.5 .sp .nf .ft C NetDeviceContainer d = ...; \&... helper.EnableAscii ("prefix", d); .ft P .fi .UNINDENT .UNINDENT .sp This would result in a number of ASCII trace files being created, each of which follows the \fB\-\-.tr\fP convention. .sp Combining all of the traces into a single file is accomplished similarly to the examples above: .INDENT 2.0 .INDENT 3.5 .sp .nf .ft C NetDeviceContainer d = ...; \&... Ptr stream = asciiTraceHelper.CreateFileStream ("trace\-file\-name.tr"); \&... helper.EnableAscii (stream, d); .ft P .fi .UNINDENT .UNINDENT .IP \(bu 2 You can enable ASCII tracing on a collection of (node, net\-device) pairs by providing a \fBNodeContainer\fP\&. For each Node in the \fBNodeContainer\fP its attached \fBNetDevices\fP are iterated. For each \fBNetDevice\fP attached to each Node in the container, the type of that device is checked. For each device of the proper type (the same type as is managed by the device helper), tracing is enabled. .INDENT 2.0 .INDENT 3.5 .sp .nf .ft C NodeContainer n; \&... helper.EnableAscii ("prefix", n); .ft P .fi .UNINDENT .UNINDENT .sp This would result in a number of ASCII trace files being created, each of which follows the \fB\-\-.tr\fP convention. Combining all of the traces into a single file is accomplished similarly to the examples above. .IP \(bu 2 You can enable ASCII tracing on the basis of Node ID and device ID as well as with explicit \fBPtr\fP\&. Each Node in the system has an integer Node ID and each device connected to a Node has an integer device ID. .INDENT 2.0 .INDENT 3.5 .sp .nf .ft C helper.EnableAscii ("prefix", 21, 1); .ft P .fi .UNINDENT .UNINDENT .sp Of course, the traces can be combined into a single file as shown above. .IP \(bu 2 Finally, you can enable ASCII tracing for all devices in the system, with the same type as that managed by the device helper. .INDENT 2.0 .INDENT 3.5 .sp .nf .ft C helper.EnableAsciiAll ("prefix"); .ft P .fi .UNINDENT .UNINDENT .sp This would result in a number of ASCII trace files being created, one for every device in the system of the type managed by the helper. All of these files will follow the \fB\-\-.tr\fP convention. Combining all of the traces into a single file is accomplished similarly to the examples above. .UNINDENT .SS Filenames .sp Implicit in the prefix\-style method descriptions above is the construction of the complete filenames by the implementation method. By convention, ASCII traces in the \fIns\-3\fP system are of the form \fB\-\-.tr\fP .sp As previously mentioned, every Node in the system will have a system\-assigned Node id; and every device will have an interface index (also called a device id) relative to its node. By default, then, an ASCII trace file created as a result of enabling tracing on the first device of Node 21, using the prefix “prefix”, would be \fBprefix\-21\-1.tr\fP\&. .sp You can always use the \fIns\-3\fP object name service to make this more clear. For example, if you use the object name service to assign the name “server” to Node 21, the resulting ASCII trace file name will automatically become, \fBprefix\-server\-1.tr\fP and if you also assign the name “eth0” to the device, your ASCII trace file name will automatically pick this up and be called \fBprefix\-server\-eth0.tr\fP\&. .sp Several of the methods have a default parameter called \fBexplicitFilename\fP\&. When set to true, this parameter disables the automatic filename completion mechanism and allows you to create an explicit filename. This option is only available in the methods which take a prefix and enable tracing on a single device. .SS Protocol Helpers .SS PCAP .sp The goal of these \fBmixins\fP is to make it easy to add a consistent PCAP trace facility to protocols. We want all of the various flavors of PCAP tracing to work the same across all protocols, so the methods of these helpers are inherited by stack helpers. Take a look at \fBsrc/network/helper/trace\-helper.h\fP if you want to follow the discussion while looking at real code. .sp In this section we will be illustrating the methods as applied to the protocol \fBIpv4\fP\&. To specify traces in similar protocols, just substitute the appropriate type. For example, use a \fBPtr\fP instead of a \fBPtr\fP and call \fBEnablePcapIpv6\fP instead of \fBEnablePcapIpv4\fP\&. .sp The class \fBPcapHelperForIpv4\fP provides the high level functionality for using PCAP tracing in the \fBIpv4\fP protocol. Each protocol helper enabling these methods must implement a single virtual method inherited from this class. There will be a separate implementation for \fBIpv6\fP, for example, but the only difference will be in the method names and signatures. Different method names are required to disambiguate class \fBIpv4\fP from \fBIpv6\fP which are both derived from class \fBObject\fP, and methods that share the same signature. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C virtual void EnablePcapIpv4Internal (std::string prefix, Ptr ipv4, uint32_t interface, bool explicitFilename) = 0; .ft P .fi .UNINDENT .UNINDENT .sp The signature of this method reflects the protocol and interface\-centric view of the situation at this level. All of the public methods inherited from class \fBPcapHelperForIpv4\fP reduce to calling this single device\-dependent implementation method. For example, the lowest level PCAP method, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C void EnablePcapIpv4 (std::string prefix, Ptr ipv4, uint32_t interface, bool explicitFilename = false); .ft P .fi .UNINDENT .UNINDENT .sp will call the device implementation of \fBEnablePcapIpv4Internal\fP directly. All other public PCAP tracing methods build on this implementation to provide additional user\-level functionality. What this means to the user is that all protocol helpers in the system will have all of the PCAP trace methods available; and these methods will all work in the same way across protocols if the helper implements \fBEnablePcapIpv4Internal\fP correctly. .SS Methods .sp These methods are designed to be in one\-to\-one correspondence with the Node\- and \fBNetDevice\fP\- centric versions of the device versions. Instead of Node and \fBNetDevice\fP pair constraints, we use protocol and interface constraints. .sp Note that just like in the device version, there are six methods: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C void EnablePcapIpv4 (std::string prefix, Ptr ipv4, uint32_t interface, bool explicitFilename = false); void EnablePcapIpv4 (std::string prefix, std::string ipv4Name, uint32_t interface, bool explicitFilename = false); void EnablePcapIpv4 (std::string prefix, Ipv4InterfaceContainer c); void EnablePcapIpv4 (std::string prefix, NodeContainer n); void EnablePcapIpv4 (std::string prefix, uint32_t nodeid, uint32_t interface, bool explicitFilename); void EnablePcapIpv4All (std::string prefix); .ft P .fi .UNINDENT .UNINDENT .sp You are encouraged to peruse the API Documentation for class \fBPcapHelperForIpv4\fP to find the details of these methods; but to summarize … .INDENT 0.0 .IP \(bu 2 You can enable PCAP tracing on a particular protocol/interface pair by providing a \fBPtr\fP and \fBinterface\fP to an \fBEnablePcap\fP method. For example, .INDENT 2.0 .INDENT 3.5 .sp .nf .ft C Ptr ipv4 = node\->GetObject (); \&... helper.EnablePcapIpv4 ("prefix", ipv4, 0); .ft P .fi .UNINDENT .UNINDENT .IP \(bu 2 You can enable PCAP tracing on a particular node/net\-device pair by providing a \fBstd::string\fP representing an object name service string to an \fBEnablePcap\fP method. The \fBPtr\fP is looked up from the name string. For example, .INDENT 2.0 .INDENT 3.5 .sp .nf .ft C Names::Add ("serverIPv4" ...); \&... helper.EnablePcapIpv4 ("prefix", "serverIpv4", 1); .ft P .fi .UNINDENT .UNINDENT .IP \(bu 2 You can enable PCAP tracing on a collection of protocol/interface pairs by providing an \fBIpv4InterfaceContainer\fP\&. For each \fBIpv4\fP / interface pair in the container the protocol type is checked. For each protocol of the proper type (the same type as is managed by the device helper), tracing is enabled for the corresponding interface. For example, .INDENT 2.0 .INDENT 3.5 .sp .nf .ft C NodeContainer nodes; \&... NetDeviceContainer devices = deviceHelper.Install (nodes); \&... Ipv4AddressHelper ipv4; ipv4.SetBase ("10.1.1.0", "255.255.255.0"); Ipv4InterfaceContainer interfaces = ipv4.Assign (devices); \&... helper.EnablePcapIpv4 ("prefix", interfaces); .ft P .fi .UNINDENT .UNINDENT .IP \(bu 2 You can enable PCAP tracing on a collection of protocol/interface pairs by providing a \fBNodeContainer\fP\&. For each Node in the \fBNodeContainer\fP the appropriate protocol is found. For each protocol, its interfaces are enumerated and tracing is enabled on the resulting pairs. For example, .INDENT 2.0 .INDENT 3.5 .sp .nf .ft C NodeContainer n; \&... helper.EnablePcapIpv4 ("prefix", n); .ft P .fi .UNINDENT .UNINDENT .IP \(bu 2 You can enable PCAP tracing on the basis of Node ID and interface as well. In this case, the node\-id is translated to a \fBPtr\fP and the appropriate protocol is looked up in the node. The resulting protocol and interface are used to specify the resulting trace source. .INDENT 2.0 .INDENT 3.5 .sp .nf .ft C helper.EnablePcapIpv4 ("prefix", 21, 1); .ft P .fi .UNINDENT .UNINDENT .IP \(bu 2 Finally, you can enable PCAP tracing for all interfaces in the system, with associated protocol being the same type as that managed by the device helper. .INDENT 2.0 .INDENT 3.5 .sp .nf .ft C helper.EnablePcapIpv4All ("prefix"); .ft P .fi .UNINDENT .UNINDENT .UNINDENT .SS Filenames .sp Implicit in all of the method descriptions above is the construction of the complete filenames by the implementation method. By convention, PCAP traces taken for devices in the \fIns\-3\fP system are of the form “\-\-.pcap”. In the case of protocol traces, there is a one\-to\-one correspondence between protocols and \fBNodes\fP\&. This is because protocol \fBObjects\fP are aggregated to \fBNode Objects\fP\&. Since there is no global protocol id in the system, we use the corresponding Node id in file naming. Therefore there is a possibility for file name collisions in automatically chosen trace file names. For this reason, the file name convention is changed for protocol traces. .sp As previously mentioned, every Node in the system will have a system\-assigned Node id. Since there is a one\-to\-one correspondence between protocol instances and Node instances we use the Node id. Each interface has an interface id relative to its protocol. We use the convention “\-n\-i.pcap” for trace file naming in protocol helpers. .sp Therefore, by default, a PCAP trace file created as a result of enabling tracing on interface 1 of the Ipv4 protocol of Node 21 using the prefix “prefix” would be “prefix\-n21\-i1.pcap”. .sp You can always use the \fIns\-3\fP object name service to make this more clear. For example, if you use the object name service to assign the name “serverIpv4” to the Ptr on Node 21, the resulting PCAP trace file name will automatically become, “prefix\-nserverIpv4\-i1.pcap”. .sp Several of the methods have a default parameter called \fBexplicitFilename\fP\&. When set to true, this parameter disables the automatic filename completion mechanism and allows you to create an explicit filename. This option is only available in the methods which take a prefix and enable tracing on a single device. .SS ASCII .sp The behavior of the ASCII trace helpers is substantially similar to the PCAP case. Take a look at \fBsrc/network/helper/trace\-helper.h\fP if you want to follow the discussion while looking at real code. .sp In this section we will be illustrating the methods as applied to the protocol \fBIpv4\fP\&. To specify traces in similar protocols, just substitute the appropriate type. For example, use a \fBPtr\fP instead of a \fBPtr\fP and call \fBEnableAsciiIpv6\fP instead of \fBEnableAsciiIpv4\fP\&. .sp The class \fBAsciiTraceHelperForIpv4\fP adds the high level functionality for using ASCII tracing to a protocol helper. Each protocol that enables these methods must implement a single virtual method inherited from this class. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C virtual void EnableAsciiIpv4Internal (Ptr stream, std::string prefix, Ptr ipv4, uint32_t interface, bool explicitFilename) = 0; .ft P .fi .UNINDENT .UNINDENT .sp The signature of this method reflects the protocol\- and interface\-centric view of the situation at this level; and also the fact that the helper may be writing to a shared output stream. All of the public methods inherited from class \fBPcapAndAsciiTraceHelperForIpv4\fP reduce to calling this single device\- dependent implementation method. For example, the lowest level ASCII trace methods, .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C void EnableAsciiIpv4 (std::string prefix, Ptr ipv4, uint32_t interface, bool explicitFilename = false); void EnableAsciiIpv4 (Ptr stream, Ptr ipv4, uint32_t interface); .ft P .fi .UNINDENT .UNINDENT .sp will call the device implementation of \fBEnableAsciiIpv4Internal\fP directly, providing either the prefix or the stream. All other public ASCII tracing methods will build on these low\-level functions to provide additional user\-level functionality. What this means to the user is that all device helpers in the system will have all of the ASCII trace methods available; and these methods will all work in the same way across protocols if the protocols implement \fBEnableAsciiIpv4Internal\fP correctly. .SS Methods .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C void EnableAsciiIpv4 (std::string prefix, Ptr ipv4, uint32_t interface, bool explicitFilename = false); void EnableAsciiIpv4 (Ptr stream, Ptr ipv4, uint32_t interface); void EnableAsciiIpv4 (std::string prefix, std::string ipv4Name, uint32_t interface, bool explicitFilename = false); void EnableAsciiIpv4 (Ptr stream, std::string ipv4Name, uint32_t interface); void EnableAsciiIpv4 (std::string prefix, Ipv4InterfaceContainer c); void EnableAsciiIpv4 (Ptr stream, Ipv4InterfaceContainer c); void EnableAsciiIpv4 (std::string prefix, NodeContainer n); void EnableAsciiIpv4 (Ptr stream, NodeContainer n); void EnableAsciiIpv4All (std::string prefix); void EnableAsciiIpv4All (Ptr stream); void EnableAsciiIpv4 (std::string prefix, uint32_t nodeid, uint32_t deviceid, bool explicitFilename); void EnableAsciiIpv4 (Ptr stream, uint32_t nodeid, uint32_t interface); .ft P .fi .UNINDENT .UNINDENT .sp You are encouraged to peruse the API Documentation for class \fBPcapAndAsciiHelperForIpv4\fP to find the details of these methods; but to summarize … .INDENT 0.0 .IP \(bu 2 There are twice as many methods available for ASCII tracing as there were for PCAP tracing. This is because, in addition to the PCAP\-style model where traces from each unique protocol/interface pair are written to a unique file, we support a model in which trace information for many protocol/interface pairs is written to a common file. This means that the \-n\- file name generation mechanism is replaced by a mechanism to refer to a common file; and the number of API methods is doubled to allow all combinations. .IP \(bu 2 Just as in PCAP tracing, you can enable ASCII tracing on a particular protocol/interface pair by providing a \fBPtr\fP and an \fBinterface\fP to an \fBEnableAscii\fP method. For example, .INDENT 2.0 .INDENT 3.5 .sp .nf .ft C Ptr ipv4; \&... helper.EnableAsciiIpv4 ("prefix", ipv4, 1); .ft P .fi .UNINDENT .UNINDENT .sp In this case, no trace contexts are written to the ASCII trace file since they would be redundant. The system will pick the file name to be created using the same rules as described in the PCAP section, except that the file will have the suffix “.tr” instead of “.pcap”. .IP \(bu 2 If you want to enable ASCII tracing on more than one interface and have all traces sent to a single file, you can do that as well by using an object to refer to a single file. We have already something similar to this in the “cwnd” example above: .INDENT 2.0 .INDENT 3.5 .sp .nf .ft C Ptr protocol1 = node1\->GetObject (); Ptr protocol2 = node2\->GetObject (); \&... Ptr stream = asciiTraceHelper.CreateFileStream ("trace\-file\-name.tr"); \&... helper.EnableAsciiIpv4 (stream, protocol1, 1); helper.EnableAsciiIpv4 (stream, protocol2, 1); .ft P .fi .UNINDENT .UNINDENT .sp In this case, trace contexts are written to the ASCII trace file since they are required to disambiguate traces from the two interfaces. Note that since the user is completely specifying the file name, the string should include the “,tr” for consistency. .IP \(bu 2 You can enable ASCII tracing on a particular protocol by providing a \fBstd::string\fP representing an object name service string to an \fBEnablePcap\fP method. The \fBPtr\fP is looked up from the name string. The \fB\fP in the resulting filenames is implicit since there is a one\-to\-one correspondence between protocol instances and nodes, For example, .INDENT 2.0 .INDENT 3.5 .sp .nf .ft C Names::Add ("node1Ipv4" ...); Names::Add ("node2Ipv4" ...); \&... helper.EnableAsciiIpv4 ("prefix", "node1Ipv4", 1); helper.EnableAsciiIpv4 ("prefix", "node2Ipv4", 1); .ft P .fi .UNINDENT .UNINDENT .sp This would result in two files named “prefix\-nnode1Ipv4\-i1.tr” and “prefix\-nnode2Ipv4\-i1.tr” with traces for each interface in the respective trace file. Since all of the EnableAscii functions are overloaded to take a stream wrapper, you can use that form as well: .INDENT 2.0 .INDENT 3.5 .sp .nf .ft C Names::Add ("node1Ipv4" ...); Names::Add ("node2Ipv4" ...); \&... Ptr stream = asciiTraceHelper.CreateFileStream ("trace\-file\-name.tr"); \&... helper.EnableAsciiIpv4 (stream, "node1Ipv4", 1); helper.EnableAsciiIpv4 (stream, "node2Ipv4", 1); .ft P .fi .UNINDENT .UNINDENT .sp This would result in a single trace file called “trace\-file\-name.tr” that contains all of the trace events for both interfaces. The events would be disambiguated by trace context strings. .IP \(bu 2 You can enable ASCII tracing on a collection of protocol/interface pairs by providing an \fBIpv4InterfaceContainer\fP\&. For each protocol of the proper type (the same type as is managed by the device helper), tracing is enabled for the corresponding interface. Again, the \fB\fP is implicit since there is a one\-to\-one correspondence between each protocol and its node. For example, .INDENT 2.0 .INDENT 3.5 .sp .nf .ft C NodeContainer nodes; \&... NetDeviceContainer devices = deviceHelper.Install (nodes); \&... Ipv4AddressHelper ipv4; ipv4.SetBase ("10.1.1.0", "255.255.255.0"); Ipv4InterfaceContainer interfaces = ipv4.Assign (devices); \&... \&... helper.EnableAsciiIpv4 ("prefix", interfaces); .ft P .fi .UNINDENT .UNINDENT .sp This would result in a number of ASCII trace files being created, each of which follows the \-n\-i.tr convention. Combining all of the traces into a single file is accomplished similarly to the examples above: .INDENT 2.0 .INDENT 3.5 .sp .nf .ft C NodeContainer nodes; \&... NetDeviceContainer devices = deviceHelper.Install (nodes); \&... Ipv4AddressHelper ipv4; ipv4.SetBase ("10.1.1.0", "255.255.255.0"); Ipv4InterfaceContainer interfaces = ipv4.Assign (devices); \&... Ptr stream = asciiTraceHelper.CreateFileStream ("trace\-file\-name.tr"); \&... helper.EnableAsciiIpv4 (stream, interfaces); .ft P .fi .UNINDENT .UNINDENT .IP \(bu 2 You can enable ASCII tracing on a collection of protocol/interface pairs by providing a \fBNodeContainer\fP\&. For each Node in the \fBNodeContainer\fP the appropriate protocol is found. For each protocol, its interfaces are enumerated and tracing is enabled on the resulting pairs. For example, .INDENT 2.0 .INDENT 3.5 .sp .nf .ft C NodeContainer n; \&... helper.EnableAsciiIpv4 ("prefix", n); .ft P .fi .UNINDENT .UNINDENT .sp This would result in a number of ASCII trace files being created, each of which follows the \-\-.tr convention. Combining all of the traces into a single file is accomplished similarly to the examples above. .IP \(bu 2 You can enable ASCII tracing on the basis of Node ID and device ID as well. In this case, the node\-id is translated to a \fBPtr\fP and the appropriate protocol is looked up in the node. The resulting protocol and interface are used to specify the resulting trace source. .INDENT 2.0 .INDENT 3.5 .sp .nf .ft C helper.EnableAsciiIpv4 ("prefix", 21, 1); .ft P .fi .UNINDENT .UNINDENT .sp Of course, the traces can be combined into a single file as shown above. .IP \(bu 2 Finally, you can enable ASCII tracing for all interfaces in the system, with associated protocol being the same type as that managed by the device helper. .INDENT 2.0 .INDENT 3.5 .sp .nf .ft C helper.EnableAsciiIpv4All ("prefix"); .ft P .fi .UNINDENT .UNINDENT .sp This would result in a number of ASCII trace files being created, one for every interface in the system related to a protocol of the type managed by the helper. All of these files will follow the \-n\-i\-\-.tr” .sp As previously mentioned, every Node in the system will have a system\-assigned Node id. Since there is a one\-to\-one correspondence between protocols and nodes we use to node\-id to identify the protocol identity. Every interface on a given protocol will have an interface index (also called simply an interface) relative to its protocol. By default, then, an ASCII trace file created as a result of enabling tracing on the first device of Node 21, using the prefix “prefix”, would be “prefix\-n21\-i1.tr”. Use the prefix to disambiguate multiple protocols per node. .sp You can always use the \fIns\-3\fP object name service to make this more clear. For example, if you use the object name service to assign the name “serverIpv4” to the protocol on Node 21, and also specify interface one, the resulting ASCII trace file name will automatically become, “prefix\-nserverIpv4\-1.tr”. .sp Several of the methods have a default parameter called \fBexplicitFilename\fP\&. When set to true, this parameter disables the automatic filename completion mechanism and allows you to create an explicit filename. This option is only available in the methods which take a prefix and enable tracing on a single device. .SS Summary .sp \fIns\-3\fP includes an extremely rich environment allowing users at several levels to customize the kinds of information that can be extracted from simulations. .sp There are high\-level helper functions that allow users to simply control the collection of pre\-defined outputs to a fine granularity. There are mid\-level helper functions to allow more sophisticated users to customize how information is extracted and saved; and there are low\-level core functions to allow expert users to alter the system to present new and previously unexported information in a way that will be immediately accessible to users at higher levels. .sp This is a very comprehensive system, and we realize that it is a lot to digest, especially for new users or those not intimately familiar with C++ and its idioms. We do consider the tracing system a very important part of \fIns\-3\fP and so recommend becoming as familiar as possible with it. It is probably the case that understanding the rest of the \fIns\-3\fP system will be quite simple once you have mastered the tracing system .SH DATA COLLECTION .sp Our final tutorial chapter introduces some components that were added to \fIns\-3\fP in version 3.18, and that are still under development. This tutorial section is also a work\-in\-progress. .SS Motivation .sp One of the main points of running simulations is to generate output data, either for research purposes or simply to learn about the system. In the previous chapter, we introduced the tracing subsystem and the example \fBsixth.cc\fP\&. from which PCAP or ASCII trace files are generated. These traces are valuable for data analysis using a variety of external tools, and for many users, such output data is a preferred means of gathering data (for analysis by external tools). .sp However, there are also use cases for more than trace file generation, including the following: .INDENT 0.0 .IP \(bu 2 generation of data that does not map well to PCAP or ASCII traces, such as non\-packet data (e.g. protocol state machine transitions), .IP \(bu 2 large simulations for which the disk I/O requirements for generating trace files is prohibitive or cumbersome, and .IP \(bu 2 the need for \fIonline\fP data reduction or computation, during the course of the simulation. A good example of this is to define a termination condition for the simulation, to tell it when to stop when it has received enough data to form a narrow\-enough confidence interval around the estimate of some parameter. .UNINDENT .sp The \fIns\-3\fP data collection framework is designed to provide these additional capabilities beyond trace\-based output. We recommend that the reader interested in this topic consult the \fIns\-3\fP Manual for a more detailed treatment of this framework; here, we summarize with an example program some of the developing capabilities. .SS Example Code .sp The tutorial example \fBexamples/tutorial/seventh.cc\fP resembles the \fBsixth.cc\fP example we previously reviewed, except for a few changes. First, it has been enabled for IPv6 support with a command\-line option: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C CommandLine cmd; cmd.AddValue ("useIpv6", "Use Ipv6", useV6); cmd.Parse (argc, argv); .ft P .fi .UNINDENT .UNINDENT .sp If the user specifies \fBuseIpv6\fP, option, the program will be run using IPv6 instead of IPv4. The \fBhelp\fP option, available on all \fIns\-3\fP programs that support the CommandLine object as shown above, can be invoked as follows (please note the use of double quotes): .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C \&./waf \-\-run "seventh \-\-help" .ft P .fi .UNINDENT .UNINDENT .sp which produces: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C ns3\-dev\-seventh\-debug [Program Arguments] [General Arguments] Program Arguments: \-\-useIpv6: Use Ipv6 [false] General Arguments: \-\-PrintGlobals: Print the list of globals. \-\-PrintGroups: Print the list of groups. \-\-PrintGroup=[group]: Print all TypeIds of group. \-\-PrintTypeIds: Print all TypeIds. \-\-PrintAttributes=[typeid]: Print all attributes of typeid. \-\-PrintHelp: Print this help message. .ft P .fi .UNINDENT .UNINDENT .sp This default (use of IPv4, since useIpv6 is false) can be changed by toggling the boolean value as follows: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C \&./waf \-\-run "seventh \-\-useIpv6=1" .ft P .fi .UNINDENT .UNINDENT .sp and have a look at the pcap generated, such as with \fBtcpdump\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C tcpdump \-r seventh.pcap \-nn \-tt .ft P .fi .UNINDENT .UNINDENT .sp This has been a short digression into IPv6 support and the command line, which was also introduced earlier in this tutorial. For a dedicated example of command line usage, please see \fBsrc/core/examples/command\-line\-example.cc\fP\&. .sp Now back to data collection. In the \fBexamples/tutorial/\fP directory, type the following command: \fBdiff \-u sixth.cc seventh.cc\fP, and examine some of the new lines of this diff: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C + std::string probeType; + std::string tracePath; + if (useV6 == false) + { ... + probeType = "ns3::Ipv4PacketProbe"; + tracePath = "/NodeList/*/$ns3::Ipv4L3Protocol/Tx"; + } + else + { ... + probeType = "ns3::Ipv6PacketProbe"; + tracePath = "/NodeList/*/$ns3::Ipv6L3Protocol/Tx"; + } ... + // Use GnuplotHelper to plot the packet byte count over time + GnuplotHelper plotHelper; + + // Configure the plot. The first argument is the file name prefix + // for the output files generated. The second, third, and fourth + // arguments are, respectively, the plot title, x\-axis, and y\-axis labels + plotHelper.ConfigurePlot ("seventh\-packet\-byte\-count", + "Packet Byte Count vs. Time", + "Time (Seconds)", + "Packet Byte Count"); + + // Specify the probe type, trace source path (in configuration namespace), and + // probe output trace source ("OutputBytes") to plot. The fourth argument + // specifies the name of the data series label on the plot. The last + // argument formats the plot by specifying where the key should be placed. + plotHelper.PlotProbe (probeType, + tracePath, + "OutputBytes", + "Packet Byte Count", + GnuplotAggregator::KEY_BELOW); + + // Use FileHelper to write out the packet byte count over time + FileHelper fileHelper; + + // Configure the file to be written, and the formatting of output data. + fileHelper.ConfigureFile ("seventh\-packet\-byte\-count", + FileAggregator::FORMATTED); + + // Set the labels for this formatted output file. + fileHelper.Set2dFormat ("Time (Seconds) = %.3e\etPacket Byte Count = %.0f"); + + // Specify the probe type, probe path (in configuration namespace), and + // probe output trace source ("OutputBytes") to write. + fileHelper.WriteProbe (probeType, + tracePath, + "OutputBytes"); + Simulator::Stop (Seconds (20)); Simulator::Run (); Simulator::Destroy (); .ft P .fi .UNINDENT .UNINDENT .sp The careful reader will have noticed, when testing the IPv6 command line attribute above, that \fBseventh.cc\fP had created a number of new output files: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C seventh\-packet\-byte\-count\-0.txt seventh\-packet\-byte\-count\-1.txt seventh\-packet\-byte\-count.dat seventh\-packet\-byte\-count.plt seventh\-packet\-byte\-count.png seventh\-packet\-byte\-count.sh .ft P .fi .UNINDENT .UNINDENT .sp These were created by the additional statements introduced above; in particular, by a GnuplotHelper and a FileHelper. This data was produced by hooking the data collection components to \fIns\-3\fP trace sources, and marshaling the data into a formatted \fBgnuplot\fP and into a formatted text file. In the next sections, we’ll review each of these. .SS GnuplotHelper .sp The GnuplotHelper is an \fIns\-3\fP helper object aimed at the production of \fBgnuplot\fP plots with as few statements as possible, for common cases. It hooks \fIns\-3\fP trace sources with data types supported by the data collection system. Not all \fIns\-3\fP trace sources data types are supported, but many of the common trace types are, including TracedValues with plain old data (POD) types. .sp Let’s look at the output produced by this helper: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C seventh\-packet\-byte\-count.dat seventh\-packet\-byte\-count.plt seventh\-packet\-byte\-count.sh .ft P .fi .UNINDENT .UNINDENT .sp The first is a gnuplot data file with a series of space\-delimited timestamps and packet byte counts. We’ll cover how this particular data output was configured below, but let’s continue with the output files. The file \fBseventh\-packet\-byte\-count.plt\fP is a gnuplot plot file, that can be opened from within gnuplot. Readers who understand gnuplot syntax can see that this will produce a formatted output PNG file named \fBseventh\-packet\-byte\-count.png\fP\&. Finally, a small shell script \fBseventh\-packet\-byte\-count.sh\fP runs this plot file through gnuplot to produce the desired PNG (which can be viewed in an image editor); that is, the command: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C sh seventh\-packet\-byte\-count.sh .ft P .fi .UNINDENT .UNINDENT .sp will yield \fBseventh\-packet\-byte\-count.png\fP\&. Why wasn’t this PNG produced in the first place? The answer is that by providing the plt file, the user can hand\-configure the result if desired, before producing the PNG. .sp The PNG image title states that this plot is a plot of “Packet Byte Count vs. Time”, and that it is plotting the probed data corresponding to the trace source path: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C /NodeList/*/$ns3::Ipv6L3Protocol/Tx .ft P .fi .UNINDENT .UNINDENT .sp Note the wild\-card in the trace path. In summary, what this plot is capturing is the plot of packet bytes observed at the transmit trace source of the Ipv6L3Protocol object; largely 596\-byte TCP segments in one direction, and 60\-byte TCP acks in the other (two node trace sources were matched by this trace source). .sp How was this configured? A few statements need to be provided. First, the GnuplotHelper object must be declared and configured: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C + // Use GnuplotHelper to plot the packet byte count over time + GnuplotHelper plotHelper; + + // Configure the plot. The first argument is the file name prefix + // for the output files generated. The second, third, and fourth + // arguments are, respectively, the plot title, x\-axis, and y\-axis labels + plotHelper.ConfigurePlot ("seventh\-packet\-byte\-count", + "Packet Byte Count vs. Time", + "Time (Seconds)", + "Packet Byte Count"); .ft P .fi .UNINDENT .UNINDENT .sp To this point, an empty plot has been configured. The filename prefix is the first argument, the plot title is the second, the x\-axis label the third, and the y\-axis label the fourth argument. .sp The next step is to configure the data, and here is where the trace source is hooked. First, note above in the program we declared a few variables for later use: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C + std::string probeType; + std::string tracePath; + probeType = "ns3::Ipv6PacketProbe"; + tracePath = "/NodeList/*/$ns3::Ipv6L3Protocol/Tx"; .ft P .fi .UNINDENT .UNINDENT .sp We use them here: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C + // Specify the probe type, trace source path (in configuration namespace), and + // probe output trace source ("OutputBytes") to plot. The fourth argument + // specifies the name of the data series label on the plot. The last + // argument formats the plot by specifying where the key should be placed. + plotHelper.PlotProbe (probeType, + tracePath, + "OutputBytes", + "Packet Byte Count", + GnuplotAggregator::KEY_BELOW); .ft P .fi .UNINDENT .UNINDENT .sp The first two arguments are the name of the probe type and the trace source path. These two are probably the hardest to determine when you try to use this framework to plot other traces. The probe trace here is the \fBTx\fP trace source of class \fBIpv6L3Protocol\fP\&. When we examine this class implementation (\fBsrc/internet/model/ipv6\-l3\-protocol.cc\fP) we can observe: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C \&.AddTraceSource ("Tx", "Send IPv6 packet to outgoing interface.", MakeTraceSourceAccessor (&Ipv6L3Protocol::m_txTrace)) .ft P .fi .UNINDENT .UNINDENT .sp This says that \fBTx\fP is a name for variable \fBm_txTrace\fP, which has a declaration of: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C /** * \ebrief Callback to trace TX (transmission) packets. */ TracedCallback, Ptr, uint32_t> m_txTrace; .ft P .fi .UNINDENT .UNINDENT .sp It turns out that this specific trace source signature is supported by a Probe class (what we need here) of class Ipv6PacketProbe. See the files \fBsrc/internet/model/ipv6\-packet\-probe.{h,cc}\fP\&. .sp So, in the PlotProbe statement above, we see that the statement is hooking the trace source (identified by path string) with a matching \fIns\-3\fP Probe type of \fBIpv6PacketProbe\fP\&. If we did not support this probe type (matching trace source signature), we could have not used this statement (although some more complicated lower\-level statements could have been used, as described in the manual). .sp The Ipv6PacketProbe exports, itself, some trace sources that extract the data out of the probed Packet object: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C TypeId Ipv6PacketProbe::GetTypeId () { static TypeId tid = TypeId ("ns3::Ipv6PacketProbe") .SetParent () .SetGroupName ("Stats") .AddConstructor () .AddTraceSource ( "Output", "The packet plus its IPv6 object and interface that serve as the output for this probe", MakeTraceSourceAccessor (&Ipv6PacketProbe::m_output)) .AddTraceSource ( "OutputBytes", "The number of bytes in the packet", MakeTraceSourceAccessor (&Ipv6PacketProbe::m_outputBytes)) ; return tid; } .ft P .fi .UNINDENT .UNINDENT .sp The third argument of our PlotProbe statement specifies that we are interested in the number of bytes in this packet; specifically, the “OutputBytes” trace source of Ipv6PacketProbe. Finally, the last two arguments of the statement provide the plot legend for this data series (“Packet Byte Count”), and an optional gnuplot formatting statement (GnuplotAggregator::KEY_BELOW) that we want the plot key to be inserted below the plot. Other options include NO_KEY, KEY_INSIDE, and KEY_ABOVE. .SS Supported Trace Types .sp The following traced values are supported with Probes as of this writing: .INDENT 0.0 .INDENT 3.5 .TS center; |l|l|l|. _ T{ TracedValue type T} T{ Probe type T} T{ File T} _ T{ double T} T{ DoubleProbe T} T{ stats/model/double\-probe.h T} _ T{ uint8_t T} T{ Uinteger8Probe T} T{ stats/model/uinteger\-8\-probe.h T} _ T{ uint16_t T} T{ Uinteger16Probe T} T{ stats/model/uinteger\-16\-probe.h T} _ T{ uint32_t T} T{ Uinteger32Probe T} T{ stats/model/uinteger\-32\-probe.h T} _ T{ bool T} T{ BooleanProbe T} T{ stats/model/uinteger\-16\-probe.h T} _ T{ ns3::Time T} T{ TimeProbe T} T{ stats/model/time\-probe.h T} _ .TE .UNINDENT .UNINDENT .sp The following TraceSource types are supported by Probes as of this writing: .INDENT 0.0 .INDENT 3.5 .TS center; |l|l|l|l|. _ T{ TracedSource type T} T{ Probe type T} T{ Probe outputs T} T{ File T} _ T{ Ptr T} T{ PacketProbe T} T{ OutputBytes T} T{ network/utils/packet\-probe.h T} _ T{ Ptr, Ptr, uint32_t T} T{ Ipv4PacketProbe T} T{ OutputBytes T} T{ internet/model/ipv4\-packet\-probe.h T} _ T{ Ptr, Ptr, uint32_t T} T{ Ipv6PacketProbe T} T{ OutputBytes T} T{ internet/model/ipv6\-packet\-probe.h T} _ T{ Ptr, Ptr, uint32_t T} T{ Ipv6PacketProbe T} T{ OutputBytes T} T{ internet/model/ipv6\-packet\-probe.h T} _ T{ Ptr, const Address& T} T{ ApplicationPacketProbe T} T{ OutputBytes T} T{ applications/model/application\-packet\-probe.h T} _ .TE .UNINDENT .UNINDENT .sp As can be seen, only a few trace sources are supported, and they are all oriented towards outputting the Packet size (in bytes). However, most of the fundamental data types available as TracedValues can be supported with these helpers. .SS FileHelper .sp The FileHelper class is just a variation of the previous GnuplotHelper example. The example program provides formatted output of the same timestamped data, such as follows: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Time (Seconds) = 9.312e+00 Packet Byte Count = 596 Time (Seconds) = 9.312e+00 Packet Byte Count = 564 .ft P .fi .UNINDENT .UNINDENT .sp Two files are provided, one for node “0” and one for node “1” as can be seen in the filenames. Let’s look at the code piece\-by\-piece: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C + // Use FileHelper to write out the packet byte count over time + FileHelper fileHelper; + + // Configure the file to be written, and the formatting of output data. + fileHelper.ConfigureFile ("seventh\-packet\-byte\-count", + FileAggregator::FORMATTED); .ft P .fi .UNINDENT .UNINDENT .sp The file helper file prefix is the first argument, and a format specifier is next. Some other options for formatting include SPACE_SEPARATED, COMMA_SEPARATED, and TAB_SEPARATED. Users are able to change the formatting (if FORMATTED is specified) with a format string such as follows: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C + + // Set the labels for this formatted output file. + fileHelper.Set2dFormat ("Time (Seconds) = %.3e\etPacket Byte Count = %.0f"); .ft P .fi .UNINDENT .UNINDENT .sp Finally, the trace source of interest must be hooked. Again, the probeType and tracePath variables in this example are used, and the probe’s output trace source “OutputBytes” is hooked: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C + + // Specify the probe type, trace source path (in configuration namespace), and + // probe output trace source ("OutputBytes") to write. + fileHelper.WriteProbe (probeType, + tracePath, + "OutputBytes"); + .ft P .fi .UNINDENT .UNINDENT .sp The wildcard fields in this trace source specifier match two trace sources. Unlike the GnuplotHelper example, in which two data series were overlaid on the same plot, here, two separate files are written to disk. .SS Summary .sp Data collection support is new as of ns\-3.18, and basic support for providing time series output has been added. The basic pattern described above may be replicated within the scope of support of the existing probes and trace sources. More capabilities including statistics processing will be added in future releases. .SH CONCLUSION .SS Futures .sp This document is intended as a living document. We hope and expect it to grow over time to cover more and more of the nuts and bolts of \fIns\-3\fP\&. .sp Writing manual and tutorial chapters is not something we all get excited about, but it is very important to the project. If you are an expert in one of these areas, please consider contributing to \fIns\-3\fP by providing one of these chapters; or any other chapter you may think is important. .SS Closing .sp \fIns\-3\fP is a large and complicated system. It is impossible to cover all of the things you will need to know in one small tutorial. Readers who want to learn more are encouraged to read the following additional documentation: .INDENT 0.0 .IP \(bu 2 The \fIns\-3\fP manual .IP \(bu 2 The \fIns\-3\fP model library documentation .IP \(bu 2 The \fIns\-3\fP Doxygen (API documentation) .IP \(bu 2 The \fIns\-3\fP wiki .UNINDENT .sp – The \fIns\-3\fP development team. .SH AUTHOR ns-3 project .SH COPYRIGHT 2006-2019 .\" Generated by docutils manpage writer. .