Logo AND Algorithmique Numérique Distribuée

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