Logo AND Algorithmique Numérique Distribuée

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