Logo AND Algorithmique Numérique Distribuée

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