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 "xbt/config.hpp"
14 #include "xbt/string.hpp"
15 #include "xbt/utility.hpp"
17 #include <ns3/application-container.h>
18 #include <ns3/core-module.h>
19 #include <ns3/csma-helper.h>
20 #include <ns3/event-id.h>
21 #include <ns3/global-route-manager.h>
22 #include <ns3/internet-stack-helper.h>
23 #include <ns3/ipv4-address-helper.h>
24 #include <ns3/ipv4-global-routing-helper.h>
25 #include <ns3/packet-sink-helper.h>
26 #include <ns3/point-to-point-helper.h>
28 #include "ns3/mobility-module.h"
29 #include "ns3/wifi-module.h"
31 #include "network_ns3.hpp"
32 #include "src/surf/ns3/ns3_simulator.hpp"
34 #include "simgrid/kernel/routing/NetPoint.hpp"
35 #include "simgrid/kernel/routing/NetZoneImpl.hpp"
36 #include "simgrid/kernel/routing/WifiZone.hpp"
37 #include "simgrid/plugins/energy.h"
38 #include "simgrid/s4u/Engine.hpp"
39 #include "simgrid/s4u/NetZone.hpp"
40 #include "src/instr/instr_private.hpp" // TRACE_is_enabled(). FIXME: remove by subscribing tracing to the surf signals
41 #include "src/kernel/EngineImpl.hpp"
42 #include "src/surf/xml/platf_private.hpp" // ClusterCreationArgs
44 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(res_ns3, res_network, "Network model based on ns-3");
50 extern std::map<std::string, SgFlow*, std::less<>> flow_from_sock;
51 extern std::map<std::string, ns3::ApplicationContainer, std::less<>> sink_from_sock;
53 static int number_of_links = 1;
54 static int number_of_networks = 1;
56 simgrid::xbt::Extension<simgrid::kernel::routing::NetPoint, NetPointNs3> NetPointNs3::EXTENSION_ID;
58 static std::string transformIpv4Address(ns3::Ipv4Address from)
60 std::stringstream sstream;
65 NetPointNs3::NetPointNs3()
67 static ns3::InternetStackHelper stack;
68 stack.Install(ns3_node_);
71 static void resumeWifiDevice(ns3::Ptr<ns3::WifiNetDevice> device)
73 device->GetPhy()->ResumeFromOff();
80 static void zoneCreation_cb(simgrid::s4u::NetZone const& zone)
82 auto const* wifizone = dynamic_cast<simgrid::kernel::routing::WifiZone*>(zone.get_impl());
83 if (wifizone == nullptr)
87 static ns3::WifiHelper wifi;
88 #if NS3_MINOR_VERSION < 33
89 static ns3::YansWifiPhyHelper wifiPhy = ns3::YansWifiPhyHelper::Default();
91 static ns3::YansWifiPhyHelper wifiPhy;
93 static ns3::YansWifiChannelHelper wifiChannel = ns3::YansWifiChannelHelper::Default();
94 static ns3::WifiMacHelper wifiMac;
95 static ns3::MobilityHelper mobility;
97 #if NS3_MINOR_VERSION < 32
98 wifi.SetStandard(ns3::WIFI_PHY_STANDARD_80211n_5GHZ);
99 #elif NS3_MINOR_VERSION < 36
100 wifi.SetStandard(ns3::WIFI_STANDARD_80211n_5GHZ);
102 wifi.SetStandard(ns3::WIFI_STANDARD_80211n);
103 wifiPhy.Set("ChannelSettings", ns3::StringValue("{0, 0, BAND_5GHZ, 0}"));
106 std::string ssid = wifizone->get_name();
107 const char* mcs = wifizone->get_property("mcs");
108 const char* nss = wifizone->get_property("nss");
109 int mcs_value = mcs ? atoi(mcs) : 3;
110 int nss_value = nss ? atoi(nss) : 1;
111 #if NS3_MINOR_VERSION < 30
112 xbt_assert(nss_value == 1 + (mcs_value / 8),
113 "On NS3 < 3.30, NSS value has to satisfy NSS == 1+(MCS/8) constraint. Bailing out");
115 wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager", "ControlMode", ns3::StringValue("HtMcs0"), "DataMode",
116 ns3::StringValue("HtMcs" + std::to_string(mcs_value)));
117 wifiPhy.SetChannel(wifiChannel.Create());
118 wifiPhy.Set("Antennas", ns3::UintegerValue(nss_value));
119 wifiPhy.Set("MaxSupportedTxSpatialStreams", ns3::UintegerValue(nss_value));
120 wifiPhy.Set("MaxSupportedRxSpatialStreams", ns3::UintegerValue(nss_value));
121 #if NS3_MINOR_VERSION > 33
122 wifiPhy.Set("ChannelWidth", ns3::UintegerValue(40));
124 wifiMac.SetType("ns3::ApWifiMac", "Ssid", ns3::SsidValue(ssid));
126 mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel");
127 ns3::Ptr<ns3::ListPositionAllocator> positionAllocS = ns3::CreateObject<ns3::ListPositionAllocator>();
128 positionAllocS->Add(ns3::Vector(0, 0, 255 * 100 * number_of_networks + 100 * number_of_links));
130 ns3::NetDeviceContainer netDevices;
131 NetPointNs3* access_point_netpoint_ns3 = wifizone->get_access_point()->extension<NetPointNs3>();
133 ns3::Ptr<ns3::Node> access_point_ns3_node = access_point_netpoint_ns3->ns3_node_;
134 ns3::NodeContainer nodes = {access_point_ns3_node};
135 std::vector<NetPointNs3*> hosts_netpoints = {access_point_netpoint_ns3};
136 netDevices.Add(wifi.Install(wifiPhy, wifiMac, access_point_ns3_node));
138 wifiMac.SetType("ns3::StaWifiMac", "Ssid", ns3::SsidValue(ssid), "ActiveProbing", ns3::BooleanValue(false));
140 NetPointNs3* station_netpoint_ns3 = nullptr;
141 ns3::Ptr<ns3::Node> station_ns3_node = nullptr;
144 auto nb_stations = static_cast<double>(wifizone->get_all_hosts().size() - 1);
145 double step = 2 * M_PI / nb_stations;
146 for (const auto* station_host : wifizone->get_all_hosts()) {
147 station_netpoint_ns3 = station_host->get_netpoint()->extension<NetPointNs3>();
148 if (station_netpoint_ns3 == access_point_netpoint_ns3)
150 hosts_netpoints.push_back(station_netpoint_ns3);
151 distance = station_host->get_property("wifi_distance") ? atof(station_host->get_property("wifi_distance")) : 10.0;
152 positionAllocS->Add(ns3::Vector(distance * std::cos(angle), distance * std::sin(angle),
153 255 * 100 * number_of_networks + 100 * number_of_links));
155 station_ns3_node = station_netpoint_ns3->ns3_node_;
156 nodes.Add(station_ns3_node);
157 netDevices.Add(wifi.Install(wifiPhy, wifiMac, station_ns3_node));
160 const char* start_time = wifizone->get_property("start_time");
161 int start_time_value = start_time ? atoi(start_time) : 0;
162 for (uint32_t i = 0; i < netDevices.GetN(); i++) {
163 ns3::Ptr<ns3::WifiNetDevice> device = ns3::StaticCast<ns3::WifiNetDevice>(netDevices.Get(i));
164 device->GetPhy()->SetOffMode();
165 ns3::Simulator::Schedule(ns3::Seconds(start_time_value), &resumeWifiDevice, device);
168 #if NS3_MINOR_VERSION < 33
169 // This fails with "The channel width does not uniquely identify an operating channel" on v3.34,
170 // so we specified the ChannelWidth of wifiPhy to 40, above, when creating wifiPhy with v3.34 and higher
171 ns3::Config::Set("/NodeList/*/DeviceList/*/$ns3::WifiNetDevice/Phy/ChannelWidth", ns3::UintegerValue(40));
174 mobility.SetPositionAllocator(positionAllocS);
175 mobility.Install(nodes);
176 ns3::Ipv4AddressHelper address;
177 std::string addr = simgrid::xbt::string_printf("%d.%d.0.0", number_of_networks, number_of_links);
178 address.SetBase(addr.c_str(), "255.255.0.0");
179 XBT_DEBUG("\tInterface stack '%s'", addr.c_str());
180 ns3::Ipv4InterfaceContainer addresses = address.Assign(netDevices);
181 for (unsigned int i = 0; i < hosts_netpoints.size(); i++) {
182 hosts_netpoints[i]->ipv4_address_ = transformIpv4Address(addresses.GetAddress(i));
185 if (number_of_links == 255) {
186 xbt_assert(number_of_networks < 255, "Number of links and networks exceed 255*255");
188 number_of_networks++;
192 /* in theory we can compute the routing table only only once at the platform seal
193 * however put it here since or platform_created signal is called before the seal right now */
194 ns3::Ipv4GlobalRoutingHelper::RecomputeRoutingTables();
197 static void clusterCreation_cb(simgrid::kernel::routing::ClusterCreationArgs const& cluster)
199 ns3::NodeContainer Nodes;
201 xbt_assert(cluster.topology == simgrid::kernel::routing::ClusterTopology::FLAT,
202 "NS-3 is supported only by flat clusters. Do not use with other topologies");
204 for (int const& i : cluster.radicals) {
205 // Create private link
206 std::string host_id = cluster.prefix + std::to_string(i) + cluster.suffix;
207 auto const* src = simgrid::s4u::Host::by_name(host_id)->get_netpoint();
208 auto const* dst = simgrid::s4u::Engine::get_instance()->netpoint_by_name_or_null(cluster.router_id);
209 xbt_assert(dst != nullptr, "No router named %s", cluster.router_id.c_str());
211 ns3_add_direct_route(src, dst, cluster.bw, cluster.lat, cluster.sharing_policy); // Any ns-3 route is symmetrical
213 // Also add the host to the list of hosts that will be connected to the backbone
214 Nodes.Add(src->extension<NetPointNs3>()->ns3_node_);
217 // Create link backbone
219 xbt_assert(Nodes.GetN() <= 65000, "Cluster with ns-3 is limited to 65000 nodes");
220 ns3::CsmaHelper csma;
221 csma.SetChannelAttribute("DataRate",
222 ns3::DataRateValue(ns3::DataRate(
223 static_cast<uint64_t>(cluster.bb_bw * 8)))); // ns-3 takes bps, but we provide Bps
224 csma.SetChannelAttribute("Delay", ns3::TimeValue(ns3::Seconds(cluster.bb_lat)));
225 ns3::NetDeviceContainer devices = csma.Install(Nodes);
226 XBT_DEBUG("Create CSMA");
228 std::string addr = simgrid::xbt::string_printf("%d.%d.0.0", number_of_networks, number_of_links);
229 XBT_DEBUG("Assign IP Addresses %s to CSMA.", addr.c_str());
230 ns3::Ipv4AddressHelper ipv4;
231 ipv4.SetBase(addr.c_str(), "255.255.0.0");
232 ipv4.Assign(devices);
234 if (number_of_links == 255) {
235 xbt_assert(number_of_networks < 255, "Number of links and networks exceed 255*255");
237 number_of_networks++;
243 static void routeCreation_cb(bool symmetrical, const simgrid::kernel::routing::NetPoint* src,
244 const simgrid::kernel::routing::NetPoint* dst,
245 const simgrid::kernel::routing::NetPoint* /*gw_src*/,
246 const simgrid::kernel::routing::NetPoint* /*gw_dst*/,
247 std::vector<simgrid::kernel::resource::StandardLinkImpl*> const& link_list)
249 /* ignoring routes from StarZone, not supported */
250 if (not src || not dst)
253 if (link_list.size() == 1) {
254 auto const* link = static_cast<simgrid::kernel::resource::LinkNS3*>(link_list[0]);
256 XBT_DEBUG("Route from '%s' to '%s' with link '%s' %s %s", src->get_cname(), dst->get_cname(), link->get_cname(),
257 (link->get_sharing_policy() == simgrid::s4u::Link::SharingPolicy::WIFI ? "(wifi)" : "(wired)"),
258 (symmetrical ? "(symmetrical)" : "(not symmetrical)"));
260 XBT_DEBUG("\tLink (%s) bw:%fbps lat:%fs", link->get_cname(), link->get_bandwidth(), link->get_latency());
262 ns3_add_direct_route(src, dst, link->get_bandwidth(), link->get_latency(), link->get_sharing_policy());
263 } else if (static bool warned_about_long_routes = false; not warned_about_long_routes) {
264 XBT_WARN("Ignoring a route between %s and %s of length %zu: Only routes of length 1 are considered with ns-3.\n"
265 "WARNING: You can ignore this warning if your hosts can still communicate when only considering routes "
267 "WARNING: Remove long routes to avoid this harmless message; subsequent long routes will be silently "
269 src->get_cname(), dst->get_cname(), link_list.size());
270 warned_about_long_routes = true;
277 // We can't use SIMGRID_REGISTER_NETWORK_MODEL here because ns-3 has a dash in its name
278 static void XBT_ATTRIB_CONSTRUCTOR(800) simgrid_ns3_network_model_register()
280 simgrid_network_models().add(
281 "ns-3", "Network pseudo-model using the real ns-3 simulator instead of an analytic model", []() {
282 auto net_model = std::make_shared<simgrid::kernel::resource::NetworkNS3Model>("NS3 network model");
283 auto* engine = simgrid::kernel::EngineImpl::get_instance();
284 engine->add_model(net_model);
285 engine->get_netzone_root()->set_network_model(net_model);
289 static simgrid::config::Flag<std::string>
290 ns3_tcp_model("ns3/TcpModel", "The ns-3 tcp model can be: NewReno or Reno or Tahoe", "default");
291 static simgrid::config::Flag<std::string> ns3_seed(
293 "The random seed provided to ns-3. Either 'time' to seed with time(), blank to not set (default), or a number.", "",
294 [](const std::string& val) {
295 if (val.length() == 0)
297 if (strcasecmp(val.c_str(), "time") == 0) {
298 std::default_random_engine prng(time(nullptr));
299 ns3::RngSeedManager::SetSeed(static_cast<uint32_t>(prng()));
300 ns3::RngSeedManager::SetRun(static_cast<uint64_t>(prng()));
302 auto v = static_cast<int>(xbt_str_parse_int(
303 val.c_str(), "Invalid value for option ns3/seed. It must be either 'time', a number, or left empty."));
304 ns3::RngSeedManager::SetSeed(v);
305 ns3::RngSeedManager::SetRun(v);
310 namespace kernel::resource {
312 NetworkNS3Model::NetworkNS3Model(const std::string& name) : NetworkModel(name)
314 xbt_assert(not sg_link_energy_is_inited(),
315 "LinkEnergy plugin and ns-3 network models are not compatible. Are you looking for Ecofen, maybe?");
317 NetPointNs3::EXTENSION_ID = routing::NetPoint::extension_create<NetPointNs3>();
319 ns3::Config::SetDefault("ns3::TcpSocket::SegmentSize", ns3::UintegerValue(1000));
320 ns3::Config::SetDefault("ns3::TcpSocket::DelAckCount", ns3::UintegerValue(1));
321 ns3::Config::SetDefault("ns3::TcpSocketBase::Timestamp", ns3::BooleanValue(false));
323 if (auto const& TcpProtocol = ns3_tcp_model.get(); TcpProtocol == "default") {
326 } else if (TcpProtocol == "Reno" || TcpProtocol == "NewReno" || TcpProtocol == "Tahoe") {
327 XBT_INFO("Switching Tcp protocol to '%s'", TcpProtocol.c_str());
328 ns3::Config::SetDefault("ns3::TcpL4Protocol::SocketType", ns3::StringValue("ns3::Tcp" + TcpProtocol));
331 xbt_die("The ns3/TcpModel must be: NewReno or Reno or Tahoe");
334 routing::NetPoint::on_creation.connect([](routing::NetPoint& pt) {
335 pt.extension_set<NetPointNs3>(new NetPointNs3());
336 XBT_VERB("Declare SimGrid's %s within ns-3", pt.get_cname());
339 s4u::Engine::on_platform_created_cb([]() {
340 /* Create the ns3 topology based on routing strategy */
341 ns3::GlobalRouteManager::DeleteGlobalRoutes(); // just in case this callback is called twice
342 ns3::GlobalRouteManager::BuildGlobalRoutingDatabase();
343 ns3::GlobalRouteManager::InitializeRoutes();
345 routing::on_cluster_creation.connect(&clusterCreation_cb);
346 routing::NetZoneImpl::on_route_creation.connect(&routeCreation_cb);
347 s4u::NetZone::on_seal_cb(&zoneCreation_cb);
350 NetworkNS3Model::~NetworkNS3Model()
352 ns3::Simulator::Destroy();
355 StandardLinkImpl* NetworkNS3Model::create_link(const std::string& name, const std::vector<double>& bandwidths)
357 xbt_assert(bandwidths.size() == 1, "ns-3 links must use only 1 bandwidth.");
358 auto* link = new LinkNS3(name, bandwidths[0]);
359 link->set_model(this);
363 StandardLinkImpl* NetworkNS3Model::create_wifi_link(const std::string& name, const std::vector<double>& bandwidths)
365 auto* link = create_link(name, bandwidths);
366 link->set_sharing_policy(s4u::Link::SharingPolicy::WIFI, {});
370 Action* NetworkNS3Model::communicate(s4u::Host* src, s4u::Host* dst, double size, double rate, bool /*streamed*/)
372 xbt_assert(rate == -1,
373 "Communication over ns-3 links cannot specify a specific rate. Please use -1 as a value instead of %f.",
375 return new NetworkNS3Action(this, size, src, dst);
378 double NetworkNS3Model::next_occurring_event(double now)
380 double time_to_next_flow_completion = 0.0;
381 XBT_DEBUG("ns3_next_occurring_event");
383 // get the first relevant value from the running_actions list
385 // If there is no comms in NS-3, then we do not move it forward.
386 // We will synchronize NS-3 with SimGrid when starting a new communication.
387 // (see NetworkNS3Action::NetworkNS3Action() for more details on this point)
388 if (get_started_action_set()->empty() || now == 0.0)
391 XBT_DEBUG("doing a ns3 simulation for a duration of %f", now);
393 time_to_next_flow_completion = ns3::Simulator::Now().GetSeconds() - EngineImpl::get_clock();
394 // NS-3 stops as soon as a flow ends,
395 // but it does not process the other flows that may finish at the same (simulated) time.
396 // If another flow ends at the same time, time_to_next_flow_completion = 0
397 if (double_equals(time_to_next_flow_completion, 0, sg_precision_timing))
398 time_to_next_flow_completion = 0.0;
400 XBT_DEBUG("min : %f", now);
401 XBT_DEBUG("ns3 time : %f", ns3::Simulator::Now().GetSeconds());
402 XBT_DEBUG("surf time : %f", EngineImpl::get_clock());
403 XBT_DEBUG("Next completion %f :", time_to_next_flow_completion);
405 return time_to_next_flow_completion;
408 void NetworkNS3Model::update_actions_state(double now, double delta)
410 static std::vector<std::string> socket_to_destroy;
412 for (const auto& [ns3_socket, sgFlow] : flow_from_sock) {
413 NetworkNS3Action* action = sgFlow->action_;
414 XBT_DEBUG("Processing flow %p (socket %s, action %p)", sgFlow, ns3_socket.c_str(), action);
415 // Because NS3 stops as soon as a flow is finished, the other flows that ends at the same time may remains in an
416 // inconsistent state (i.e. remains_ == 0 but finished_ == false).
417 // However, SimGrid considers sometimes that an action with remains_ == 0 is finished.
418 // Thus, to avoid inconsistencies between SimGrid and NS3, set remains to 0 only when the flow is finished in NS3
419 double remains = action->get_cost() - sgFlow->sent_bytes_;
421 action->set_remains(remains);
423 if (TRACE_is_enabled() && action->get_state() == kernel::resource::Action::State::STARTED) {
424 double data_delta_sent = sgFlow->sent_bytes_ - action->last_sent_;
426 std::vector<StandardLinkImpl*> route;
427 action->get_src().route_to(&action->get_dst(), route, nullptr);
428 for (auto const& link : route)
429 instr::resource_set_utilization("LINK", "bandwidth_used", link->get_cname(), action->get_category(),
430 data_delta_sent / delta, now - delta, delta);
432 action->last_sent_ = sgFlow->sent_bytes_;
435 if ((sgFlow->finished_) && (remains <= 0)) { // finished_ should not become true before remains gets to 0, but it
436 // sometimes does. Let's play safe, here.
437 socket_to_destroy.push_back(ns3_socket);
438 XBT_DEBUG("Destroy socket %s of action %p", ns3_socket.c_str(), action);
439 action->set_remains(0);
440 action->finish(Action::State::FINISHED);
442 XBT_DEBUG("Socket %s sent %u bytes out of %u (%u remaining)", ns3_socket.c_str(), sgFlow->sent_bytes_,
443 sgFlow->total_bytes_, sgFlow->remaining_);
447 while (not socket_to_destroy.empty()) {
448 std::string ns3_socket = socket_to_destroy.back();
449 socket_to_destroy.pop_back();
450 SgFlow* flow = flow_from_sock.at(ns3_socket);
451 if (XBT_LOG_ISENABLED(res_ns3, xbt_log_priority_debug)) {
452 XBT_DEBUG("Removing socket %s of action %p", ns3_socket.c_str(), flow->action_);
455 flow_from_sock.erase(ns3_socket);
456 sink_from_sock.erase(ns3_socket);
464 LinkNS3::LinkNS3(const std::string& name, double bandwidth) : StandardLinkImpl(name)
466 bandwidth_.peak = bandwidth;
469 LinkNS3::~LinkNS3() = default;
471 void LinkNS3::apply_event(profile::Event*, double)
476 void LinkNS3::set_bandwidth_profile(profile::Profile* profile)
478 xbt_assert(profile == nullptr, "The ns-3 network model doesn't support bandwidth profiles");
481 void LinkNS3::set_latency_profile(profile::Profile* profile)
483 xbt_assert(profile == nullptr, "The ns-3 network model doesn't support latency profiles");
486 void LinkNS3::set_latency(double latency)
488 latency_.peak = latency;
491 void LinkNS3::set_sharing_policy(s4u::Link::SharingPolicy policy, const s4u::NonLinearResourceCb& cb)
493 sharing_policy_ = policy;
499 NetworkNS3Action::NetworkNS3Action(Model* model, double totalBytes, s4u::Host* src, s4u::Host* dst)
500 : NetworkAction(model, *src, *dst, totalBytes, false)
502 // ns-3 fails when src = dst, so avoid the problem by considering that communications are infinitely fast on the
503 // loopback that does not exists
505 if (static bool warned = false; not warned) {
506 XBT_WARN("Sending from a host %s to itself is not supported by ns-3. Every such communication finishes "
507 "immediately upon startup.",
511 finish(Action::State::FINISHED);
515 // If there is no other started actions, we need to move NS-3 forward to be sync with SimGrid
516 if (model->get_started_action_set()->size() == 1) {
517 while (double_positive(EngineImpl::get_clock() - ns3::Simulator::Now().GetSeconds(), sg_precision_timing)) {
518 XBT_DEBUG("Synchronizing NS-3 (time %f) with SimGrid (time %f)", ns3::Simulator::Now().GetSeconds(),
519 EngineImpl::get_clock());
520 ns3_simulator(EngineImpl::get_clock() - ns3::Simulator::Now().GetSeconds());
524 static uint16_t port_number = 1;
526 ns3::Ptr<ns3::Node> src_node = get_ns3node_from_sghost(src);
527 ns3::Ptr<ns3::Node> dst_node = get_ns3node_from_sghost(dst);
529 const std::string& addr = dst->get_netpoint()->extension<NetPointNs3>()->ipv4_address_;
530 xbt_assert(not addr.empty(), "Element %s is unknown to ns-3. Is it connected to any one-hop link?",
531 dst->get_netpoint()->get_cname());
533 ns3::PacketSinkHelper sink("ns3::TcpSocketFactory", ns3::InetSocketAddress(ns3::Ipv4Address::GetAny(), port_number));
534 ns3::ApplicationContainer apps = sink.Install(dst_node);
536 ns3::Ptr<ns3::Socket> sock = ns3::Socket::CreateSocket(src_node, ns3::TcpSocketFactory::GetTypeId());
538 XBT_DEBUG("Create socket %s for a flow of %.0f Bytes from %s to %s with Interface %s",
539 transform_socket_ptr(sock).c_str(), totalBytes, src->get_cname(), dst->get_cname(), addr.c_str());
541 flow_from_sock.try_emplace(transform_socket_ptr(sock), new SgFlow(static_cast<uint32_t>(totalBytes), this));
542 sink_from_sock.try_emplace(transform_socket_ptr(sock), apps);
544 sock->Bind(ns3::InetSocketAddress(port_number));
545 ns3::Simulator::ScheduleNow(&start_flow, sock, addr.c_str(), port_number);
547 port_number = 1 + (port_number % UINT16_MAX);
548 if (port_number == 1)
549 XBT_WARN("Too many connections! Port number is saturated. Trying to use the oldest ports.");
552 void NetworkNS3Action::suspend()
557 void NetworkNS3Action::resume()
562 std::list<StandardLinkImpl*> NetworkNS3Action::get_links() const
566 void NetworkNS3Action::update_remains_lazy(double /*now*/)
571 } // namespace kernel::resource
573 ns3::Ptr<ns3::Node> get_ns3node_from_sghost(const simgrid::s4u::Host* host)
575 xbt_assert(host->get_netpoint()->extension<NetPointNs3>() != nullptr, "Please only use this function on ns-3 nodes");
576 return host->get_netpoint()->extension<NetPointNs3>()->ns3_node_;
578 } // namespace simgrid
580 void ns3_simulator(double maxSeconds)
583 if (maxSeconds > 0.0) // If there is a maximum amount of time to run
584 id = ns3::Simulator::Schedule(ns3::Seconds(maxSeconds), &ns3::Simulator::Stop);
586 XBT_DEBUG("Start simulator for at most %fs (current time: %f)", maxSeconds, simgrid::kernel::EngineImpl::get_clock());
587 ns3::Simulator::Run();
588 XBT_DEBUG("Simulator stopped at %fs", ns3::Simulator::Now().GetSeconds());
590 if (maxSeconds > 0.0)
594 void ns3_add_direct_route(const simgrid::kernel::routing::NetPoint* src, const simgrid::kernel::routing::NetPoint* dst,
595 double bw, double lat, simgrid::s4u::Link::SharingPolicy policy)
597 ns3::Ipv4AddressHelper address;
598 ns3::NetDeviceContainer netA;
601 auto* host_src = src->extension<NetPointNs3>();
602 auto* host_dst = dst->extension<NetPointNs3>();
604 xbt_assert(host_src != nullptr, "Network element %s does not seem to be ns-3-ready", src->get_cname());
605 xbt_assert(host_dst != nullptr, "Network element %s does not seem to be ns-3-ready", dst->get_cname());
607 xbt_assert(policy != simgrid::s4u::Link::SharingPolicy::WIFI,
608 "The wifi sharing policy is not supported for links. You want to use a wifi zone (see documentation).");
610 ns3::PointToPointHelper pointToPoint;
612 XBT_DEBUG("\tAdd PTP from %s to %s bw:'%f Bps' lat:'%fs'", src->get_cname(), dst->get_cname(), bw, lat);
613 pointToPoint.SetDeviceAttribute(
615 ns3::DataRateValue(ns3::DataRate(static_cast<uint64_t>(bw * 8)))); // ns-3 takes bps, but we provide Bps
616 pointToPoint.SetChannelAttribute("Delay", ns3::TimeValue(ns3::Seconds(lat)));
618 netA.Add(pointToPoint.Install(host_src->ns3_node_, host_dst->ns3_node_));
620 std::string addr = simgrid::xbt::string_printf("%d.%d.0.0", number_of_networks, number_of_links);
621 address.SetBase(addr.c_str(), "255.255.0.0");
622 XBT_DEBUG("\tInterface stack '%s'", addr.c_str());
624 auto addresses = address.Assign(netA);
626 host_src->ipv4_address_ = transformIpv4Address(addresses.GetAddress(0));
627 host_dst->ipv4_address_ = transformIpv4Address(addresses.GetAddress(1));
629 if (number_of_links == 255) {
630 xbt_assert(number_of_networks < 255, "Number of links and networks exceed 255*255");
632 number_of_networks++;