Logo AND Algorithmique Numérique Distribuée

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