Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Fix sonar issues in ns3 bindings.
[simgrid.git] / src / surf / network_ns3.cpp
1 /* Copyright (c) 2007-2022. The SimGrid Team. All rights reserved.          */
2
3 /* This program is free software; you can redistribute it and/or modify it
4  * under the terms of the license (GNU LGPL) which comes with this package. */
5
6 #include "simgrid/plugins/ns3.hpp"
7
8 #include <random>
9 #include <string>
10 #include <unordered_set>
11
12 #include "xbt/config.hpp"
13 #include "xbt/str.h"
14 #include "xbt/string.hpp"
15 #include "xbt/utility.hpp"
16
17 #include <ns3/application-container.h>
18 #include <ns3/core-module.h>
19 #include <ns3/csma-helper.h>
20 #include <ns3/event-id.h>
21 #include <ns3/global-route-manager.h>
22 #include <ns3/internet-stack-helper.h>
23 #include <ns3/ipv4-address-helper.h>
24 #include <ns3/ipv4-global-routing-helper.h>
25 #include <ns3/packet-sink-helper.h>
26 #include <ns3/point-to-point-helper.h>
27
28 #include "ns3/mobility-module.h"
29 #include "ns3/wifi-module.h"
30
31 #include "network_ns3.hpp"
32 #include "ns3/ns3_simulator.hpp"
33
34 #include "simgrid/kernel/routing/NetPoint.hpp"
35 #include "simgrid/kernel/routing/NetZoneImpl.hpp"
36 #include "simgrid/kernel/routing/WifiZone.hpp"
37 #include "simgrid/plugins/energy.h"
38 #include "simgrid/s4u/Engine.hpp"
39 #include "simgrid/s4u/NetZone.hpp"
40 #include "src/instr/instr_private.hpp" // TRACE_is_enabled(). FIXME: remove by subscribing tracing to the surf signals
41 #include "src/kernel/EngineImpl.hpp"
42 #include "src/surf/surf_interface.hpp"
43 #include "src/surf/xml/platf_private.hpp" // ClusterCreationArgs
44
45 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(res_ns3, res_network, "Network model based on ns-3");
46
47 /*****************
48  * Crude globals *
49  *****************/
50
51 extern std::map<std::string, SgFlow*, std::less<>> flow_from_sock;
52 extern std::map<std::string, ns3::ApplicationContainer, std::less<>> sink_from_sock;
53
54 static ns3::InternetStackHelper stack;
55
56 static int number_of_links    = 1;
57 static int number_of_networks = 1;
58
59 simgrid::xbt::Extension<simgrid::kernel::routing::NetPoint, NetPointNs3> NetPointNs3::EXTENSION_ID;
60
61 static std::string transformIpv4Address(ns3::Ipv4Address from)
62 {
63   std::stringstream sstream;
64   sstream << from;
65   return sstream.str();
66 }
67
68 NetPointNs3::NetPointNs3()
69 {
70   stack.Install(ns3_node_);
71 }
72
73 static void resumeWifiDevice(ns3::Ptr<ns3::WifiNetDevice> device)
74 {
75   device->GetPhy()->ResumeFromOff();
76 }
77
78 /*************
79  * Callbacks *
80  *************/
81
82 static void zoneCreation_cb(simgrid::s4u::NetZone const& zone)
83 {
84   auto const* wifizone = dynamic_cast<simgrid::kernel::routing::WifiZone*>(zone.get_impl());
85   if (wifizone == nullptr)
86     return;
87
88   /* wifi globals */
89   static ns3::WifiHelper wifi;
90 #if NS3_MINOR_VERSION < 33
91   static ns3::YansWifiPhyHelper wifiPhy = ns3::YansWifiPhyHelper::Default();
92 #else
93   static ns3::YansWifiPhyHelper wifiPhy;
94 #endif
95   static ns3::YansWifiChannelHelper wifiChannel = ns3::YansWifiChannelHelper::Default();
96   static ns3::WifiMacHelper wifiMac;
97   static ns3::MobilityHelper mobility;
98
99 #if NS3_MINOR_VERSION < 32
100   wifi.SetStandard(ns3::WIFI_PHY_STANDARD_80211n_5GHZ);
101 #else
102   wifi.SetStandard(ns3::WIFI_STANDARD_80211n_5GHZ);
103 #endif
104
105   std::string ssid = wifizone->get_name();
106   const char* mcs  = wifizone->get_property("mcs");
107   const char* nss  = wifizone->get_property("nss");
108   int mcs_value    = mcs ? atoi(mcs) : 3;
109   int nss_value    = nss ? atoi(nss) : 1;
110 #if NS3_MINOR_VERSION < 30
111   xbt_assert(nss_value == 1 + (mcs_value / 8),
112              "On NS3 < 3.30, NSS value has to satisfy NSS == 1+(MCS/8) constraint. Bailing out");
113 #endif
114   wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager", "ControlMode", ns3::StringValue("HtMcs0"), "DataMode",
115                                ns3::StringValue("HtMcs" + std::to_string(mcs_value)));
116   wifiPhy.SetChannel(wifiChannel.Create());
117   wifiPhy.Set("Antennas", ns3::UintegerValue(nss_value));
118   wifiPhy.Set("MaxSupportedTxSpatialStreams", ns3::UintegerValue(nss_value));
119   wifiPhy.Set("MaxSupportedRxSpatialStreams", ns3::UintegerValue(nss_value));
120 #if NS3_MINOR_VERSION > 33
121   wifiPhy.Set("ChannelWidth", ns3::UintegerValue(40));
122 #endif
123   wifiMac.SetType("ns3::ApWifiMac", "Ssid", ns3::SsidValue(ssid));
124
125   mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel");
126   ns3::Ptr<ns3::ListPositionAllocator> positionAllocS = ns3::CreateObject<ns3::ListPositionAllocator>();
127   positionAllocS->Add(ns3::Vector(0, 0, 255 * 100 * number_of_networks + 100 * number_of_links));
128
129   ns3::NetDeviceContainer netDevices;
130   NetPointNs3* access_point_netpoint_ns3 = wifizone->get_access_point()->extension<NetPointNs3>();
131
132   ns3::Ptr<ns3::Node> access_point_ns3_node = access_point_netpoint_ns3->ns3_node_;
133   ns3::NodeContainer nodes                  = {access_point_ns3_node};
134   std::vector<NetPointNs3*> hosts_netpoints = {access_point_netpoint_ns3};
135   netDevices.Add(wifi.Install(wifiPhy, wifiMac, access_point_ns3_node));
136
137   wifiMac.SetType("ns3::StaWifiMac", "Ssid", ns3::SsidValue(ssid), "ActiveProbing", ns3::BooleanValue(false));
138
139   NetPointNs3* station_netpoint_ns3    = nullptr;
140   ns3::Ptr<ns3::Node> station_ns3_node = nullptr;
141   double distance;
142   double angle    = 0;
143   auto nb_stations = wifizone->get_all_hosts().size() - 1;
144   double step     = 2 * M_PI / nb_stations;
145   for (auto station_host : wifizone->get_all_hosts()) {
146     station_netpoint_ns3 = station_host->get_netpoint()->extension<NetPointNs3>();
147     if (station_netpoint_ns3 == access_point_netpoint_ns3)
148       continue;
149     hosts_netpoints.push_back(station_netpoint_ns3);
150     distance = station_host->get_property("wifi_distance") ? atof(station_host->get_property("wifi_distance")) : 10.0;
151     positionAllocS->Add(ns3::Vector(distance * std::cos(angle), distance * std::sin(angle),
152                                     255 * 100 * number_of_networks + 100 * number_of_links));
153     angle += step;
154     station_ns3_node = station_netpoint_ns3->ns3_node_;
155     nodes.Add(station_ns3_node);
156     netDevices.Add(wifi.Install(wifiPhy, wifiMac, station_ns3_node));
157   }
158
159   const char* start_time = wifizone->get_property("start_time");
160   int start_time_value   = start_time ? atoi(start_time) : 0;
161   for (uint32_t i = 0; i < netDevices.GetN(); i++) {
162     ns3::Ptr<ns3::WifiNetDevice> device = ns3::StaticCast<ns3::WifiNetDevice>(netDevices.Get(i));
163     device->GetPhy()->SetOffMode();
164     ns3::Simulator::Schedule(ns3::Seconds(start_time_value), &resumeWifiDevice, device);
165   }
166
167 #if NS3_MINOR_VERSION < 33
168   // This fails with "The channel width does not uniquely identify an operating channel" on v3.34,
169   // so we specified the ChannelWidth of wifiPhy to 40, above, when creating wifiPhy with v3.34 and higher
170   ns3::Config::Set("/NodeList/*/DeviceList/*/$ns3::WifiNetDevice/Phy/ChannelWidth", ns3::UintegerValue(40));
171 #endif
172
173   mobility.SetPositionAllocator(positionAllocS);
174   mobility.Install(nodes);
175   ns3::Ipv4AddressHelper address;
176   std::string addr = simgrid::xbt::string_printf("%d.%d.0.0", number_of_networks, number_of_links);
177   address.SetBase(addr.c_str(), "255.255.0.0");
178   XBT_DEBUG("\tInterface stack '%s'", addr.c_str());
179   ns3::Ipv4InterfaceContainer addresses = address.Assign(netDevices);
180   for (unsigned int i = 0; i < hosts_netpoints.size(); i++) {
181     hosts_netpoints[i]->ipv4_address_ = transformIpv4Address(addresses.GetAddress(i));
182   }
183
184   if (number_of_links == 255) {
185     xbt_assert(number_of_networks < 255, "Number of links and networks exceed 255*255");
186     number_of_links = 1;
187     number_of_networks++;
188   } else {
189     number_of_links++;
190   }
191   /* in theory we can compute the routing table only only once at the platform seal
192    *  however put it here since or platform_created signal is called before the seal right now */
193   ns3::Ipv4GlobalRoutingHelper::RecomputeRoutingTables();
194 }
195
196 static void clusterCreation_cb(simgrid::kernel::routing::ClusterCreationArgs const& cluster)
197 {
198   ns3::NodeContainer Nodes;
199
200   xbt_assert(cluster.topology == simgrid::kernel::routing::ClusterTopology::FLAT,
201              "NS-3 is supported only by flat clusters. Do not use with other topologies");
202
203   for (int const& i : cluster.radicals) {
204     // Create private link
205     std::string host_id = cluster.prefix + std::to_string(i) + cluster.suffix;
206     auto const* src     = simgrid::s4u::Host::by_name(host_id)->get_netpoint();
207     auto const* dst     = simgrid::s4u::Engine::get_instance()->netpoint_by_name_or_null(cluster.router_id);
208     xbt_assert(dst != nullptr, "No router named %s", cluster.router_id.c_str());
209
210     ns3_add_direct_route(src, dst, cluster.bw, cluster.lat, cluster.sharing_policy); // Any ns-3 route is symmetrical
211
212     // Also add the host to the list of hosts that will be connected to the backbone
213     Nodes.Add(src->extension<NetPointNs3>()->ns3_node_);
214   }
215
216   // Create link backbone
217
218   xbt_assert(Nodes.GetN() <= 65000, "Cluster with ns-3 is limited to 65000 nodes");
219   ns3::CsmaHelper csma;
220   csma.SetChannelAttribute("DataRate",
221                            ns3::DataRateValue(ns3::DataRate(cluster.bb_bw * 8))); // ns-3 takes bps, but we provide Bps
222   csma.SetChannelAttribute("Delay", ns3::TimeValue(ns3::Seconds(cluster.bb_lat)));
223   ns3::NetDeviceContainer devices = csma.Install(Nodes);
224   XBT_DEBUG("Create CSMA");
225
226   std::string addr = simgrid::xbt::string_printf("%d.%d.0.0", number_of_networks, number_of_links);
227   XBT_DEBUG("Assign IP Addresses %s to CSMA.", addr.c_str());
228   ns3::Ipv4AddressHelper ipv4;
229   ipv4.SetBase(addr.c_str(), "255.255.0.0");
230   ipv4.Assign(devices);
231
232   if (number_of_links == 255) {
233     xbt_assert(number_of_networks < 255, "Number of links and networks exceed 255*255");
234     number_of_links = 1;
235     number_of_networks++;
236   } else {
237     number_of_links++;
238   }
239 }
240
241 static void routeCreation_cb(bool symmetrical, const simgrid::kernel::routing::NetPoint* src,
242                              const simgrid::kernel::routing::NetPoint* dst,
243                              const simgrid::kernel::routing::NetPoint* /*gw_src*/,
244                              const simgrid::kernel::routing::NetPoint* /*gw_dst*/,
245                              std::vector<simgrid::kernel::resource::StandardLinkImpl*> const& link_list)
246 {
247   /* ignoring routes from StarZone, not supported */
248   if (not src || not dst)
249     return;
250
251   if (link_list.size() == 1) {
252     auto const* link = static_cast<simgrid::kernel::resource::LinkNS3*>(link_list[0]);
253
254     XBT_DEBUG("Route from '%s' to '%s' with link '%s' %s %s", src->get_cname(), dst->get_cname(), link->get_cname(),
255               (link->get_sharing_policy() == simgrid::s4u::Link::SharingPolicy::WIFI ? "(wifi)" : "(wired)"),
256               (symmetrical ? "(symmetrical)" : "(not symmetrical)"));
257
258     XBT_DEBUG("\tLink (%s) bw:%fbps lat:%fs", link->get_cname(), link->get_bandwidth(), link->get_latency());
259
260     ns3_add_direct_route(src, dst, link->get_bandwidth(), link->get_latency(), link->get_sharing_policy());
261   } else {
262     static bool warned_about_long_routes = false;
263
264     if (not warned_about_long_routes)
265       XBT_WARN("Ignoring a route between %s and %s of length %zu: Only routes of length 1 are considered with ns-3.\n"
266                "WARNING: You can ignore this warning if your hosts can still communicate when only considering routes "
267                "of length 1.\n"
268                "WARNING: Remove long routes to avoid this harmless message; subsequent long routes will be silently "
269                "ignored.",
270                src->get_cname(), dst->get_cname(), link_list.size());
271     warned_about_long_routes = true;
272   }
273 }
274
275 /*********
276  * Model *
277  *********/
278 void surf_network_model_init_NS3()
279 {
280   auto net_model = std::make_shared<simgrid::kernel::resource::NetworkNS3Model>("NS3 network model");
281   auto* engine   = simgrid::kernel::EngineImpl::get_instance();
282   engine->add_model(net_model);
283   engine->get_netzone_root()->set_network_model(net_model);
284 }
285
286 static simgrid::config::Flag<std::string>
287     ns3_tcp_model("ns3/TcpModel", "The ns-3 tcp model can be: NewReno or Reno or Tahoe", "default");
288 static simgrid::config::Flag<std::string> ns3_seed(
289     "ns3/seed",
290     "The random seed provided to ns-3. Either 'time' to seed with time(), blank to not set (default), or a number.", "",
291     [](const std::string& val) {
292       if (val.length() == 0)
293         return;
294       if (strcasecmp(val.c_str(), "time") == 0) {
295         std::default_random_engine prng(time(nullptr));
296         ns3::RngSeedManager::SetSeed(prng());
297         ns3::RngSeedManager::SetRun(prng());
298       } else {
299         int v = static_cast<int>(xbt_str_parse_int(
300             val.c_str(), "Invalid value for option ns3/seed. It must be either 'time', a number, or left empty."));
301         ns3::RngSeedManager::SetSeed(v);
302         ns3::RngSeedManager::SetRun(v);
303       }
304     });
305
306 namespace simgrid {
307 namespace kernel {
308 namespace resource {
309
310 NetworkNS3Model::NetworkNS3Model(const std::string& name) : NetworkModel(name)
311 {
312   xbt_assert(not sg_link_energy_is_inited(),
313              "LinkEnergy plugin and ns-3 network models are not compatible. Are you looking for Ecofen, maybe?");
314
315   NetPointNs3::EXTENSION_ID = routing::NetPoint::extension_create<NetPointNs3>();
316
317   ns3::Config::SetDefault("ns3::TcpSocket::SegmentSize", ns3::UintegerValue(1000));
318   ns3::Config::SetDefault("ns3::TcpSocket::DelAckCount", ns3::UintegerValue(1));
319   ns3::Config::SetDefault("ns3::TcpSocketBase::Timestamp", ns3::BooleanValue(false));
320
321   auto const& TcpProtocol = ns3_tcp_model.get();
322   if (TcpProtocol == "default") {
323     /* nothing to do */
324
325   } else if (TcpProtocol == "Reno" || TcpProtocol == "NewReno" || TcpProtocol == "Tahoe") {
326     XBT_INFO("Switching Tcp protocol to '%s'", TcpProtocol.c_str());
327     ns3::Config::SetDefault("ns3::TcpL4Protocol::SocketType", ns3::StringValue("ns3::Tcp" + TcpProtocol));
328
329   } else {
330     xbt_die("The ns3/TcpModel must be: NewReno or Reno or Tahoe");
331   }
332
333   routing::NetPoint::on_creation.connect([](routing::NetPoint& pt) {
334     pt.extension_set<NetPointNs3>(new NetPointNs3());
335     XBT_VERB("Declare SimGrid's %s within ns-3", pt.get_cname());
336   });
337
338   s4u::Engine::on_platform_created_cb([]() {
339     /* Create the ns3 topology based on routing strategy */
340     ns3::GlobalRouteManager::DeleteGlobalRoutes(); // just in case this callback is called twice
341     ns3::GlobalRouteManager::BuildGlobalRoutingDatabase();
342     ns3::GlobalRouteManager::InitializeRoutes();
343   });
344   routing::on_cluster_creation.connect(&clusterCreation_cb);
345   routing::NetZoneImpl::on_route_creation.connect(&routeCreation_cb);
346   s4u::NetZone::on_seal_cb(&zoneCreation_cb);
347 }
348
349 NetworkNS3Model::~NetworkNS3Model()
350 {
351   ns3::Simulator::Destroy();
352 }
353
354 StandardLinkImpl* NetworkNS3Model::create_link(const std::string& name, const std::vector<double>& bandwidths)
355 {
356   xbt_assert(bandwidths.size() == 1, "ns-3 links must use only 1 bandwidth.");
357   auto* link = new LinkNS3(name, bandwidths[0]);
358   link->set_model(this);
359   return link;
360 }
361
362 StandardLinkImpl* NetworkNS3Model::create_wifi_link(const std::string& name, const std::vector<double>& bandwidths)
363 {
364   auto* link = create_link(name, bandwidths);
365   link->set_sharing_policy(s4u::Link::SharingPolicy::WIFI, {});
366   return link;
367 }
368
369 Action* NetworkNS3Model::communicate(s4u::Host* src, s4u::Host* dst, double size, double rate)
370 {
371   xbt_assert(rate == -1,
372              "Communication over ns-3 links cannot specify a specific rate. Please use -1 as a value instead of %f.",
373              rate);
374   return new NetworkNS3Action(this, size, src, dst);
375 }
376
377 double NetworkNS3Model::next_occurring_event(double now)
378 {
379   double time_to_next_flow_completion = 0.0;
380   XBT_DEBUG("ns3_next_occurring_event");
381
382   // get the first relevant value from the running_actions list
383
384   // If there is no comms in NS-3, then we do not move it forward.
385   // We will synchronize NS-3 with SimGrid when starting a new communication.
386   // (see NetworkNS3Action::NetworkNS3Action() for more details on this point)
387   if (get_started_action_set()->empty() || now == 0.0)
388     return -1.0;
389
390   XBT_DEBUG("doing a ns3 simulation for a duration of %f", now);
391   ns3_simulator(now);
392   time_to_next_flow_completion = ns3::Simulator::Now().GetSeconds() - EngineImpl::get_clock();
393   // NS-3 stops as soon as a flow ends,
394   // but it does not process the other flows that may finish at the same (simulated) time.
395   // If another flow ends at the same time, time_to_next_flow_completion = 0
396   if (double_equals(time_to_next_flow_completion, 0, sg_surf_precision))
397     time_to_next_flow_completion = 0.0;
398
399   XBT_DEBUG("min       : %f", now);
400   XBT_DEBUG("ns3  time : %f", ns3::Simulator::Now().GetSeconds());
401   XBT_DEBUG("surf time : %f", EngineImpl::get_clock());
402   XBT_DEBUG("Next completion %f :", time_to_next_flow_completion);
403
404   return time_to_next_flow_completion;
405 }
406
407 void NetworkNS3Model::update_actions_state(double now, double delta)
408 {
409   static std::vector<std::string> socket_to_destroy;
410
411   std::string ns3_socket;
412   for (const auto& elm : flow_from_sock) {
413     ns3_socket               = elm.first;
414     SgFlow* sgFlow           = elm.second;
415     NetworkNS3Action* action = sgFlow->action_;
416     XBT_DEBUG("Processing flow %p (socket %s, action %p)", sgFlow, ns3_socket.c_str(), action);
417     // Because NS3 stops as soon as a flow is finished, the other flows that ends at the same time may remains in an
418     // inconsistent state (i.e. remains_ == 0 but finished_ == false).
419     // However, SimGrid considers sometimes that an action with remains_ == 0 is finished.
420     // Thus, to avoid inconsistencies between SimGrid and NS3, set remains to 0 only when the flow is finished in NS3
421     double remains = action->get_cost() - sgFlow->sent_bytes_;
422     if (remains > 0)
423       action->set_remains(remains);
424
425     if (TRACE_is_enabled() && action->get_state() == kernel::resource::Action::State::STARTED) {
426       double data_delta_sent = sgFlow->sent_bytes_ - action->last_sent_;
427
428       std::vector<StandardLinkImpl*> route;
429       action->get_src().route_to(&action->get_dst(), route, nullptr);
430       for (auto const& link : route)
431         instr::resource_set_utilization("LINK", "bandwidth_used", link->get_cname(), action->get_category(),
432                                         data_delta_sent / delta, now - delta, delta);
433
434       action->last_sent_ = sgFlow->sent_bytes_;
435     }
436
437     if ((sgFlow->finished_) && (remains <= 0)) { // finished_ should not become true before remains gets to 0, but it
438                                                  // sometimes does. Let's play safe, here.
439       socket_to_destroy.push_back(ns3_socket);
440       XBT_DEBUG("Destroy socket %s of action %p", ns3_socket.c_str(), action);
441       action->set_remains(0);
442       action->finish(Action::State::FINISHED);
443     } else {
444       XBT_DEBUG("Socket %s sent %u bytes out of %u (%u remaining)", ns3_socket.c_str(), sgFlow->sent_bytes_,
445                 sgFlow->total_bytes_, sgFlow->remaining_);
446     }
447   }
448
449   while (not socket_to_destroy.empty()) {
450     ns3_socket = socket_to_destroy.back();
451     socket_to_destroy.pop_back();
452     SgFlow* flow = flow_from_sock.at(ns3_socket);
453     if (XBT_LOG_ISENABLED(res_ns3, xbt_log_priority_debug)) {
454       XBT_DEBUG("Removing socket %s of action %p", ns3_socket.c_str(), flow->action_);
455     }
456     delete flow;
457     flow_from_sock.erase(ns3_socket);
458     sink_from_sock.erase(ns3_socket);
459   }
460 }
461
462 /************
463  * Resource *
464  ************/
465
466 LinkNS3::LinkNS3(const std::string& name, double bandwidth) : StandardLinkImpl(name)
467 {
468   bandwidth_.peak = bandwidth;
469 }
470
471 LinkNS3::~LinkNS3() = default;
472
473 void LinkNS3::apply_event(profile::Event*, double)
474 {
475   THROW_UNIMPLEMENTED;
476 }
477
478 void LinkNS3::set_bandwidth_profile(profile::Profile* profile)
479 {
480   xbt_assert(profile == nullptr, "The ns-3 network model doesn't support bandwidth profiles");
481 }
482
483 void LinkNS3::set_latency_profile(profile::Profile* profile)
484 {
485   xbt_assert(profile == nullptr, "The ns-3 network model doesn't support latency profiles");
486 }
487
488 void LinkNS3::set_latency(double latency)
489 {
490   latency_.peak = latency;
491 }
492
493 void LinkNS3::set_sharing_policy(s4u::Link::SharingPolicy policy, const s4u::NonLinearResourceCb& cb)
494 {
495   sharing_policy_ = policy;
496 }
497 /**********
498  * Action *
499  **********/
500
501 NetworkNS3Action::NetworkNS3Action(Model* model, double totalBytes, s4u::Host* src, s4u::Host* dst)
502     : NetworkAction(model, *src, *dst, totalBytes, false)
503 {
504   // ns-3 fails when src = dst, so avoid the problem by considering that communications are infinitely fast on the
505   // loopback that does not exists
506   if (src == dst) {
507     static bool warned = false;
508     if (not warned) {
509       XBT_WARN("Sending from a host %s to itself is not supported by ns-3. Every such communication finishes "
510                "immediately upon startup.",
511                src->get_cname());
512       warned = true;
513     }
514     finish(Action::State::FINISHED);
515     return;
516   }
517
518   // If there is no other started actions, we need to move NS-3 forward to be sync with SimGrid
519   if (model->get_started_action_set()->size() == 1) {
520     while (double_positive(EngineImpl::get_clock() - ns3::Simulator::Now().GetSeconds(), sg_surf_precision)) {
521       XBT_DEBUG("Synchronizing NS-3 (time %f) with SimGrid (time %f)", ns3::Simulator::Now().GetSeconds(),
522                 EngineImpl::get_clock());
523       ns3_simulator(EngineImpl::get_clock() - ns3::Simulator::Now().GetSeconds());
524     }
525   }
526
527   static uint16_t port_number = 1;
528
529   ns3::Ptr<ns3::Node> src_node = get_ns3node_from_sghost(src);
530   ns3::Ptr<ns3::Node> dst_node = get_ns3node_from_sghost(dst);
531
532   const std::string& addr = dst->get_netpoint()->extension<NetPointNs3>()->ipv4_address_;
533   xbt_assert(not addr.empty(), "Element %s is unknown to ns-3. Is it connected to any one-hop link?",
534              dst->get_netpoint()->get_cname());
535
536   ns3::PacketSinkHelper sink("ns3::TcpSocketFactory", ns3::InetSocketAddress(ns3::Ipv4Address::GetAny(), port_number));
537   ns3::ApplicationContainer apps = sink.Install(dst_node);
538
539   ns3::Ptr<ns3::Socket> sock = ns3::Socket::CreateSocket(src_node, ns3::TcpSocketFactory::GetTypeId());
540
541   XBT_DEBUG("Create socket %s for a flow of %.0f Bytes from %s to %s with Interface %s",
542             transform_socket_ptr(sock).c_str(), totalBytes, src->get_cname(), dst->get_cname(), addr.c_str());
543
544   flow_from_sock.insert({transform_socket_ptr(sock), new SgFlow(totalBytes, this)});
545   sink_from_sock.insert({transform_socket_ptr(sock), apps});
546
547   sock->Bind(ns3::InetSocketAddress(port_number));
548   ns3::Simulator::ScheduleNow(&start_flow, sock, addr.c_str(), port_number);
549
550   port_number = 1 + (port_number % UINT16_MAX);
551   if (port_number == 1)
552     XBT_WARN("Too many connections! Port number is saturated. Trying to use the oldest ports.");
553 }
554
555 void NetworkNS3Action::suspend()
556 {
557   THROW_UNIMPLEMENTED;
558 }
559
560 void NetworkNS3Action::resume()
561 {
562   THROW_UNIMPLEMENTED;
563 }
564
565 std::list<StandardLinkImpl*> NetworkNS3Action::get_links() const
566 {
567   THROW_UNIMPLEMENTED;
568 }
569 void NetworkNS3Action::update_remains_lazy(double /*now*/)
570 {
571   THROW_IMPOSSIBLE;
572 }
573
574 } // namespace resource
575 } // namespace kernel
576
577 ns3::Ptr<ns3::Node> get_ns3node_from_sghost(const simgrid::s4u::Host* host)
578 {
579   xbt_assert(host->get_netpoint()->extension<NetPointNs3>() != nullptr, "Please only use this function on ns-3 nodes");
580   return host->get_netpoint()->extension<NetPointNs3>()->ns3_node_;
581 }
582 } // namespace simgrid
583
584 void ns3_simulator(double maxSeconds)
585 {
586   ns3::EventId id;
587   if (maxSeconds > 0.0) // If there is a maximum amount of time to run
588     id = ns3::Simulator::Schedule(ns3::Seconds(maxSeconds), &ns3::Simulator::Stop);
589
590   XBT_DEBUG("Start simulator for at most %fs (current time: %f)", maxSeconds, simgrid::kernel::EngineImpl::get_clock());
591   ns3::Simulator::Run();
592   XBT_DEBUG("Simulator stopped at %fs", ns3::Simulator::Now().GetSeconds());
593
594   if (maxSeconds > 0.0)
595     id.Cancel();
596 }
597
598 void ns3_add_direct_route(const simgrid::kernel::routing::NetPoint* src, const simgrid::kernel::routing::NetPoint* dst,
599                           double bw, double lat, simgrid::s4u::Link::SharingPolicy policy)
600 {
601   ns3::Ipv4AddressHelper address;
602   ns3::NetDeviceContainer netA;
603
604   // create link ns3
605   auto* host_src = src->extension<NetPointNs3>();
606   auto* host_dst = dst->extension<NetPointNs3>();
607
608   xbt_assert(host_src != nullptr, "Network element %s does not seem to be ns-3-ready", src->get_cname());
609   xbt_assert(host_dst != nullptr, "Network element %s does not seem to be ns-3-ready", dst->get_cname());
610
611   xbt_assert(policy != simgrid::s4u::Link::SharingPolicy::WIFI,
612              "The wifi sharing policy is not supported for links. You want to use a wifi zone (see documentation).");
613
614   ns3::PointToPointHelper pointToPoint;
615
616   XBT_DEBUG("\tAdd PTP from %s to %s bw:'%f Bps' lat:'%fs'", src->get_cname(), dst->get_cname(), bw, lat);
617   pointToPoint.SetDeviceAttribute("DataRate",
618                                   ns3::DataRateValue(ns3::DataRate(bw * 8))); // ns-3 takes bps, but we provide Bps
619   pointToPoint.SetChannelAttribute("Delay", ns3::TimeValue(ns3::Seconds(lat)));
620
621   netA.Add(pointToPoint.Install(host_src->ns3_node_, host_dst->ns3_node_));
622
623   std::string addr = simgrid::xbt::string_printf("%d.%d.0.0", number_of_networks, number_of_links);
624   address.SetBase(addr.c_str(), "255.255.0.0");
625   XBT_DEBUG("\tInterface stack '%s'", addr.c_str());
626
627   auto addresses = address.Assign(netA);
628
629   host_src->ipv4_address_ = transformIpv4Address(addresses.GetAddress(0));
630   host_dst->ipv4_address_ = transformIpv4Address(addresses.GetAddress(1));
631
632   if (number_of_links == 255) {
633     xbt_assert(number_of_networks < 255, "Number of links and networks exceed 255*255");
634     number_of_links = 1;
635     number_of_networks++;
636   } else {
637     number_of_links++;
638   }
639 }