Logo AND Algorithmique Numérique Distribuée

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