Logo AND Algorithmique Numérique Distribuée

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