1 /* Copyright (c) 2007-2023. The SimGrid Team. All rights reserved. */
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. */
6 #include "simgrid/plugins/ns3.hpp"
10 #include <unordered_set>
12 #include "src/simgrid/math_utils.h"
13 #include "src/simgrid/module.hpp"
14 #include "xbt/config.hpp"
16 #include "xbt/string.hpp"
17 #include "xbt/utility.hpp"
19 #include <ns3/application-container.h>
20 #include <ns3/core-module.h>
21 #include <ns3/csma-helper.h>
22 #include <ns3/event-id.h>
23 #include <ns3/global-route-manager.h>
24 #include <ns3/internet-stack-helper.h>
25 #include <ns3/ipv4-address-helper.h>
26 #include <ns3/ipv4-global-routing-helper.h>
27 #include <ns3/packet-sink-helper.h>
28 #include <ns3/point-to-point-helper.h>
30 #include <ns3/mobility-module.h>
31 #include <ns3/wifi-module.h>
33 #include "network_ns3.hpp"
34 #include "src/kernel/resource/models/ns3/ns3_simulator.hpp"
36 #include "simgrid/kernel/routing/NetPoint.hpp"
37 #include "simgrid/kernel/routing/NetZoneImpl.hpp"
38 #include "simgrid/kernel/routing/WifiZone.hpp"
39 #include "simgrid/plugins/energy.h"
40 #include "simgrid/s4u/Engine.hpp"
41 #include "simgrid/s4u/NetZone.hpp"
42 #include "src/instr/instr_private.hpp" // TRACE_is_enabled(). FIXME: remove by subscribing tracing to the signals
43 #include "src/kernel/EngineImpl.hpp"
44 #include "src/kernel/xml/platf_private.hpp" // ClusterCreationArgs
46 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(res_ns3, res_network, "Network model based on ns-3");
52 extern std::map<std::string, SgFlow*, std::less<>> flow_from_sock;
54 static int number_of_links = 1;
55 static int number_of_networks = 1;
57 simgrid::xbt::Extension<simgrid::kernel::routing::NetPoint, NetPointNs3> NetPointNs3::EXTENSION_ID;
59 static std::string transformIpv4Address(ns3::Ipv4Address from)
61 std::stringstream sstream;
66 NetPointNs3::NetPointNs3()
68 static ns3::InternetStackHelper stack;
69 stack.Install(ns3_node_);
72 static void resumeWifiDevice(ns3::Ptr<ns3::WifiNetDevice> device)
74 device->GetPhy()->ResumeFromOff();
81 static void zoneCreation_cb(simgrid::s4u::NetZone const& zone)
83 auto const* wifizone = dynamic_cast<simgrid::kernel::routing::WifiZone*>(zone.get_impl());
84 if (wifizone == nullptr)
88 static ns3::WifiHelper wifi;
89 #if NS3_MINOR_VERSION < 33
90 static ns3::YansWifiPhyHelper wifiPhy = ns3::YansWifiPhyHelper::Default();
92 static ns3::YansWifiPhyHelper wifiPhy;
94 static ns3::YansWifiChannelHelper wifiChannel = ns3::YansWifiChannelHelper::Default();
95 static ns3::WifiMacHelper wifiMac;
96 static ns3::MobilityHelper mobility;
98 #if NS3_MINOR_VERSION < 32
99 wifi.SetStandard(ns3::WIFI_PHY_STANDARD_80211n_5GHZ);
100 #elif NS3_MINOR_VERSION < 36
101 wifi.SetStandard(ns3::WIFI_STANDARD_80211n_5GHZ);
103 wifi.SetStandard(ns3::WIFI_STANDARD_80211n);
104 wifiPhy.Set("ChannelSettings", ns3::StringValue("{0, 0, BAND_5GHZ, 0}"));
107 std::string ssid = wifizone->get_name();
108 const char* mcs = wifizone->get_property("mcs");
109 const char* nss = wifizone->get_property("nss");
110 int mcs_value = mcs ? atoi(mcs) : 3;
111 int nss_value = nss ? atoi(nss) : 1;
112 #if NS3_MINOR_VERSION < 30
113 xbt_assert(nss_value == 1 + (mcs_value / 8),
114 "On NS3 < 3.30, NSS value has to satisfy NSS == 1+(MCS/8) constraint. Bailing out");
116 wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager", "ControlMode", ns3::StringValue("HtMcs0"), "DataMode",
117 ns3::StringValue("HtMcs" + std::to_string(mcs_value)));
118 wifiPhy.SetChannel(wifiChannel.Create());
119 wifiPhy.Set("Antennas", ns3::UintegerValue(nss_value));
120 wifiPhy.Set("MaxSupportedTxSpatialStreams", ns3::UintegerValue(nss_value));
121 wifiPhy.Set("MaxSupportedRxSpatialStreams", ns3::UintegerValue(nss_value));
122 #if NS3_MINOR_VERSION < 33
123 // This fails with "The channel width does not uniquely identify an operating channel" on v3.34,
124 // so we specified the ChannelWidth of wifiPhy to 40, above, when creating wifiPhy with v3.34 and higher
125 ns3::Config::Set("/NodeList/*/DeviceList/*/$ns3::WifiNetDevice/Phy/ChannelWidth", ns3::UintegerValue(40));
126 #elif NS3_MINOR_VERSION < 36
127 wifiPhy.Set("ChannelWidth", ns3::UintegerValue(40));
129 wifiPhy.Set("ChannelSettings", ns3::StringValue("{0, 40, BAND_UNSPECIFIED, 0}"));
131 wifiMac.SetType("ns3::ApWifiMac", "Ssid", ns3::SsidValue(ssid));
133 mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel");
134 ns3::Ptr<ns3::ListPositionAllocator> positionAllocS = ns3::CreateObject<ns3::ListPositionAllocator>();
135 positionAllocS->Add(ns3::Vector(0, 0, 255 * 100 * number_of_networks + 100 * number_of_links));
137 ns3::NetDeviceContainer netDevices;
138 NetPointNs3* access_point_netpoint_ns3 = wifizone->get_access_point()->extension<NetPointNs3>();
140 ns3::Ptr<ns3::Node> access_point_ns3_node = access_point_netpoint_ns3->ns3_node_;
141 ns3::NodeContainer nodes = {access_point_ns3_node};
142 std::vector<NetPointNs3*> hosts_netpoints = {access_point_netpoint_ns3};
143 netDevices.Add(wifi.Install(wifiPhy, wifiMac, access_point_ns3_node));
145 wifiMac.SetType("ns3::StaWifiMac", "Ssid", ns3::SsidValue(ssid), "ActiveProbing", ns3::BooleanValue(false));
147 NetPointNs3* station_netpoint_ns3 = nullptr;
148 ns3::Ptr<ns3::Node> station_ns3_node = nullptr;
151 auto nb_stations = static_cast<double>(wifizone->get_all_hosts().size() - 1);
152 double step = 2 * M_PI / nb_stations;
153 for (const auto* station_host : wifizone->get_all_hosts()) {
154 station_netpoint_ns3 = station_host->get_netpoint()->extension<NetPointNs3>();
155 if (station_netpoint_ns3 == access_point_netpoint_ns3)
157 hosts_netpoints.push_back(station_netpoint_ns3);
158 distance = station_host->get_property("wifi_distance") ? atof(station_host->get_property("wifi_distance")) : 10.0;
159 positionAllocS->Add(ns3::Vector(distance * std::cos(angle), distance * std::sin(angle),
160 255 * 100 * number_of_networks + 100 * number_of_links));
162 station_ns3_node = station_netpoint_ns3->ns3_node_;
163 nodes.Add(station_ns3_node);
164 netDevices.Add(wifi.Install(wifiPhy, wifiMac, station_ns3_node));
167 const char* start_time = wifizone->get_property("start_time");
168 int start_time_value = start_time ? atoi(start_time) : 0;
169 for (uint32_t i = 0; i < netDevices.GetN(); i++) {
170 ns3::Ptr<ns3::WifiNetDevice> device = ns3::StaticCast<ns3::WifiNetDevice>(netDevices.Get(i));
171 device->GetPhy()->SetOffMode();
172 ns3::Simulator::Schedule(ns3::Seconds(start_time_value), &resumeWifiDevice, device);
175 mobility.SetPositionAllocator(positionAllocS);
176 mobility.Install(nodes);
177 ns3::Ipv4AddressHelper address;
178 std::string addr = simgrid::xbt::string_printf("%d.%d.0.0", number_of_networks, number_of_links);
179 address.SetBase(addr.c_str(), "255.255.0.0");
180 XBT_DEBUG("\tInterface stack '%s'", addr.c_str());
181 ns3::Ipv4InterfaceContainer addresses = address.Assign(netDevices);
182 for (unsigned int i = 0; i < hosts_netpoints.size(); i++) {
183 hosts_netpoints[i]->ipv4_address_ = transformIpv4Address(addresses.GetAddress(i));
186 if (number_of_links == 255) {
187 xbt_assert(number_of_networks < 255, "Number of links and networks exceed 255*255");
189 number_of_networks++;
193 /* in theory we can compute the routing table only only once at the platform seal
194 * however put it here since or platform_created signal is called before the seal right now */
195 ns3::Ipv4GlobalRoutingHelper::RecomputeRoutingTables();
198 static void clusterCreation_cb(simgrid::kernel::routing::ClusterCreationArgs const& cluster)
200 ns3::NodeContainer Nodes;
202 xbt_assert(cluster.topology == simgrid::kernel::routing::ClusterTopology::FLAT,
203 "NS-3 is supported only by flat clusters. Do not use with other topologies");
205 for (int const& i : cluster.radicals) {
206 // Create private link
207 std::string host_id = cluster.prefix + std::to_string(i) + cluster.suffix;
208 auto const* src = simgrid::s4u::Host::by_name(host_id)->get_netpoint();
209 auto const* dst = simgrid::s4u::Engine::get_instance()->netpoint_by_name_or_null(cluster.router_id);
210 xbt_assert(dst != nullptr, "No router named %s", cluster.router_id.c_str());
212 ns3_add_direct_route(src, dst, cluster.bw, cluster.lat, cluster.sharing_policy); // Any ns-3 route is symmetrical
214 // Also add the host to the list of hosts that will be connected to the backbone
215 Nodes.Add(src->extension<NetPointNs3>()->ns3_node_);
218 // Create link backbone
220 xbt_assert(Nodes.GetN() <= 65000, "Cluster with ns-3 is limited to 65000 nodes");
221 ns3::CsmaHelper csma;
222 csma.SetChannelAttribute("DataRate",
223 ns3::DataRateValue(ns3::DataRate(
224 static_cast<uint64_t>(cluster.bb_bw * 8)))); // ns-3 takes bps, but we provide Bps
225 csma.SetChannelAttribute("Delay", ns3::TimeValue(ns3::Seconds(cluster.bb_lat)));
226 ns3::NetDeviceContainer devices = csma.Install(Nodes);
227 XBT_DEBUG("Create CSMA");
229 std::string addr = simgrid::xbt::string_printf("%d.%d.0.0", number_of_networks, number_of_links);
230 XBT_DEBUG("Assign IP Addresses %s to CSMA.", addr.c_str());
231 ns3::Ipv4AddressHelper ipv4;
232 ipv4.SetBase(addr.c_str(), "255.255.0.0");
233 ipv4.Assign(devices);
235 if (number_of_links == 255) {
236 xbt_assert(number_of_networks < 255, "Number of links and networks exceed 255*255");
238 number_of_networks++;
244 static void routeCreation_cb(bool symmetrical, const simgrid::kernel::routing::NetPoint* src,
245 const simgrid::kernel::routing::NetPoint* dst,
246 const simgrid::kernel::routing::NetPoint* /*gw_src*/,
247 const simgrid::kernel::routing::NetPoint* /*gw_dst*/,
248 std::vector<simgrid::kernel::resource::StandardLinkImpl*> const& link_list)
250 /* ignoring routes from StarZone, not supported */
251 if (not src || not dst)
254 if (link_list.size() == 1) {
255 auto const* link = static_cast<simgrid::kernel::resource::LinkNS3*>(link_list[0]);
257 XBT_DEBUG("Route from '%s' to '%s' with link '%s' %s %s", src->get_cname(), dst->get_cname(), link->get_cname(),
258 (link->get_sharing_policy() == simgrid::s4u::Link::SharingPolicy::WIFI ? "(wifi)" : "(wired)"),
259 (symmetrical ? "(symmetrical)" : "(not symmetrical)"));
261 XBT_DEBUG("\tLink (%s) bw:%fbps lat:%fs", link->get_cname(), link->get_bandwidth(), link->get_latency());
263 ns3_add_direct_route(src, dst, link->get_bandwidth(), link->get_latency(), link->get_sharing_policy());
264 } else if (static bool warned_about_long_routes = false; not warned_about_long_routes) {
265 XBT_WARN("Ignoring a route between %s and %s of length %zu: Only routes of length 1 are considered with ns-3.\n"
266 "WARNING: You can ignore this warning if your hosts can still communicate when only considering routes "
268 "WARNING: Remove long routes to avoid this harmless message; subsequent long routes will be silently "
270 src->get_cname(), dst->get_cname(), link_list.size());
271 warned_about_long_routes = true;
278 // We can't use SIMGRID_REGISTER_NETWORK_MODEL here because ns-3 has a dash in its name
279 static void XBT_ATTRIB_CONSTRUCTOR(800) simgrid_ns3_network_model_register()
281 simgrid_network_models().add(
282 "ns-3", "Network pseudo-model using the real ns-3 simulator instead of an analytic model", []() {
283 auto net_model = std::make_shared<simgrid::kernel::resource::NetworkNS3Model>("NS3 network model");
284 auto* engine = simgrid::kernel::EngineImpl::get_instance();
285 engine->add_model(net_model);
286 engine->get_netzone_root()->set_network_model(net_model);
290 static simgrid::config::Flag<std::string> ns3_network_model_name("ns3/NetworkModel", {"ns3/TcpModel"},
291 "The ns-3 tcp model can be: NewReno or Cubic",
292 "default", [](const std::string&) {});
293 static simgrid::config::Flag<std::string> ns3_seed(
295 "The random seed provided to ns-3. Either 'time' to seed with time(), blank to not set (default), or a number.", "",
296 [](const std::string& val) {
297 if (val.length() == 0)
299 if (strcasecmp(val.c_str(), "time") == 0) {
300 std::default_random_engine prng(time(nullptr));
301 ns3::RngSeedManager::SetSeed(static_cast<uint32_t>(prng()));
302 ns3::RngSeedManager::SetRun(static_cast<uint64_t>(prng()));
304 auto v = static_cast<int>(xbt_str_parse_int(
305 val.c_str(), "Invalid value for option ns3/seed. It must be either 'time', a number, or left empty."));
306 ns3::RngSeedManager::SetSeed(v);
307 ns3::RngSeedManager::SetRun(v);
312 namespace kernel::resource {
314 NetworkNS3Model::NetworkNS3Model(const std::string& name) : NetworkModel(name)
316 xbt_assert(not sg_link_energy_is_inited(),
317 "LinkEnergy plugin and ns-3 network models are not compatible. Are you looking for Ecofen, maybe?");
319 NetPointNs3::EXTENSION_ID = routing::NetPoint::extension_create<NetPointNs3>();
320 auto const& NetworkProtocol = ns3_network_model_name.get();
322 if (NetworkProtocol == "UDP") {
324 UdpEchoClientApplication=0
325 UdpEchoServerApplication=0
331 LogComponentEnable("UdpSocket", ns3::LOG_LEVEL_DEBUG);
332 LogComponentEnable("UdpL4Protocol", ns3::LOG_LEVEL_DEBUG);
334 ns3::Config::SetDefault("ns3::TcpSocket::SegmentSize", ns3::UintegerValue(1000));
335 ns3::Config::SetDefault("ns3::TcpSocket::DelAckCount", ns3::UintegerValue(1));
336 ns3::Config::SetDefault("ns3::TcpSocketBase::Timestamp", ns3::BooleanValue(false));
339 if (NetworkProtocol == "NewReno" || NetworkProtocol == "Cubic") {
340 XBT_INFO("Switching Tcp protocol to '%s'", NetworkProtocol.c_str());
341 ns3::Config::SetDefault("ns3::TcpL4Protocol::SocketType", ns3::StringValue("ns3::Tcp" + NetworkProtocol));
343 } else if (NetworkProtocol == "UDP") {
344 XBT_INFO("Switching network protocol to UDP.");
346 } else if (NetworkProtocol != "default") {
347 xbt_die("The ns3/NetworkModel must be: NewReno, Cubic or UDP but it's '%s'", NetworkProtocol.c_str());
350 routing::NetPoint::on_creation.connect([](routing::NetPoint& pt) {
351 pt.extension_set<NetPointNs3>(new NetPointNs3());
352 XBT_VERB("Declare SimGrid's %s within ns-3", pt.get_cname());
355 s4u::Engine::on_platform_created_cb([]() {
356 /* Create the ns3 topology based on routing strategy */
357 ns3::GlobalRouteManager::BuildGlobalRoutingDatabase();
358 ns3::GlobalRouteManager::InitializeRoutes();
360 routing::on_cluster_creation.connect(&clusterCreation_cb);
361 routing::NetZoneImpl::on_route_creation.connect(&routeCreation_cb);
362 s4u::NetZone::on_seal_cb(&zoneCreation_cb);
365 NetworkNS3Model::~NetworkNS3Model()
367 ns3::Simulator::Destroy();
370 StandardLinkImpl* NetworkNS3Model::create_link(const std::string& name, const std::vector<double>& bandwidths)
372 xbt_assert(bandwidths.size() == 1, "ns-3 links must use only 1 bandwidth.");
373 auto* link = new LinkNS3(name, bandwidths[0]);
374 link->set_model(this);
378 StandardLinkImpl* NetworkNS3Model::create_wifi_link(const std::string& name, const std::vector<double>& bandwidths)
380 auto* link = create_link(name, bandwidths);
381 link->set_sharing_policy(s4u::Link::SharingPolicy::WIFI, {});
385 Action* NetworkNS3Model::communicate(s4u::Host* src, s4u::Host* dst, double size, double rate, bool /*streamed*/)
387 xbt_assert(rate == -1,
388 "Communication over ns-3 links cannot specify a specific rate. Please use -1 as a value instead of %f.",
390 return new NetworkNS3Action(this, size, src, dst);
393 #if SIMGRID_HAVE_NS3_GetNextEventTime
394 /* If patched, ns3 is idempotent and nice to use */
395 bool NetworkNS3Model::next_occurring_event_is_idempotent()
400 double NetworkNS3Model::next_occurring_event(double sg_time)
402 if (get_started_action_set()->empty()) {
406 double ns3_time = ns3::Simulator::GetNextEventTime().GetSeconds();
407 XBT_DEBUG("NS3 tells that the next occuring event is at %f (it's %f in SimGrid), so NS3 returns a delta of %f.",
408 ns3_time, sg_time, ns3_time - sg_time);
409 return ns3_time - sg_time;
412 /* NS3 is only idempotent with the appropriate patch */
413 bool NetworkNS3Model::next_occurring_event_is_idempotent()
418 double NetworkNS3Model::next_occurring_event(double now)
420 double time_to_next_flow_completion = 0.0;
421 XBT_DEBUG("ns3_next_occurring_event");
423 // get the first relevant value from the running_actions list
425 // If there is no comms in NS-3, then we do not move it forward.
426 // We will synchronize NS-3 with SimGrid when starting a new communication.
427 // (see NetworkNS3Action::NetworkNS3Action() for more details on this point)
428 if (get_started_action_set()->empty() || now == 0.0)
431 XBT_DEBUG("doing a ns3 simulation for a duration of %f", now);
433 time_to_next_flow_completion = ns3::Simulator::Now().GetSeconds() - EngineImpl::get_clock();
434 // NS-3 stops as soon as a flow ends,
435 // but it does not process the other flows that may finish at the same (simulated) time.
436 // If another flow ends at the same time, time_to_next_flow_completion = 0
437 if (double_equals(time_to_next_flow_completion, 0, sg_precision_timing))
438 time_to_next_flow_completion = 0.0;
440 XBT_DEBUG("min : %f", now);
441 XBT_DEBUG("ns-3 time : %f", ns3::Simulator::Now().GetSeconds());
442 XBT_DEBUG("simgrid time: %f", EngineImpl::get_clock());
443 XBT_DEBUG("Next completion %f :", time_to_next_flow_completion);
445 return time_to_next_flow_completion;
449 void NetworkNS3Model::update_actions_state(double now, double delta)
451 static std::vector<std::string> socket_to_destroy;
453 #if SIMGRID_HAVE_NS3_GetNextEventTime
454 /* If the ns-3 model is idempotent, it won't get updated in next_occurring_event() */
457 XBT_DEBUG("DO START simulator delta: %f (current simgrid time: %f; current ns3 time: %f)", delta,
458 simgrid::kernel::EngineImpl::get_clock(), ns3::Simulator::Now().GetSeconds());
459 ns3_simulator(delta);
461 XBT_DEBUG("don't start simulator delta: %f (current simgrid time: %f; current ns3 time: %f)", delta,
462 simgrid::kernel::EngineImpl::get_clock(), ns3::Simulator::Now().GetSeconds());
466 for (const auto& [ns3_socket, sgFlow] : flow_from_sock) {
467 NetworkNS3Action* action = sgFlow->action_;
468 XBT_DEBUG("Processing flow %p (socket %s, action %p)", sgFlow, ns3_socket.c_str(), action);
469 // Because NS3 stops as soon as a flow is finished, the other flows that ends at the same time may remains in an
470 // inconsistent state (i.e. remains_ == 0 but finished_ == false).
471 // However, SimGrid considers sometimes that an action with remains_ == 0 is finished.
472 // Thus, to avoid inconsistencies between SimGrid and NS3, set remains to 0 only when the flow is finished in NS3
473 double remains = action->get_cost() - sgFlow->sent_bytes_;
475 action->set_remains(remains);
477 if (TRACE_is_enabled() && action->get_state() == kernel::resource::Action::State::STARTED) {
478 double data_delta_sent = sgFlow->sent_bytes_ - action->last_sent_;
480 std::vector<StandardLinkImpl*> route;
481 action->get_src().route_to(&action->get_dst(), route, nullptr);
482 for (auto const* link : route)
483 instr::resource_set_utilization("LINK", "bandwidth_used", link->get_cname(), action->get_category(),
484 data_delta_sent / delta, now - delta, delta);
486 action->last_sent_ = sgFlow->sent_bytes_;
489 if ((sgFlow->finished_) && (remains <= 0)) { // finished_ should not become true before remains gets to 0, but it
490 // sometimes does. Let's play safe, here.
491 socket_to_destroy.push_back(ns3_socket);
492 XBT_DEBUG("Destroy socket %s of action %p", ns3_socket.c_str(), action);
493 action->set_remains(0);
494 action->finish(Action::State::FINISHED);
496 XBT_DEBUG("Socket %s sent %u bytes out of %u (%u remaining)", ns3_socket.c_str(), sgFlow->sent_bytes_,
497 sgFlow->total_bytes_, sgFlow->remaining_);
501 while (not socket_to_destroy.empty()) {
502 std::string ns3_socket = socket_to_destroy.back();
503 socket_to_destroy.pop_back();
504 SgFlow* flow = flow_from_sock.at(ns3_socket);
505 if (XBT_LOG_ISENABLED(res_ns3, xbt_log_priority_debug)) {
506 XBT_DEBUG("Removing socket %s of action %p", ns3_socket.c_str(), flow->action_);
509 flow_from_sock.erase(ns3_socket);
517 LinkNS3::LinkNS3(const std::string& name, double bandwidth) : StandardLinkImpl(name)
519 bandwidth_.peak = bandwidth;
522 LinkNS3::~LinkNS3() = default;
524 void LinkNS3::apply_event(profile::Event*, double)
529 void LinkNS3::set_bandwidth_profile(profile::Profile* profile)
531 xbt_assert(profile == nullptr, "The ns-3 network model doesn't support bandwidth profiles");
534 void LinkNS3::set_latency_profile(profile::Profile* profile)
536 xbt_assert(profile == nullptr, "The ns-3 network model doesn't support latency profiles");
539 void LinkNS3::set_latency(double latency)
541 latency_.peak = latency;
544 void LinkNS3::set_sharing_policy(s4u::Link::SharingPolicy policy, const s4u::NonLinearResourceCb& cb)
546 sharing_policy_ = policy;
552 NetworkNS3Action::NetworkNS3Action(Model* model, double totalBytes, s4u::Host* src, s4u::Host* dst)
553 : NetworkAction(model, *src, *dst, totalBytes, false)
555 // ns-3 fails when src = dst, so avoid the problem by considering that communications are infinitely fast on the
556 // loopback that does not exists
558 if (static bool warned = false; not warned) {
559 XBT_WARN("Sending from a host %s to itself is not supported by ns-3. Every such communication finishes "
560 "immediately upon startup in the SimGrid+ns-3 system.",
564 finish(Action::State::FINISHED);
568 // If there is no other started actions, we need to move NS-3 forward to be sync with SimGrid
569 if (model->get_started_action_set()->size() == 1) {
570 while (double_positive(EngineImpl::get_clock() - ns3::Simulator::Now().GetSeconds(), sg_precision_timing)) {
571 XBT_DEBUG("Synchronizing NS-3 (time %f) with SimGrid (time %f)", ns3::Simulator::Now().GetSeconds(),
572 EngineImpl::get_clock());
573 ns3_simulator(EngineImpl::get_clock() - ns3::Simulator::Now().GetSeconds());
577 static uint16_t port_number = 1;
579 ns3::Ptr<ns3::Node> src_node = get_ns3node_from_sghost(src);
580 ns3::Ptr<ns3::Node> dst_node = get_ns3node_from_sghost(dst);
582 const std::string& addr = dst->get_netpoint()->extension<NetPointNs3>()->ipv4_address_;
583 xbt_assert(not addr.empty(), "Element %s is unknown to ns-3. Is it connected to any one-hop link?",
584 dst->get_netpoint()->get_cname());
586 ns3::PacketSinkHelper sink("ns3::TcpSocketFactory", ns3::InetSocketAddress(ns3::Ipv4Address::GetAny(), port_number));
587 sink.Install(dst_node);
589 ns3::Ptr<ns3::Socket> sock = ns3::Socket::CreateSocket(src_node, ns3::TcpSocketFactory::GetTypeId());
591 auto sock_addr = transform_socket_ptr(sock);
592 XBT_DEBUG("Create socket %s for a flow of %.0f Bytes from %s to %s with Interface %s", sock_addr.c_str(), totalBytes,
593 src->get_cname(), dst->get_cname(), addr.c_str());
595 flow_from_sock.try_emplace(sock_addr, new SgFlow(static_cast<uint32_t>(totalBytes), this));
597 sock->Bind(ns3::InetSocketAddress(port_number));
599 ns3::Simulator::ScheduleNow(&start_flow, sock, addr.c_str(), port_number);
601 port_number = 1 + (port_number % UINT16_MAX);
602 if (port_number == 1)
603 XBT_WARN("Too many connections! Port number is saturated. Trying to use the oldest ports.");
606 void NetworkNS3Action::suspend()
611 void NetworkNS3Action::resume()
616 std::list<StandardLinkImpl*> NetworkNS3Action::get_links() const
620 void NetworkNS3Action::update_remains_lazy(double /*now*/)
625 } // namespace kernel::resource
627 ns3::Ptr<ns3::Node> get_ns3node_from_sghost(const simgrid::s4u::Host* host)
629 auto* netext = host->get_netpoint()->extension<NetPointNs3>();
630 xbt_assert(netext != nullptr, "Please only use this function on ns-3 nodes");
631 return netext->ns3_node_;
633 } // namespace simgrid
635 void ns3_simulator(double maxSeconds) // maxSecond is a delay, not an absolute time
638 if (maxSeconds >= 0.0) // If there is a maximum amount of time to run
639 id = ns3::Simulator::Schedule(ns3::Seconds(maxSeconds), &ns3::Simulator::Stop);
641 XBT_DEBUG("Start simulator for at most %fs (current simgrid time: %f; current ns3 time: %f)", maxSeconds,
642 simgrid::kernel::EngineImpl::get_clock(), ns3::Simulator::Now().GetSeconds());
643 #if SIMGRID_HAVE_NS3_GetNextEventTime
644 xbt_assert(maxSeconds >= 0.0);
646 ns3::Simulator::Run();
647 XBT_DEBUG("ns3 simulator stopped at %fs", ns3::Simulator::Now().GetSeconds());
649 if (maxSeconds >= 0.0)
653 void ns3_add_direct_route(const simgrid::kernel::routing::NetPoint* src, const simgrid::kernel::routing::NetPoint* dst,
654 double bw, double lat, simgrid::s4u::Link::SharingPolicy policy)
656 ns3::Ipv4AddressHelper address;
657 ns3::NetDeviceContainer netA;
660 auto* host_src = src->extension<NetPointNs3>();
661 auto* host_dst = dst->extension<NetPointNs3>();
663 xbt_assert(host_src != nullptr, "Network element %s does not seem to be ns-3-ready", src->get_cname());
664 xbt_assert(host_dst != nullptr, "Network element %s does not seem to be ns-3-ready", dst->get_cname());
666 xbt_assert(policy != simgrid::s4u::Link::SharingPolicy::WIFI,
667 "The wifi sharing policy is not supported for links. You want to use a wifi zone (see documentation).");
669 ns3::PointToPointHelper pointToPoint;
671 XBT_DEBUG("\tAdd PTP from %s to %s bw:'%f Bps' lat:'%fs'", src->get_cname(), dst->get_cname(), bw, lat);
672 pointToPoint.SetDeviceAttribute(
674 ns3::DataRateValue(ns3::DataRate(static_cast<uint64_t>(bw * 8)))); // ns-3 takes bps, but we provide Bps
675 pointToPoint.SetChannelAttribute("Delay", ns3::TimeValue(ns3::Seconds(lat)));
677 netA.Add(pointToPoint.Install(host_src->ns3_node_, host_dst->ns3_node_));
679 std::string addr = simgrid::xbt::string_printf("%d.%d.0.0", number_of_networks, number_of_links);
680 address.SetBase(addr.c_str(), "255.255.0.0");
681 XBT_DEBUG("\tInterface stack '%s'", addr.c_str());
683 auto addresses = address.Assign(netA);
685 host_src->ipv4_address_ = transformIpv4Address(addresses.GetAddress(0));
686 host_dst->ipv4_address_ = transformIpv4Address(addresses.GetAddress(1));
688 if (number_of_links == 255) {
689 xbt_assert(number_of_networks < 255, "Number of links and networks exceed 255*255");
691 number_of_networks++;