1 /* s4u::Engine Simulation Engine and global functions. */
3 /* Copyright (c) 2006-2023. The SimGrid Team. All rights reserved. */
5 /* This program is free software; you can redistribute it and/or modify it
6 * under the terms of the license (GNU LGPL) which comes with this package. */
8 #include <simgrid/kernel/routing/NetPoint.hpp>
9 #include <simgrid/modelchecker.h>
10 #include <simgrid/s4u/Engine.hpp>
12 #include "src/instr/instr_private.hpp"
13 #include "src/kernel/EngineImpl.hpp"
14 #include "src/kernel/resource/HostImpl.hpp"
15 #include "src/kernel/resource/NetworkModel.hpp"
16 #include "src/kernel/resource/SplitDuplexLinkImpl.hpp"
17 #include "src/kernel/resource/StandardLinkImpl.hpp"
18 #include "src/mc/mc.h"
19 #include "src/mc/mc_replay.hpp"
20 #include "xbt/config.hpp"
25 XBT_LOG_NEW_CATEGORY(s4u, "Log channels of the S4U (SimGrid for you) interface");
26 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(s4u_engine, s4u, "Logging specific to S4U (engine)");
28 static simgrid::kernel::actor::ActorCode maestro_code;
30 namespace simgrid::s4u {
31 xbt::signal<void()> Engine::on_platform_creation;
32 xbt::signal<void()> Engine::on_platform_created;
33 xbt::signal<void()> Engine::on_simulation_start;
34 xbt::signal<void()> Engine::on_simulation_end;
35 xbt::signal<void(double)> Engine::on_time_advance;
36 xbt::signal<void(void)> Engine::on_deadlock;
38 Engine* Engine::instance_ = nullptr; /* This singleton is awful, but I don't see no other solution right now. */
40 void Engine::initialize(int* argc, char** argv)
42 xbt_assert(Engine::instance_ == nullptr, "It is currently forbidden to create more than one instance of s4u::Engine");
43 Engine::instance_ = this;
45 pimpl_->initialize(argc, argv);
46 // Either create a new context with maestro or create
47 // a context object with the current context maestro):
48 kernel::actor::create_maestro(maestro_code);
51 Engine::Engine(std::string name) : pimpl_(new kernel::EngineImpl())
54 char* argv = &name[0];
55 initialize(&argc, &argv);
58 Engine::Engine(int* argc, char** argv) : pimpl_(new kernel::EngineImpl())
60 initialize(argc, argv);
65 kernel::EngineImpl::shutdown();
66 Engine::instance_ = nullptr;
69 /** @brief Retrieve the engine singleton */
70 Engine* Engine::get_instance()
74 return get_instance(&argc, &argv);
76 Engine* Engine::get_instance(int* argc, char** argv)
78 if (Engine::instance_ == nullptr) {
79 const auto* e = new Engine(argc, argv);
80 xbt_assert(Engine::instance_ == e);
82 return Engine::instance_;
84 const std::vector<std::string>& Engine::get_cmdline() const
86 return pimpl_->get_cmdline();
89 double Engine::get_clock()
91 if (MC_is_active() || MC_record_replay_is_active()) {
92 return MC_process_clock_get(kernel::actor::ActorImpl::self());
94 return kernel::EngineImpl::get_clock();
98 void Engine::add_model(std::shared_ptr<kernel::resource::Model> model,
99 const std::vector<kernel::resource::Model*>& dependencies)
101 kernel::actor::simcall_answered([this, &model, &dependencies] { pimpl_->add_model(std::move(model), dependencies); });
104 const std::vector<simgrid::kernel::resource::Model*>& Engine::get_all_models() const
106 return pimpl_->get_all_models();
109 void Engine::load_platform(const std::string& platf) const
111 pimpl_->load_platform(platf);
114 void Engine::seal_platform() const
116 pimpl_->seal_platform();
119 static void flatify_hosts(Engine const& engine, std::stringstream& ss)
122 std::vector<Host*> hosts = engine.get_all_hosts();
124 for (auto const* h : hosts) {
125 ss << " <host id=\"" << h->get_name() << "\" speed=\"" << h->get_speed() << "\"";
126 const std::unordered_map<std::string, std::string>* props = h->get_properties();
127 if (h->get_core_count() > 1)
128 ss << " core=\"" << h->get_core_count() << "\"";
130 // Sort the properties before displaying them, so that the tests are perfectly reproducible
131 std::vector<std::string> keys;
132 for (auto const& [key, _] : *props)
134 if (not keys.empty()) {
136 std::sort(keys.begin(), keys.end());
137 for (const std::string& key : keys)
138 ss << " <prop id=\"" << key << "\" value=\"" << props->at(key) << "\"/>\n";
146 std::vector<simgrid::kernel::routing::NetPoint*> netpoints = engine.get_all_netpoints();
147 std::sort(netpoints.begin(), netpoints.end(),
148 [](const simgrid::kernel::routing::NetPoint* a, const simgrid::kernel::routing::NetPoint* b) {
149 return a->get_name() < b->get_name();
152 for (auto const& src : netpoints)
153 if (src->is_router())
154 ss << " <router id=\"" << src->get_name() << "\"/>\n";
157 static void flatify_links(Engine const& engine, std::stringstream& ss)
159 std::vector<Link*> links = engine.get_all_links();
161 std::sort(links.begin(), links.end(), [](const Link* a, const Link* b) { return a->get_name() < b->get_name(); });
163 for (auto const* link : links) {
164 ss << " <link id=\"" << link->get_name() << "\"";
165 ss << " bandwidth=\"" << link->get_bandwidth() << "\"";
166 ss << " latency=\"" << link->get_latency() << "\"";
167 if (link->get_concurrency_limit() != -1)
168 ss << " concurrency=\"" << link->get_concurrency_limit() << "\"";
169 if (link->is_shared()) {
172 ss << " sharing_policy=\"FATPIPE\"/>\n";
177 static void flatify_routes(Engine const& engine, std::stringstream& ss)
179 auto hosts = engine.get_all_hosts();
180 auto netpoints = engine.get_all_netpoints();
181 std::sort(netpoints.begin(), netpoints.end(),
182 [](const simgrid::kernel::routing::NetPoint* a, const simgrid::kernel::routing::NetPoint* b) {
183 return a->get_name() < b->get_name();
186 for (auto const* src_host : hosts) { // Routes from host
187 const simgrid::kernel::routing::NetPoint* src = src_host->get_netpoint();
188 for (auto const* dst_host : hosts) { // Routes to host
189 std::vector<simgrid::kernel::resource::StandardLinkImpl*> route;
190 const simgrid::kernel::routing::NetPoint* dst = dst_host->get_netpoint();
191 simgrid::kernel::routing::NetZoneImpl::get_global_route(src, dst, route, nullptr);
194 ss << " <route src=\"" << src_host->get_name() << "\" dst=\"" << dst_host->get_name() << "\">\n ";
195 for (auto const& link : route)
196 ss << "<link_ctn id=\"" << link->get_name() << "\"/>";
197 ss << "\n </route>\n";
200 for (auto const& dst : netpoints) { // to router
201 if (not dst->is_router())
203 ss << " <route src=\"" << src_host->get_name() << "\" dst=\"" << dst->get_name() << "\">\n ";
204 std::vector<simgrid::kernel::resource::StandardLinkImpl*> route;
205 simgrid::kernel::routing::NetZoneImpl::get_global_route(src, dst, route, nullptr);
206 for (auto const& link : route)
207 ss << "<link_ctn id=\"" << link->get_name() << "\"/>";
208 ss << "\n </route>\n";
212 for (auto const& value1 : netpoints) { // Routes from router
213 if (not value1->is_router())
215 for (auto const& value2 : netpoints) { // to router
216 if (not value2->is_router())
218 std::vector<simgrid::kernel::resource::StandardLinkImpl*> route;
219 simgrid::kernel::routing::NetZoneImpl::get_global_route(value1, value2, route, nullptr);
222 ss << " <route src=\"" << value1->get_name() << "\" dst=\"" << value2->get_name() << "\">\n ";
223 for (auto const& link : route)
224 ss << "<link_ctn id=\"" << link->get_name() << "\"/>";
225 ss << "\n </route>\n";
227 for (auto const* dst_host : hosts) { // Routes to host
228 ss << " <route src=\"" << value1->get_name() << "\" dst=\"" << dst_host->get_name() << "\">\n ";
229 std::vector<simgrid::kernel::resource::StandardLinkImpl*> route;
230 const simgrid::kernel::routing::NetPoint* netcardDst = dst_host->get_netpoint();
231 simgrid::kernel::routing::NetZoneImpl::get_global_route(value1, netcardDst, route, nullptr);
232 for (auto const& link : route)
233 ss << "<link_ctn id=\"" << link->get_name() << "\"/>";
234 ss << "\n </route>\n";
238 std::string Engine::flatify_platform() const
240 std::string version = "4.1";
241 std::stringstream ss;
243 ss << "<?xml version='1.0'?>\n";
244 ss << "<!DOCTYPE platform SYSTEM \"https://simgrid.org/simgrid.dtd\">\n";
245 ss << "<platform version=\"" << version << "\">\n";
246 ss << "<zone id=\"" << get_netzone_root()->get_name() << "\" routing=\"Full\">\n";
248 flatify_hosts(*this, ss);
249 flatify_links(*this, ss);
250 flatify_routes(*this, ss);
253 ss << "</platform>\n";
257 /** Registers the main function of an actor that will be launched from the deployment file */
258 void Engine::register_function(const std::string& name, const std::function<void(int, char**)>& code)
260 kernel::actor::ActorCodeFactory code_factory = [code](std::vector<std::string> args) {
261 return xbt::wrap_main(code, std::move(args));
263 register_function(name, code_factory);
266 /** Registers the main function of an actor that will be launched from the deployment file */
267 void Engine::register_function(const std::string& name, const std::function<void(std::vector<std::string>)>& code)
269 kernel::actor::ActorCodeFactory code_factory = [code{code}](std::vector<std::string> args) mutable {
270 return std::bind(std::move(code), std::move(args));
272 register_function(name, code_factory);
274 /** Registers a function as the default main function of actors
276 * It will be used as fallback when the function requested from the deployment file was not registered.
277 * It is used for trace-based simulations (see examples/cpp/replay-comms and similar).
279 void Engine::register_default(const std::function<void(int, char**)>& code)
281 register_default([code](std::vector<std::string> args) { return xbt::wrap_main(code, std::move(args)); });
283 void Engine::register_default(const kernel::actor::ActorCodeFactory& code)
285 simgrid::kernel::actor::simcall_answered([this, &code]() { pimpl_->register_default(code); });
288 void Engine::register_function(const std::string& name, const kernel::actor::ActorCodeFactory& code)
290 simgrid::kernel::actor::simcall_answered([this, name, &code]() { pimpl_->register_function(name, code); });
293 /** Load a deployment file and launch the actors that it contains
296 * See also: :ref:`deploy`.
299 void Engine::load_deployment(const std::string& deploy) const
301 pimpl_->load_deployment(deploy);
304 /** Returns the amount of hosts in the platform */
305 size_t Engine::get_host_count() const
307 return get_all_hosts().size();
310 std::vector<Host*> Engine::get_all_hosts() const
312 return get_filtered_hosts([](const Host*) { return true; });
315 std::vector<Host*> Engine::get_filtered_hosts(const std::function<bool(Host*)>& filter) const
317 std::vector<Host*> hosts;
318 if (pimpl_->netzone_root_) {
319 hosts = pimpl_->netzone_root_->get_filtered_hosts(filter);
321 /* Sort hosts in lexicographical order: keep same behavior when the hosts were saved on Engine
322 * Some tests do a get_all_hosts() and selects hosts in this order */
323 std::sort(hosts.begin(), hosts.end(), [](const auto* h1, const auto* h2) { return h1->get_name() < h2->get_name(); });
328 /** @brief Find a host from its name.
330 * @throw std::invalid_argument if the searched host does not exist.
332 Host* Engine::host_by_name(const std::string& name) const
334 auto* host = host_by_name_or_null(name);
336 throw std::invalid_argument("Host not found: '" + name + "'");
340 /** @brief Find a host from its name (or nullptr if that host does not exist) */
341 Host* Engine::host_by_name_or_null(const std::string& name) const
343 Host* host = nullptr;
344 if (pimpl_->netzone_root_) {
345 auto* host_impl = pimpl_->netzone_root_->get_host_by_name_or_null(name);
347 host = host_impl->get_iface();
352 /** @brief Find a link from its name.
354 * @throw std::invalid_argument if the searched link does not exist.
356 Link* Engine::link_by_name(const std::string& name) const
358 auto* link = link_by_name_or_null(name);
360 throw std::invalid_argument("Link not found: " + name);
364 SplitDuplexLink* Engine::split_duplex_link_by_name(const std::string& name) const
367 pimpl_->netzone_root_ ? pimpl_->netzone_root_->get_split_duplex_link_by_name_or_null(name) : nullptr;
369 throw std::invalid_argument("Link not found: " + name);
370 return link_impl->get_iface();
373 /** @brief Find a link from its name (or nullptr if that link does not exist) */
374 Link* Engine::link_by_name_or_null(const std::string& name) const
376 Link* link = nullptr;
377 if (pimpl_->netzone_root_) {
378 /* keep behavior where internal __loopback__ link from network model is given to user */
379 if (name == "__loopback__")
380 return pimpl_->netzone_root_->get_network_model()->loopback_->get_iface();
381 auto* link_impl = pimpl_->netzone_root_->get_link_by_name_or_null(name);
383 link = link_impl->get_iface();
388 /** @brief Find a mailbox from its name or create one if it does not exist) */
389 Mailbox* Engine::mailbox_by_name_or_create(const std::string& name) const
391 /* two actors may have pushed the same mbox_create simcall at the same time */
392 kernel::activity::MailboxImpl* mbox = kernel::actor::simcall_answered([&name, this] {
393 auto [m, inserted] = pimpl_->mailboxes_.try_emplace(name, nullptr);
395 m->second = new kernel::activity::MailboxImpl(name);
396 XBT_DEBUG("Creating a mailbox at %p with name %s", m->second, name.c_str());
400 return mbox->get_iface();
403 MessageQueue* Engine::message_queue_by_name_or_create(const std::string& name) const
405 /* two actors may have pushed the same mbox_create simcall at the same time */
406 kernel::activity::MessageQueueImpl* queue = kernel::actor::simcall_answered([&name, this] {
407 auto [m, inserted] = pimpl_->mqueues_.try_emplace(name, nullptr);
409 m->second = new kernel::activity::MessageQueueImpl(name);
410 XBT_DEBUG("Creating a message queue at %p with name %s", m->second, name.c_str());
414 return queue->get_iface();
417 /** @brief Returns the amount of links in the platform */
418 size_t Engine::get_link_count() const
421 if (pimpl_->netzone_root_) {
422 count += pimpl_->netzone_root_->get_link_count();
423 /* keep behavior where internal __loopback__ link from network model is given to user */
424 count += pimpl_->netzone_root_->get_network_model()->loopback_ ? 1 : 0;
429 /** @brief Returns the list of all links found in the platform */
430 std::vector<Link*> Engine::get_all_links() const
432 return get_filtered_links([](const Link*) { return true; });
435 std::vector<Link*> Engine::get_filtered_links(const std::function<bool(Link*)>& filter) const
437 std::vector<Link*> res;
438 if (pimpl_->netzone_root_) {
439 res = pimpl_->netzone_root_->get_filtered_links(filter);
440 /* keep behavior where internal __loopback__ link from network model is given to user */
441 if (pimpl_->netzone_root_->get_network_model()->loopback_ &&
442 filter(pimpl_->netzone_root_->get_network_model()->loopback_->get_iface()))
443 res.push_back(pimpl_->netzone_root_->get_network_model()->loopback_->get_iface());
448 size_t Engine::get_actor_count() const
450 return pimpl_->get_actor_count();
453 std::vector<ActorPtr> Engine::get_all_actors() const
455 std::vector<ActorPtr> actor_list;
456 for (auto const& [_, actor] : pimpl_->get_actor_list()) {
457 actor_list.push_back(actor->get_iface());
462 std::vector<ActorPtr> Engine::get_filtered_actors(const std::function<bool(ActorPtr)>& filter) const
464 std::vector<ActorPtr> actor_list;
465 for (auto const& [_, actor] : pimpl_->get_actor_list()) {
466 if (filter(actor->get_iface()))
467 actor_list.push_back(actor->get_iface());
472 void Engine::run() const
476 void Engine::run_until(double max_date) const
478 if (static bool callback_called = false; not callback_called) {
479 on_simulation_start();
480 callback_called = true;
482 /* Clean IO before the run */
486 pimpl_->run(max_date);
489 void Engine::track_vetoed_activities(std::set<Activity*>* vetoed_activities) const
491 Activity::set_vetoed_activities(vetoed_activities);
494 /** @brief Retrieve the root netzone, containing all others */
495 s4u::NetZone* Engine::get_netzone_root() const
497 if (pimpl_->netzone_root_)
498 return pimpl_->netzone_root_->get_iface();
501 /** @brief Set the root netzone, containing all others. Once set, it cannot be changed. */
502 void Engine::set_netzone_root(const s4u::NetZone* netzone)
504 xbt_assert(pimpl_->netzone_root_ == nullptr, "The root NetZone cannot be changed once set");
505 pimpl_->netzone_root_ = netzone->get_impl();
508 static NetZone* netzone_by_name_recursive(NetZone* current, const std::string& name)
510 if (current->get_name() == name)
513 for (auto const& elem : current->get_children()) {
514 NetZone* tmp = netzone_by_name_recursive(elem, name);
515 if (tmp != nullptr) {
522 /** @brief Retrieve the NetZone of the given name (or nullptr if not found) */
523 NetZone* Engine::netzone_by_name_or_null(const std::string& name) const
525 return netzone_by_name_recursive(get_netzone_root(), name);
528 /** @brief Retrieve the netpoint of the given name (or nullptr if not found) */
529 kernel::routing::NetPoint* Engine::netpoint_by_name_or_null(const std::string& name) const
531 auto netp = pimpl_->netpoints_.find(name);
532 return netp == pimpl_->netpoints_.end() ? nullptr : netp->second;
535 kernel::routing::NetPoint* Engine::netpoint_by_name(const std::string& name) const
537 auto* netp = netpoint_by_name_or_null(name);
538 if (netp == nullptr) {
539 throw std::invalid_argument("Netpoint not found: " + name);
544 std::vector<kernel::routing::NetPoint*> Engine::get_all_netpoints() const
546 std::vector<kernel::routing::NetPoint*> res;
547 for (auto const& [_, netpoint] : pimpl_->netpoints_)
548 res.push_back(netpoint);
552 /** @brief Register a new netpoint to the system */
553 void Engine::netpoint_register(kernel::routing::NetPoint* point)
555 simgrid::kernel::actor::simcall_answered([this, point] { pimpl_->netpoints_[point->get_name()] = point; });
558 /** @brief Unregister a given netpoint */
559 void Engine::netpoint_unregister(kernel::routing::NetPoint* point)
561 kernel::actor::simcall_answered([this, point] {
562 pimpl_->netpoints_.erase(point->get_name());
567 bool Engine::is_initialized()
569 return Engine::instance_ != nullptr;
571 void Engine::set_config(const std::string& str)
573 config::set_parse(str);
575 void Engine::set_config(const std::string& name, int value)
577 config::set_value(name.c_str(), value);
579 void Engine::set_config(const std::string& name, double value)
581 config::set_value(name.c_str(), value);
583 void Engine::set_config(const std::string& name, bool value)
585 config::set_value(name.c_str(), value);
587 void Engine::set_config(const std::string& name, const std::string& value)
589 config::set_value(name.c_str(), value);
592 Engine* Engine::set_default_comm_data_copy_callback(
593 const std::function<void(kernel::activity::CommImpl*, void*, size_t)>& callback)
595 kernel::activity::CommImpl::set_copy_data_callback(callback);
599 } // namespace simgrid::s4u
601 /* **************************** Public C interface *************************** */
602 void simgrid_init(int* argc, char** argv)
604 static simgrid::s4u::Engine e(argc, argv);
606 void simgrid_load_platform(const char* file)
608 simgrid::s4u::Engine::get_instance()->load_platform(file);
611 void simgrid_load_deployment(const char* file)
613 simgrid::s4u::Engine::get_instance()->load_deployment(file);
617 simgrid::s4u::Engine::get_instance()->run();
619 void simgrid_run_until(double max_date)
621 simgrid::s4u::Engine::get_instance()->run_until(max_date);
623 void simgrid_register_function(const char* name, void (*code)(int, char**))
625 simgrid::s4u::Engine::get_instance()->register_function(name, code);
627 void simgrid_register_default(void (*code)(int, char**))
629 simgrid::s4u::Engine::get_instance()->register_default(code);
631 double simgrid_get_clock()
633 return simgrid::s4u::Engine::get_clock();
636 void simgrid_set_maestro(void (*code)(void*), void* data)
638 maestro_code = std::bind(code, data);