Logo AND Algorithmique Numérique Distribuée

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