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
85ReportRank(int color, MPI_Comm splitComm)
86{
87 int otherId = 0;
88 int otherSize = 1;
89
90 MPI_Comm_rank(splitComm, &otherId);
91 MPI_Comm_size(splitComm, &otherSize);
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
107int
108main(int argc, char* argv[])
109{
110 bool nix = true;
111 bool nullmsg = false;
112 bool tracing = false;
113 bool init = false;
114 bool verbose = false;
115 bool testing = false;
116
117 // Parse command line
118 CommandLine cmd(__FILE__);
119 cmd.AddValue("nix", "Enable the use of nix-vector or global routing", nix);
120 cmd.AddValue("nullmsg",
121 "Enable the use of null-message synchronization (instead of granted time window)",
122 nullmsg);
123 cmd.AddValue("tracing", "Enable pcap tracing", tracing);
124 cmd.AddValue("init", "ns-3 should initialize MPI by calling MPI_Init", init);
125 cmd.AddValue("verbose", "verbose output", verbose);
126 cmd.AddValue("test", "Enable regression test output", testing);
127 cmd.Parse(argc, argv);
128
129 // Defer reporting the configuration until we know the communicator
130
131 // Distributed simulation setup; by default use granted time window algorithm.
132 if (nullmsg)
133 {
134 GlobalValue::Bind("SimulatorImplementationType",
135 StringValue("ns3::NullMessageSimulatorImpl"));
136 }
137 else
138 {
139 GlobalValue::Bind("SimulatorImplementationType",
140 StringValue("ns3::DistributedSimulatorImpl"));
141 }
142
143 // MPI_Init
144
145 if (init)
146 {
147 // Initialize MPI directly
148 MPI_Init(&argc, &argv);
149 }
150 else
151 {
152 // Let ns-3 call MPI_Init and MPI_Finalize
153 MpiInterface::Enable(&argc, &argv);
154 }
155
157
158 auto worldSize = SinkTracer::GetWorldSize();
159 auto worldRank = SinkTracer::GetWorldRank();
160
161 if ((!init) && (worldSize != 2))
162 {
163 RANK0COUT("This simulation requires exactly 2 logical processors if --init is not set."
164 << std::endl);
165 return 1;
166 }
167
168 if (worldSize < 2)
169 {
170 RANK0COUT("This simulation requires 2 or more logical processors." << std::endl);
171 return 1;
172 }
173
174 // Set up the MPI communicator for ns-3
175 // Condition ns-3 Communicator
176 // a. worldSize = 2 copy of MPI_COMM_WORLD
177 // b. worldSize > 2 communicator of ranks 1-2
178
179 // Flag to record that we created a communicator so we can free it at the end.
180 bool freeComm = false;
181 // The new communicator, if we create one
182 MPI_Comm splitComm = MPI_COMM_WORLD;
183 // The list of ranks assigned to ns-3
184 std::string ns3Ranks;
185 // Tag for whether this rank should go into a new communicator
186 int color = MPI_UNDEFINED;
187
188 if (worldSize == 2)
189 {
190 std::stringstream ss;
191 color = NS_COLOR;
192 ss << "MPI_COMM_WORLD (" << worldSize << " ranks)";
193 ns3Ranks = ss.str();
194 splitComm = MPI_COMM_WORLD;
195 freeComm = false;
196 }
197 else
198 {
199 // worldSize > 2 communicator of ranks 1-2
200
201 // Put ranks 1-2 in the new communicator
202 if (worldRank == 1 || worldRank == 2)
203 {
204 color = NS_COLOR;
205 }
206 else
207 {
208 color = NOT_NS_COLOR;
209 }
210 std::stringstream ss;
211 ss << "Split [1-2] (out of " << worldSize << " ranks) from MPI_COMM_WORLD";
212 ns3Ranks = ss.str();
213
214 // Now create the new communicator
215 MPI_Comm_split(MPI_COMM_WORLD, color, worldRank, &splitComm);
216 freeComm = true;
217 }
218
219 if (init)
220 {
221 MpiInterface::Enable(splitComm);
222 }
223
224 // Report the configuration from rank 0 only
225 RANK0COUT(cmd.GetName() << "\n");
226 RANK0COUT("\n");
227 RANK0COUT("Configuration:\n");
228 RANK0COUT("Routing: " << (nix ? "nix-vector" : "global") << "\n");
229 RANK0COUT("Synchronization: " << (nullmsg ? "null-message" : "granted time window (YAWNS)")
230 << "\n");
231 RANK0COUT("MPI_Init called: "
232 << (init ? "explicitly by this program" : "implicitly by ns3::MpiInterface::Enable()")
233 << "\n");
234 RANK0COUT("ns-3 Communicator: " << ns3Ranks << "\n");
235 RANK0COUT("PCAP tracing: " << (tracing ? "" : "not") << " enabled\n");
236 RANK0COUT("\n");
237 RANK0COUT("Rank assignments:" << std::endl);
238
239 if (worldRank == 0)
240 {
241 ReportRank(color, splitComm);
242 }
243
244 if (verbose)
245 {
246 // Circulate a token to have each rank report in turn
247 int token;
248
249 if (worldRank == 0)
250 {
251 token = 1;
252 }
253 else
254 {
255 MPI_Recv(&token, 1, MPI_INT, worldRank - 1, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
256 ReportRank(color, splitComm);
257 }
258
259 MPI_Send(&token, 1, MPI_INT, (worldRank + 1) % worldSize, 0, MPI_COMM_WORLD);
260
261 if (worldRank == 0)
262 {
263 MPI_Recv(&token, 1, MPI_INT, worldSize - 1, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
264 }
265 } // circulate token to report rank
266
267 RANK0COUT(std::endl);
268
269 if (color != NS_COLOR)
270 {
271 // Do other work outside the ns-3 communicator
272
273 // In real use of a separate communicator from ns-3
274 // the other tasks would be running another simulator
275 // or other desired work here..
276
277 // Our work is done, just wait for everyone else to finish.
278
280
281 if (init)
282 {
283 MPI_Finalize();
284 }
285
286 return 0;
287 }
288
289 // The code below here is essentially the same as simple-distributed.cc
290 // --------------------------------------------------------------------
291
292 // We use a trace instead of relying on NS_LOG
293
294 if (verbose)
295 {
296 LogComponentEnable("PacketSink", LOG_LEVEL_INFO);
297 }
298
300 uint32_t systemCount = MpiInterface::GetSize();
301
302 // Check for valid distributed parameters.
303 // Both this script and simple-distributed.cc will work
304 // with arbitrary numbers of ranks, as long as there are at least 2.
305 if (systemCount < 2)
306 {
307 RANK0COUT("This simulation requires at least 2 logical processors." << std::endl);
308 return 1;
309 }
310
311 // Some default values
312 Config::SetDefault("ns3::OnOffApplication::PacketSize", UintegerValue(512));
313 Config::SetDefault("ns3::OnOffApplication::DataRate", StringValue("1Mbps"));
314 Config::SetDefault("ns3::OnOffApplication::MaxBytes", UintegerValue(512));
315
316 // Create leaf nodes on left with system id 0
317 NodeContainer leftLeafNodes;
318 leftLeafNodes.Create(4, 0);
319
320 // Create router nodes. Left router
321 // with system id 0, right router with
322 // system id 1
323 NodeContainer routerNodes;
324 Ptr<Node> routerNode1 = CreateObject<Node>(0);
325 Ptr<Node> routerNode2 = CreateObject<Node>(1);
326 routerNodes.Add(routerNode1);
327 routerNodes.Add(routerNode2);
328
329 // Create leaf nodes on left with system id 1
330 NodeContainer rightLeafNodes;
331 rightLeafNodes.Create(4, 1);
332
333 PointToPointHelper routerLink;
334 routerLink.SetDeviceAttribute("DataRate", StringValue("5Mbps"));
335 routerLink.SetChannelAttribute("Delay", StringValue("5ms"));
336
337 PointToPointHelper leafLink;
338 leafLink.SetDeviceAttribute("DataRate", StringValue("1Mbps"));
339 leafLink.SetChannelAttribute("Delay", StringValue("2ms"));
340
341 // Add link connecting routers
342 NetDeviceContainer routerDevices;
343 routerDevices = routerLink.Install(routerNodes);
344
345 // Add links for left side leaf nodes to left router
346 NetDeviceContainer leftRouterDevices;
347 NetDeviceContainer leftLeafDevices;
348 for (uint32_t i = 0; i < 4; ++i)
349 {
350 NetDeviceContainer temp = leafLink.Install(leftLeafNodes.Get(i), routerNodes.Get(0));
351 leftLeafDevices.Add(temp.Get(0));
352 leftRouterDevices.Add(temp.Get(1));
353 }
354
355 // Add links for right side leaf nodes to right router
356 NetDeviceContainer rightRouterDevices;
357 NetDeviceContainer rightLeafDevices;
358 for (uint32_t i = 0; i < 4; ++i)
359 {
360 NetDeviceContainer temp = leafLink.Install(rightLeafNodes.Get(i), routerNodes.Get(1));
361 rightLeafDevices.Add(temp.Get(0));
362 rightRouterDevices.Add(temp.Get(1));
363 }
364
367 Ipv4StaticRoutingHelper staticRouting;
368
370 list.Add(staticRouting, 0);
371 list.Add(nixRouting, 10);
372
373 if (nix)
374 {
375 stack.SetRoutingHelper(list); // has effect on the next Install ()
376 }
377
378 stack.InstallAll();
379
380 Ipv4InterfaceContainer routerInterfaces;
381 Ipv4InterfaceContainer leftLeafInterfaces;
382 Ipv4InterfaceContainer leftRouterInterfaces;
383 Ipv4InterfaceContainer rightLeafInterfaces;
384 Ipv4InterfaceContainer rightRouterInterfaces;
385
386 Ipv4AddressHelper leftAddress;
387 leftAddress.SetBase("10.1.1.0", "255.255.255.0");
388
389 Ipv4AddressHelper routerAddress;
390 routerAddress.SetBase("10.2.1.0", "255.255.255.0");
391
392 Ipv4AddressHelper rightAddress;
393 rightAddress.SetBase("10.3.1.0", "255.255.255.0");
394
395 // Router-to-Router interfaces
396 routerInterfaces = routerAddress.Assign(routerDevices);
397
398 // Left interfaces
399 for (uint32_t i = 0; i < 4; ++i)
400 {
402 ndc.Add(leftLeafDevices.Get(i));
403 ndc.Add(leftRouterDevices.Get(i));
404 Ipv4InterfaceContainer ifc = leftAddress.Assign(ndc);
405 leftLeafInterfaces.Add(ifc.Get(0));
406 leftRouterInterfaces.Add(ifc.Get(1));
407 leftAddress.NewNetwork();
408 }
409
410 // Right interfaces
411 for (uint32_t i = 0; i < 4; ++i)
412 {
414 ndc.Add(rightLeafDevices.Get(i));
415 ndc.Add(rightRouterDevices.Get(i));
416 Ipv4InterfaceContainer ifc = rightAddress.Assign(ndc);
417 rightLeafInterfaces.Add(ifc.Get(0));
418 rightRouterInterfaces.Add(ifc.Get(1));
419 rightAddress.NewNetwork();
420 }
421
422 if (!nix)
423 {
425 }
426
427 if (tracing)
428 {
429 if (systemId == 0)
430 {
431 routerLink.EnablePcap("router-left", routerDevices, true);
432 leafLink.EnablePcap("leaf-left", leftLeafDevices, true);
433 }
434
435 if (systemId == 1)
436 {
437 routerLink.EnablePcap("router-right", routerDevices, true);
438 leafLink.EnablePcap("leaf-right", rightLeafDevices, true);
439 }
440 }
441
442 // Create a packet sink on the right leafs to receive packets from left leafs
443 uint16_t port = 50000;
444 if (systemId == 1)
445 {
447 PacketSinkHelper sinkHelper("ns3::UdpSocketFactory", sinkLocalAddress);
448 ApplicationContainer sinkApp;
449 for (uint32_t i = 0; i < 4; ++i)
450 {
451 auto apps = sinkHelper.Install(rightLeafNodes.Get(i));
452 auto sink = DynamicCast<PacketSink>(apps.Get(0));
453 NS_ASSERT_MSG(sink, "Couldn't get PacketSink application.");
454 if (testing)
455 {
456 sink->TraceConnectWithoutContext("RxWithAddresses",
458 }
459 sinkApp.Add(apps);
460 }
461 sinkApp.Start(Seconds(1));
462 sinkApp.Stop(Seconds(5));
463 }
464
465 // Create the OnOff applications to send
466 if (systemId == 0)
467 {
468 OnOffHelper clientHelper("ns3::UdpSocketFactory", Address());
469 clientHelper.SetAttribute("OnTime", StringValue("ns3::ConstantRandomVariable[Constant=1]"));
470 clientHelper.SetAttribute("OffTime",
471 StringValue("ns3::ConstantRandomVariable[Constant=0]"));
472
474 for (uint32_t i = 0; i < 4; ++i)
475 {
477 clientHelper.SetAttribute("Remote", remoteAddress);
478 clientApps.Add(clientHelper.Install(leftLeafNodes.Get(i)));
479 }
480 clientApps.Start(Seconds(1));
481 clientApps.Stop(Seconds(5));
482 }
483
484 RANK0COUT(std::endl);
485
489
490 // --------------------------------------------------------------------
491 // Conditional cleanup based on whether we built a communicator
492 // and called MPI_Init
493
494 if (freeComm)
495 {
496 MPI_Comm_free(&splitComm);
497 }
498
499 if (testing)
500 {
502 }
503
504 // Clean up the ns-3 MPI execution environment
505 // This will call MPI_Finalize if MpiInterface::Initialize was called
507
508 if (init)
509 {
510 // We called MPI_Init, so we have to call MPI_Finalize
511 MPI_Finalize();
512 }
513
514 return 0;
515}
a polymophic address class
Definition address.h:90
AttributeValue implementation for Address.
Definition address.h:275
holds a vector of ns3::Application pointers.
void Start(Time start) const
Start all of the Applications in this container at the start time given as a parameter.
void Stop(Time stop) const
Arrange for all of the Applications in this container to Stop() at the Time given as a parameter.
void Add(ApplicationContainer other)
Append the contents of another ApplicationContainer to the end of this container.
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.
Ipv4Address NewNetwork()
Increment the network number and reset the IP address counter to the base value provided in the SetBa...
Ipv4InterfaceContainer Assign(const NetDeviceContainer &c)
Assign IP addresses to the net devices specified in the container based on the current network prefix...
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.
std::pair< Ptr< Ipv4 >, uint32_t > Get(uint32_t i) const
Get the std::pair of an Ptr<Ipv4> and interface stored at the location specified by the index.
void Add(const Ipv4InterfaceContainer &other)
Concatenate the entries in the other container with ours.
Ipv4Address GetAddress(uint32_t i, uint32_t j=0) const
Helper class that adds ns3::Ipv4ListRouting objects.
void Add(const Ipv4RoutingHelper &routing, int16_t priority)
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.
Ptr< NetDevice > Get(uint32_t i) const
Get the Ptr<NetDevice> stored in this container at a given index.
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.
void Add(const NodeContainer &nc)
Append the contents of another NodeContainer to the end of this container.
Ptr< Node > Get(uint32_t i) const
Get the Ptr<Node> stored in this container at a given index.
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.
void EnablePcap(std::string prefix, Ptr< NetDevice > nd, bool promiscuous=false, bool explicitFilename=false)
Enable pcap output the indicated net device.
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.
void SetChannelAttribute(std::string name, const AttributeValue &value)
Set an attribute value to be propagated to each Channel created by the helper.
NetDeviceContainer Install(NodeContainer c)
Smart pointer class similar to boost::intrusive_ptr.
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:886
#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 > CreateObject(Args &&... args)
Create an object by type, with varying number of constructor parameters.
Definition object.h:619
Time Seconds(double value)
Construct a Time in the indicated unit.
Definition nstime.h:1345
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
Ptr< T1 > DynamicCast(const Ptr< T2 > &p)
Cast a Ptr.
Definition ptr.h:580
@ 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