Logo AND Algorithmique Numérique Distribuée

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