Logo AND Algorithmique Numérique Distribuée

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