Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Add new entry in Release_Notes.
[simgrid.git] / src / s4u / s4u_Engine.cpp
1 /* s4u::Engine Simulation Engine and global functions. */
2
3 /* Copyright (c) 2006-2023. The SimGrid Team. All rights reserved.          */
4
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. */
7
8 #include <simgrid/kernel/routing/NetPoint.hpp>
9 #include <simgrid/modelchecker.h>
10 #include <simgrid/s4u/Engine.hpp>
11
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"
21
22 #include <algorithm>
23 #include <string>
24
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)");
27
28 static simgrid::kernel::actor::ActorCode maestro_code;
29
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;
37
38 Engine* Engine::instance_ = nullptr; /* This singleton is awful, but I don't see no other solution right now. */
39
40 void Engine::initialize(int* argc, char** argv)
41 {
42   xbt_assert(Engine::instance_ == nullptr, "It is currently forbidden to create more than one instance of s4u::Engine");
43   Engine::instance_ = this;
44   instr::init();
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);
49 }
50
51 Engine::Engine(std::string name) : pimpl_(new kernel::EngineImpl())
52 {
53   int argc   = 1;
54   char* argv = &name[0];
55   initialize(&argc, &argv);
56 }
57
58 Engine::Engine(int* argc, char** argv) : pimpl_(new kernel::EngineImpl())
59 {
60   initialize(argc, argv);
61 }
62
63 Engine::~Engine()
64 {
65   kernel::EngineImpl::shutdown();
66   Engine::instance_ = nullptr;
67 }
68
69 /** @brief Retrieve the engine singleton */
70 Engine* Engine::get_instance()
71 {
72   int argc   = 0;
73   char* argv = nullptr;
74   return get_instance(&argc, &argv);
75 }
76 Engine* Engine::get_instance(int* argc, char** argv)
77 {
78   if (Engine::instance_ == nullptr) {
79     const auto* e = new Engine(argc, argv);
80     xbt_assert(Engine::instance_ == e);
81   }
82   return Engine::instance_;
83 }
84 const std::vector<std::string>& Engine::get_cmdline() const
85 {
86   return pimpl_->get_cmdline();
87 }
88
89 double Engine::get_clock()
90 {
91   if (MC_is_active() || MC_record_replay_is_active()) {
92     return MC_process_clock_get(kernel::actor::ActorImpl::self());
93   } else {
94     return kernel::EngineImpl::get_clock();
95   }
96 }
97
98 void Engine::add_model(std::shared_ptr<kernel::resource::Model> model,
99                        const std::vector<kernel::resource::Model*>& dependencies)
100 {
101   kernel::actor::simcall_answered([this, &model, &dependencies] { pimpl_->add_model(std::move(model), dependencies); });
102 }
103
104 const std::vector<simgrid::kernel::resource::Model*>& Engine::get_all_models() const
105 {
106   return pimpl_->get_all_models();
107 }
108
109 void Engine::load_platform(const std::string& platf) const
110 {
111   pimpl_->load_platform(platf);
112 }
113
114 void Engine::seal_platform() const
115 {
116   pimpl_->seal_platform();
117 }
118
119 static void flatify_hosts(Engine const& engine, std::stringstream& ss)
120 {
121   // Regular hosts
122   std::vector<Host*> hosts = engine.get_all_hosts();
123
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() << "\"";
129
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)
133       keys.push_back(key);
134     if (not keys.empty()) {
135       ss << ">\n";
136       std::sort(keys.begin(), keys.end());
137       for (const std::string& key : keys)
138         ss << "    <prop id=\"" << key << "\" value=\"" << props->at(key) << "\"/>\n";
139       ss << "  </host>\n";
140     } else {
141       ss << "/>\n";
142     }
143   }
144
145   // Routers
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();
150             });
151
152   for (auto const& src : netpoints)
153     if (src->is_router())
154       ss << "  <router id=\"" << src->get_name() << "\"/>\n";
155 }
156
157 static void flatify_links(Engine const& engine, std::stringstream& ss)
158 {
159   std::vector<Link*> links = engine.get_all_links();
160
161   std::sort(links.begin(), links.end(), [](const Link* a, const Link* b) { return a->get_name() < b->get_name(); });
162
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()) {
170       ss << "/>\n";
171     } else {
172       ss << " sharing_policy=\"FATPIPE\"/>\n";
173     }
174   }
175 }
176
177 static void flatify_routes(Engine const& engine, std::stringstream& ss)
178 {
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();
184             });
185
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);
192       if (route.empty())
193         continue;
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";
198     }
199
200     for (auto const& dst : netpoints) { // to router
201       if (not dst->is_router())
202         continue;
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";
209     }
210   }
211
212   for (auto const& value1 : netpoints) { // Routes from router
213     if (not value1->is_router())
214       continue;
215     for (auto const& value2 : netpoints) { // to router
216       if (not value2->is_router())
217         continue;
218       std::vector<simgrid::kernel::resource::StandardLinkImpl*> route;
219       simgrid::kernel::routing::NetZoneImpl::get_global_route(value1, value2, route, nullptr);
220       if (route.empty())
221         continue;
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";
226     }
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";
235     }
236   }
237 }
238 std::string Engine::flatify_platform() const
239 {
240   std::string version = "4.1";
241   std::stringstream ss;
242
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";
247
248   flatify_hosts(*this, ss);
249   flatify_links(*this, ss);
250   flatify_routes(*this, ss);
251
252   ss << "</zone>\n";
253   ss << "</platform>\n";
254   return ss.str();
255 }
256
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)
259 {
260   kernel::actor::ActorCodeFactory code_factory = [code](std::vector<std::string> args) {
261     return xbt::wrap_main(code, std::move(args));
262   };
263   register_function(name, code_factory);
264 }
265
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)
268 {
269   kernel::actor::ActorCodeFactory code_factory = [code{code}](std::vector<std::string> args) mutable {
270     return std::bind(std::move(code), std::move(args));
271   };
272   register_function(name, code_factory);
273 }
274 /** Registers a function as the default main function of actors
275  *
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).
278  */
279 void Engine::register_default(const std::function<void(int, char**)>& code)
280 {
281   register_default([code](std::vector<std::string> args) { return xbt::wrap_main(code, std::move(args)); });
282 }
283 void Engine::register_default(const kernel::actor::ActorCodeFactory& code)
284 {
285   simgrid::kernel::actor::simcall_answered([this, &code]() { pimpl_->register_default(code); });
286 }
287
288 void Engine::register_function(const std::string& name, const kernel::actor::ActorCodeFactory& code)
289 {
290   simgrid::kernel::actor::simcall_answered([this, name, &code]() { pimpl_->register_function(name, code); });
291 }
292
293 /** Load a deployment file and launch the actors that it contains
294  *
295  * @beginrst
296  * See also: :ref:`deploy`.
297  * @endrst
298  */
299 void Engine::load_deployment(const std::string& deploy) const
300 {
301   pimpl_->load_deployment(deploy);
302 }
303
304 /** Returns the amount of hosts in the platform */
305 size_t Engine::get_host_count() const
306 {
307   return get_all_hosts().size();
308 }
309
310 std::vector<Host*> Engine::get_all_hosts() const
311 {
312   return get_filtered_hosts([](const Host*) { return true; });
313 }
314
315 std::vector<Host*> Engine::get_filtered_hosts(const std::function<bool(Host*)>& filter) const
316 {
317   std::vector<Host*> hosts;
318   if (pimpl_->netzone_root_) {
319     hosts = pimpl_->netzone_root_->get_filtered_hosts(filter);
320   }
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(); });
324
325   return hosts;
326 }
327
328 /** @brief Find a host from its name.
329  *
330  *  @throw std::invalid_argument if the searched host does not exist.
331  */
332 Host* Engine::host_by_name(const std::string& name) const
333 {
334   auto* host = host_by_name_or_null(name);
335   if (not host)
336     throw std::invalid_argument("Host not found: '" + name + "'");
337   return host;
338 }
339
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
342 {
343   Host* host = nullptr;
344   if (pimpl_->netzone_root_) {
345     auto* host_impl = pimpl_->netzone_root_->get_host_by_name_or_null(name);
346     if (host_impl)
347       host = host_impl->get_iface();
348   }
349   return host;
350 }
351
352 /** @brief Find a link from its name.
353  *
354  *  @throw std::invalid_argument if the searched link does not exist.
355  */
356 Link* Engine::link_by_name(const std::string& name) const
357 {
358   auto* link = link_by_name_or_null(name);
359   if (not link)
360     throw std::invalid_argument("Link not found: " + name);
361   return link;
362 }
363
364 SplitDuplexLink* Engine::split_duplex_link_by_name(const std::string& name) const
365 {
366   auto* link_impl =
367       pimpl_->netzone_root_ ? pimpl_->netzone_root_->get_split_duplex_link_by_name_or_null(name) : nullptr;
368   if (not link_impl)
369     throw std::invalid_argument("Link not found: " + name);
370   return link_impl->get_iface();
371 }
372
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
375 {
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);
382     if (link_impl)
383       link = link_impl->get_iface();
384   }
385   return link;
386 }
387
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
390 {
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);
394     if (inserted) {
395       m->second = new kernel::activity::MailboxImpl(name);
396       XBT_DEBUG("Creating a mailbox at %p with name %s", m->second, name.c_str());
397     }
398     return m->second;
399   });
400   return mbox->get_iface();
401 }
402
403 MessageQueue* Engine::message_queue_by_name_or_create(const std::string& name) const
404 {
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);
408     if (inserted) {
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());
411     }
412     return m->second;
413   });
414   return queue->get_iface();
415 }
416
417 /** @brief Returns the amount of links in the platform */
418 size_t Engine::get_link_count() const
419 {
420   int count = 0;
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;
425   }
426   return count;
427 }
428
429 /** @brief Returns the list of all links found in the platform */
430 std::vector<Link*> Engine::get_all_links() const
431 {
432   return get_filtered_links([](const Link*) { return true; });
433 }
434
435 std::vector<Link*> Engine::get_filtered_links(const std::function<bool(Link*)>& filter) const
436 {
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());
444   }
445   return res;
446 }
447
448 size_t Engine::get_actor_count() const
449 {
450   return pimpl_->get_actor_count();
451 }
452
453 std::vector<ActorPtr> Engine::get_all_actors() const
454 {
455   std::vector<ActorPtr> actor_list;
456   for (auto const& [_, actor] : pimpl_->get_actor_list()) {
457     actor_list.push_back(actor->get_iface());
458   }
459   return actor_list;
460 }
461
462 std::vector<ActorPtr> Engine::get_filtered_actors(const std::function<bool(ActorPtr)>& filter) const
463 {
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());
468   }
469   return actor_list;
470 }
471
472 void Engine::run() const
473 {
474   run_until(-1);
475 }
476 void Engine::run_until(double max_date) const
477 {
478   if (static bool callback_called = false; not callback_called) {
479     on_simulation_start();
480     callback_called = true;
481   }
482   /* Clean IO before the run */
483   fflush(stdout);
484   fflush(stderr);
485
486   pimpl_->run(max_date);
487 }
488
489 void Engine::track_vetoed_activities(std::set<Activity*>* vetoed_activities) const
490 {
491   Activity::set_vetoed_activities(vetoed_activities);
492 }
493
494 /** @brief Retrieve the root netzone, containing all others */
495 s4u::NetZone* Engine::get_netzone_root() const
496 {
497   if (pimpl_->netzone_root_)
498     return pimpl_->netzone_root_->get_iface();
499   return nullptr;
500 }
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)
503 {
504   xbt_assert(pimpl_->netzone_root_ == nullptr, "The root NetZone cannot be changed once set");
505   pimpl_->netzone_root_ = netzone->get_impl();
506 }
507
508 static NetZone* netzone_by_name_recursive(NetZone* current, const std::string& name)
509 {
510   if (current->get_name() == name)
511     return current;
512
513   for (auto const& elem : current->get_children()) {
514     NetZone* tmp = netzone_by_name_recursive(elem, name);
515     if (tmp != nullptr) {
516       return tmp;
517     }
518   }
519   return nullptr;
520 }
521
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
524 {
525   return netzone_by_name_recursive(get_netzone_root(), name);
526 }
527
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
530 {
531   auto netp = pimpl_->netpoints_.find(name);
532   return netp == pimpl_->netpoints_.end() ? nullptr : netp->second;
533 }
534
535 kernel::routing::NetPoint* Engine::netpoint_by_name(const std::string& name) const
536 {
537   auto* netp = netpoint_by_name_or_null(name);
538   if (netp == nullptr) {
539     throw std::invalid_argument("Netpoint not found: " + name);
540   }
541   return netp;
542 }
543
544 std::vector<kernel::routing::NetPoint*> Engine::get_all_netpoints() const
545 {
546   std::vector<kernel::routing::NetPoint*> res;
547   for (auto const& [_, netpoint] : pimpl_->netpoints_)
548     res.push_back(netpoint);
549   return res;
550 }
551
552 /** @brief Register a new netpoint to the system */
553 void Engine::netpoint_register(kernel::routing::NetPoint* point)
554 {
555   simgrid::kernel::actor::simcall_answered([this, point] { pimpl_->netpoints_[point->get_name()] = point; });
556 }
557
558 /** @brief Unregister a given netpoint */
559 void Engine::netpoint_unregister(kernel::routing::NetPoint* point)
560 {
561   kernel::actor::simcall_answered([this, point] {
562     pimpl_->netpoints_.erase(point->get_name());
563     delete point;
564   });
565 }
566
567 bool Engine::is_initialized()
568 {
569   return Engine::instance_ != nullptr;
570 }
571 void Engine::set_config(const std::string& str)
572 {
573   config::set_parse(str);
574 }
575 void Engine::set_config(const std::string& name, int value)
576 {
577   config::set_value(name.c_str(), value);
578 }
579 void Engine::set_config(const std::string& name, double value)
580 {
581   config::set_value(name.c_str(), value);
582 }
583 void Engine::set_config(const std::string& name, bool value)
584 {
585   config::set_value(name.c_str(), value);
586 }
587 void Engine::set_config(const std::string& name, const std::string& value)
588 {
589   config::set_value(name.c_str(), value);
590 }
591
592 Engine* Engine::set_default_comm_data_copy_callback(
593     const std::function<void(kernel::activity::CommImpl*, void*, size_t)>& callback)
594 {
595   kernel::activity::CommImpl::set_copy_data_callback(callback);
596   return this;
597 }
598
599 } // namespace simgrid::s4u
600
601 /* **************************** Public C interface *************************** */
602 void simgrid_init(int* argc, char** argv)
603 {
604   static simgrid::s4u::Engine e(argc, argv);
605 }
606 void simgrid_load_platform(const char* file)
607 {
608   simgrid::s4u::Engine::get_instance()->load_platform(file);
609 }
610
611 void simgrid_load_deployment(const char* file)
612 {
613   simgrid::s4u::Engine::get_instance()->load_deployment(file);
614 }
615 void simgrid_run()
616 {
617   simgrid::s4u::Engine::get_instance()->run();
618 }
619 void simgrid_run_until(double max_date)
620 {
621   simgrid::s4u::Engine::get_instance()->run_until(max_date);
622 }
623 void simgrid_register_function(const char* name, void (*code)(int, char**))
624 {
625   simgrid::s4u::Engine::get_instance()->register_function(name, code);
626 }
627 void simgrid_register_default(void (*code)(int, char**))
628 {
629   simgrid::s4u::Engine::get_instance()->register_default(code);
630 }
631 double simgrid_get_clock()
632 {
633   return simgrid::s4u::Engine::get_clock();
634 }
635
636 void simgrid_set_maestro(void (*code)(void*), void* data)
637 {
638   maestro_code = std::bind(code, data);
639 }