Logo AND Algorithmique Numérique Distribuée

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