A Discrete-Event Network Simulator
API
Loading...
Searching...
No Matches
simple-distributed-mpi-comm.cc
Go to the documentation of this file.
1/*
2 * Copyright 2018. Lawrence Livermore National Security, LLC.
3 *
4 * SPDX-License-Identifier: GPL-2.0-only
5 *
6 * Author: Steven Smith <smith84@llnl.gov>
7 */
8
9/**
10 * @file
11 * @ingroup mpi
12 *
13 * This test is equivalent to simple-distributed with the addition of
14 * initialization of MPI by user code (this script) and providing
15 * a communicator to ns-3. The ns-3 communicator is smaller than
16 * MPI Comm World as might be the case if ns-3 is run in parallel
17 * with another simulator.
18 *
19 * TestDistributed creates a dumbbell topology and logically splits it in
20 * half. The left half is placed on logical processor 0 and the right half
21 * is placed on logical processor 1.
22 *
23 * ------- -------
24 * RANK 0 RANK 1
25 * ------- | -------
26 * |
27 * n0 ---------| | |---------- n6
28 * | | |
29 * n1 -------\ | | | /------- n7
30 * n4 ----------|---------- n5
31 * n2 -------/ | | | \------- n8
32 * | | |
33 * n3 ---------| | |---------- n9
34 *
35 *
36 * OnOff clients are placed on each left leaf node. Each right leaf node
37 * is a packet sink for a left leaf node. As a packet travels from one
38 * logical processor to another (the link between n4 and n5), MPI messages
39 * are passed containing the serialized packet. The message is then
40 * deserialized into a new packet and sent on as normal.
41 *
42 * One packet is sent from each left leaf node. The packet sinks on the
43 * right leaf nodes output logging information when they receive the packet.
44 */
45
46#include "mpi-test-fixtures.h"
47
48#include "ns3/core-module.h"
49#include "ns3/internet-stack-helper.h"
50#include "ns3/ipv4-address-helper.h"
51#include "ns3/ipv4-global-routing-helper.h"
52#include "ns3/ipv4-list-routing-helper.h"
53#include "ns3/ipv4-static-routing-helper.h"
54#include "ns3/mpi-interface.h"
55#include "ns3/network-module.h"
56#include "ns3/nix-vector-helper.h"
57#include "ns3/on-off-helper.h"
58#include "ns3/packet-sink-helper.h"
59#include "ns3/packet-sink.h"
60#include "ns3/point-to-point-helper.h"
61
62#include <mpi.h>
63
64using namespace ns3;
65
66NS_LOG_COMPONENT_DEFINE("SimpleDistributedMpiComm");
67
68/**
69 * Tag for whether this rank should go into a new communicator
70 * ns-3 ranks will have color == 1.
71 * @{
72 */
73const int NS_COLOR = 1;
74const int NOT_NS_COLOR = NS_COLOR + 1;
75
76/** @} */
77
78/**
79 * Report my rank, in both MPI_COMM_WORLD and the split communicator.
80 *
81 * @param [in] color My role, either ns-3 rank or other rank.
82 * @param [in] splitComm The split communicator.
83 */
84void
86{
87 int otherId = 0;
88 int otherSize = 1;
89
92
93 if (color == NS_COLOR)
94 {
95 RANK0COUT("ns-3 rank: ");
96 }
97 else
98 {
99 RANK0COUT("Other rank: ");
100 }
101
102 RANK0COUTAPPEND("in MPI_COMM_WORLD: " << SinkTracer::GetWorldRank() << ":"
103 << SinkTracer::GetWorldSize() << ", in splitComm: "
104 << otherId << ":" << otherSize << std::endl);
105
106} // ReportRank()
107
108int
109main(int argc, char* argv[])
110{
111 bool nix = true;
112 bool nullmsg = false;
113 bool tracing = false;
114 bool init = false;
115 bool verbose = false;
116 bool testing = false;
117
118 // Parse command line
120 cmd.AddValue("nix", "Enable the use of nix-vector or global routing", nix);
121 cmd.AddValue("nullmsg",
122 "Enable the use of null-message synchronization (instead of granted time window)",
123 nullmsg);
124 cmd.AddValue("tracing", "Enable pcap tracing", tracing);
125 cmd.AddValue("init", "ns-3 should initialize MPI by calling MPI_Init", init);
126 cmd.AddValue("verbose", "verbose output", verbose);
127 cmd.AddValue("test", "Enable regression test output", testing);
128 cmd.Parse(argc, argv);
129
130 // Defer reporting the configuration until we know the communicator
131
132 // Distributed simulation setup; by default use granted time window algorithm.
133 if (nullmsg)
134 {
135 GlobalValue::Bind("SimulatorImplementationType",
136 StringValue("ns3::NullMessageSimulatorImpl"));
137 }
138 else
139 {
140 GlobalValue::Bind("SimulatorImplementationType",
141 StringValue("ns3::DistributedSimulatorImpl"));
142 }
143
144 // MPI_Init
145
146 if (init)
147 {
148 // Initialize MPI directly
149 MPI_Init(&argc, &argv);
150 }
151 else
152 {
153 // Let ns-3 call MPI_Init and MPI_Finalize
155 }
156
158
161
162 if ((!init) && (worldSize != 2))
163 {
164 RANK0COUT("This simulation requires exactly 2 logical processors if --init is not set."
165 << std::endl);
166 return 1;
167 }
168
169 if (worldSize < 2)
170 {
171 RANK0COUT("This simulation requires 2 or more logical processors." << std::endl);
172 return 1;
173 }
174
175 // Set up the MPI communicator for ns-3
176 // Condition ns-3 Communicator
177 // a. worldSize = 2 copy of MPI_COMM_WORLD
178 // b. worldSize > 2 communicator of ranks 1-2
179
180 // Flag to record that we created a communicator so we can free it at the end.
181 bool freeComm = false;
182 // The new communicator, if we create one
184 // The list of ranks assigned to ns-3
185 std::string ns3Ranks;
186 // Tag for whether this rank should go into a new communicator
187 int color = MPI_UNDEFINED;
188
189 if (worldSize == 2)
190 {
191 std::stringstream ss;
192 color = NS_COLOR;
193 ss << "MPI_COMM_WORLD (" << worldSize << " ranks)";
194 ns3Ranks = ss.str();
196 freeComm = false;
197 }
198 else
199 {
200 // worldSize > 2 communicator of ranks 1-2
201
202 // Put ranks 1-2 in the new communicator
203 if (worldRank == 1 || worldRank == 2)
204 {
205 color = NS_COLOR;
206 }
207 else
208 {
209 color = NOT_NS_COLOR;
210 }
211 std::stringstream ss;
212 ss << "Split [1-2] (out of " << worldSize << " ranks) from MPI_COMM_WORLD";
213 ns3Ranks = ss.str();
214
215 // Now create the new communicator
217 freeComm = true;
218 }
219
220 if (init)
221 {
223 }
224
225 // Report the configuration from rank 0 only
226 RANK0COUT(cmd.GetName() << "\n");
227 RANK0COUT("\n");
228 RANK0COUT("Configuration:\n");
229 RANK0COUT("Routing: " << (nix ? "nix-vector" : "global") << "\n");
230 RANK0COUT("Synchronization: " << (nullmsg ? "null-message" : "granted time window (YAWNS)")
231 << "\n");
232 RANK0COUT("MPI_Init called: "
233 << (init ? "explicitly by this program" : "implicitly by ns3::MpiInterface::Enable()")
234 << "\n");
235 RANK0COUT("ns-3 Communicator: " << ns3Ranks << "\n");
236 RANK0COUT("PCAP tracing: " << (tracing ? "" : "not") << " enabled\n");
237 RANK0COUT("\n");
238 RANK0COUT("Rank assignments:" << std::endl);
239
240 if (worldRank == 0)
241 {
242 ReportRank(color, splitComm);
243 }
244
245 if (verbose)
246 {
247 // Circulate a token to have each rank report in turn
248 int token;
249
250 if (worldRank == 0)
251 {
252 token = 1;
253 }
254 else
255 {
257 ReportRank(color, splitComm);
258 }
259
260 MPI_Send(&token, 1, MPI_INT, (worldRank + 1) % worldSize, 0, MPI_COMM_WORLD);
261
262 if (worldRank == 0)
263 {
265 }
266 } // circulate token to report rank
267
268 RANK0COUT(std::endl);
269
270 if (color != NS_COLOR)
271 {
272 // Do other work outside the ns-3 communicator
273
274 // In real use of a separate communicator from ns-3
275 // the other tasks would be running another simulator
276 // or other desired work here..
277
278 // Our work is done, just wait for everyone else to finish.
279
281
282 if (init)
283 {
284 MPI_Finalize();
285 }
286
287 return 0;
288 }
289
290 // The code below here is essentially the same as simple-distributed.cc
291 // --------------------------------------------------------------------
292
293 // We use a trace instead of relying on NS_LOG
294
295 if (verbose)
296 {
297 LogComponentEnable("PacketSink", LOG_LEVEL_INFO);
298 }
299
302
303 // Check for valid distributed parameters.
304 // Both this script and simple-distributed.cc will work
305 // with arbitrary numbers of ranks, as long as there are at least 2.
306 if (systemCount < 2)
307 {
308 RANK0COUT("This simulation requires at least 2 logical processors." << std::endl);
309 return 1;
310 }
311
312 // Some default values
313 Config::SetDefault("ns3::OnOffApplication::PacketSize", UintegerValue(512));
314 Config::SetDefault("ns3::OnOffApplication::DataRate", StringValue("1Mbps"));
315 Config::SetDefault("ns3::OnOffApplication::MaxBytes", UintegerValue(512));
316
317 // Create leaf nodes on left with system id 0
319 leftLeafNodes.Create(4, 0);
320
321 // Create router nodes. Left router
322 // with system id 0, right router with
323 // system id 1
329
330 // Create leaf nodes on left with system id 1
333
335 routerLink.SetDeviceAttribute("DataRate", StringValue("5Mbps"));
336 routerLink.SetChannelAttribute("Delay", StringValue("5ms"));
337
339 leafLink.SetDeviceAttribute("DataRate", StringValue("1Mbps"));
340 leafLink.SetChannelAttribute("Delay", StringValue("2ms"));
341
342 // Add link connecting routers
345
346 // Add links for left side leaf nodes to left router
349 for (uint32_t i = 0; i < 4; ++i)
350 {
352 leftLeafDevices.Add(temp.Get(0));
353 leftRouterDevices.Add(temp.Get(1));
354 }
355
356 // Add links for right side leaf nodes to right router
359 for (uint32_t i = 0; i < 4; ++i)
360 {
362 rightLeafDevices.Add(temp.Get(0));
363 rightRouterDevices.Add(temp.Get(1));
364 }
365
369
371 list.Add(staticRouting, 0);
372 list.Add(nixRouting, 10);
373
374 if (nix)
375 {
376 stack.SetRoutingHelper(list); // has effect on the next Install ()
377 }
378
379 stack.InstallAll();
380
386
388 leftAddress.SetBase("10.1.1.0", "255.255.255.0");
389
391 routerAddress.SetBase("10.2.1.0", "255.255.255.0");
392
394 rightAddress.SetBase("10.3.1.0", "255.255.255.0");
395
396 // Router-to-Router interfaces
398
399 // Left interfaces
400 for (uint32_t i = 0; i < 4; ++i)
401 {
403 ndc.Add(leftLeafDevices.Get(i));
404 ndc.Add(leftRouterDevices.Get(i));
406 leftLeafInterfaces.Add(ifc.Get(0));
407 leftRouterInterfaces.Add(ifc.Get(1));
408 leftAddress.NewNetwork();
409 }
410
411 // Right interfaces
412 for (uint32_t i = 0; i < 4; ++i)
413 {
416 ndc.Add(rightRouterDevices.Get(i));
419 rightRouterInterfaces.Add(ifc.Get(1));
420 rightAddress.NewNetwork();
421 }
422
423 if (!nix)
424 {
426 }
427
428 if (tracing)
429 {
430 if (systemId == 0)
431 {
432 routerLink.EnablePcap("router-left", routerDevices, true);
433 leafLink.EnablePcap("leaf-left", leftLeafDevices, true);
434 }
435
436 if (systemId == 1)
437 {
438 routerLink.EnablePcap("router-right", routerDevices, true);
439 leafLink.EnablePcap("leaf-right", rightLeafDevices, true);
440 }
441 }
442
443 // Create a packet sink on the right leafs to receive packets from left leafs
444 uint16_t port = 50000;
445 if (systemId == 1)
446 {
448 PacketSinkHelper sinkHelper("ns3::UdpSocketFactory", sinkLocalAddress);
450 for (uint32_t i = 0; i < 4; ++i)
451 {
452 auto apps = sinkHelper.Install(rightLeafNodes.Get(i));
453 auto sink = DynamicCast<PacketSink>(apps.Get(0));
454 NS_ASSERT_MSG(sink, "Couldn't get PacketSink application.");
455 if (testing)
456 {
457 sink->TraceConnectWithoutContext("RxWithAddresses",
459 }
460 sinkApp.Add(apps);
461 }
462 sinkApp.Start(Seconds(1));
463 sinkApp.Stop(Seconds(5));
464 }
465
466 // Create the OnOff applications to send
467 if (systemId == 0)
468 {
469 OnOffHelper clientHelper("ns3::UdpSocketFactory", Address());
470 clientHelper.SetAttribute("OnTime", StringValue("ns3::ConstantRandomVariable[Constant=1]"));
471 clientHelper.SetAttribute("OffTime",
472 StringValue("ns3::ConstantRandomVariable[Constant=0]"));
473
475 for (uint32_t i = 0; i < 4; ++i)
476 {
478 clientHelper.SetAttribute("Remote", remoteAddress);
479 clientApps.Add(clientHelper.Install(leftLeafNodes.Get(i)));
480 }
481 clientApps.Start(Seconds(1));
482 clientApps.Stop(Seconds(5));
483 }
484
485 RANK0COUT(std::endl);
486
490
491 // --------------------------------------------------------------------
492 // Conditional cleanup based on whether we built a communicator
493 // and called MPI_Init
494
495 if (freeComm)
496 {
498 }
499
500 if (testing)
501 {
503 }
504
505 // Clean up the ns-3 MPI execution environment
506 // This will call MPI_Finalize if MpiInterface::Initialize was called
508
509 if (init)
510 {
511 // We called MPI_Init, so we have to call MPI_Finalize
512 MPI_Finalize();
513 }
514
515 return 0;
516}
a polymophic address class
Definition address.h:90
AttributeValue implementation for Address.
Definition address.h:275
holds a vector of ns3::Application pointers.
Parse command-line arguments.
static void Bind(std::string name, const AttributeValue &value)
Iterate over the set of GlobalValues until a matching name is found and then set its value with Globa...
an Inet address class
aggregate IP/TCP/UDP functionality to existing Nodes.
A helper class to make life easier while doing simple IPv4 address assignment in scripts.
void SetBase(Ipv4Address network, Ipv4Mask mask, Ipv4Address base="0.0.0.1")
Set the base network number, network mask and base address.
static Ipv4Address GetAny()
static void PopulateRoutingTables()
Build a routing database and initialize the routing tables of the nodes in the simulation.
holds a vector of std::pair of Ptr<Ipv4> and interface index.
void Add(const Ipv4InterfaceContainer &other)
Concatenate the entries in the other container with ours.
Helper class that adds ns3::Ipv4ListRouting objects.
Helper class that adds ns3::Ipv4StaticRouting objects.
static uint32_t GetSystemId()
Get the id number of this rank.
static uint32_t GetSize()
Get the number of ranks used by ns-3.
static void Disable()
Clean up the ns-3 parallel communications interface.
static void Enable(int *pargc, char ***pargv)
Setup the parallel communication interface.
holds a vector of ns3::NetDevice pointers
void Add(NetDeviceContainer other)
Append the contents of another NetDeviceContainer to the end of this container.
Helper class that adds Nix-vector routing to nodes.
keep track of a set of node pointers.
void Create(uint32_t n)
Create n nodes and append pointers to them to the end of this NodeContainer.
A helper to make it easier to instantiate an ns3::OnOffApplication on a set of nodes.
A helper to make it easier to instantiate an ns3::PacketSinkApplication on a set of nodes.
Build a set of PointToPointNetDevice objects.
void SetDeviceAttribute(std::string name, const AttributeValue &value)
Set an attribute value to be propagated to each NetDevice created by the helper.
Smart pointer class similar to boost::intrusive_ptr.
Definition ptr.h:66
static void Destroy()
Execute the events scheduled with ScheduleDestroy().
Definition simulator.cc:131
static void Run()
Run the simulation.
Definition simulator.cc:167
static void Stop()
Tell the Simulator the calling event should be the last one executed.
Definition simulator.cc:175
static void SinkTrace(const ns3::Ptr< const ns3::Packet > packet, const ns3::Address &srcAddress, const ns3::Address &destAddress)
PacketSink receive trace callback.
static void Verify(unsigned long expectedCount)
Verify the sink trace count observed matches the expected count.
static void Init()
PacketSink Init.
static int GetWorldSize()
Get the MPI size of the world communicator.
static int GetWorldRank()
Get the MPI rank in the world communicator.
Hold variables of type string.
Definition string.h:45
Hold an unsigned integer type.
Definition uinteger.h:34
uint16_t port
Definition dsdv-manet.cc:33
#define NS_ASSERT_MSG(condition, message)
At runtime, in debugging builds, if this condition is not true, the program prints the message to out...
Definition assert.h:75
void SetDefault(std::string name, const AttributeValue &value)
Definition config.cc:883
#define NS_LOG_COMPONENT_DEFINE(name)
Define a Log component with a specific name.
Definition log.h:191
#define RANK0COUT(x)
Write to std::cout only from rank 0.
#define RANK0COUTAPPEND(x)
Append to std::cout only from rank 0.
Ptr< T > Create(Ts &&... args)
Create class instances by constructors with varying numbers of arguments and return them by Ptr.
Definition ptr.h:436
Time Seconds(double value)
Construct a Time in the indicated unit.
Definition nstime.h:1344
Common methods for MPI examples.
clientApps
Definition first.py:53
stack
Definition first.py:33
Every class exported by the ns3 library is enclosed in the ns3 namespace.
void LogComponentEnable(const std::string &name, LogLevel level)
Enable the logging output associated with that log component.
Definition log.cc:291
Callback< R, Args... > MakeCallback(R(T::*memPtr)(Args...), OBJ objPtr)
Build Callbacks for class method members which take varying numbers of arguments and potentially retu...
Definition callback.h:684
@ LOG_LEVEL_INFO
LOG_INFO and above.
Definition log.h:93
#define list
bool verbose
void ReportRank(int color, MPI_Comm splitComm)
Report my rank, in both MPI_COMM_WORLD and the split communicator.
const int NS_COLOR
Tag for whether this rank should go into a new communicator ns-3 ranks will have color == 1.
const int NOT_NS_COLOR
Tag for whether this rank should go into a new communicator ns-3 ranks will have color == 1.
bool tracing
Flag to enable/disable generation of tracing files.
Ptr< PacketSink > sink
Pointer to the packet sink application.
Definition wifi-tcp.cc:44