Logo AND Algorithmique Numérique Distribuée

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