Logo AND Algorithmique Numérique Distribuée

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