Logo AND Algorithmique Numérique Distribuée

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