Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
3d7c6cbe823646e0afeb712cedca55a5ce215bcc
[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     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 void Engine::shutdown() // XBT_ATTRIB_DEPRECATED_v335
90 {
91   delete Engine::instance_;
92 }
93
94 double Engine::get_clock()
95 {
96   if (MC_is_active() || MC_record_replay_is_active()) {
97     return MC_process_clock_get(kernel::actor::ActorImpl::self());
98   } else {
99     return kernel::EngineImpl::get_clock();
100   }
101 }
102
103 void Engine::add_model(std::shared_ptr<kernel::resource::Model> model,
104                        const std::vector<kernel::resource::Model*>& dependencies)
105 {
106   kernel::actor::simcall_answered([this, &model, &dependencies] { pimpl->add_model(std::move(model), dependencies); });
107 }
108
109 const std::vector<simgrid::kernel::resource::Model*>& Engine::get_all_models() const
110 {
111   return pimpl->get_all_models();
112 }
113
114 void Engine::load_platform(const std::string& platf) const
115 {
116   pimpl->load_platform(platf);
117 }
118
119 void Engine::seal_platform() const
120 {
121   pimpl->seal_platform();
122 }
123
124 static void flatify_hosts(Engine const& engine, std::stringstream& ss)
125 {
126   // Regular hosts
127   std::vector<Host*> hosts = engine.get_all_hosts();
128
129   for (auto const* h : hosts) {
130     ss << "  <host id=\"" << h->get_name() << "\" speed=\"" << h->get_speed() << "\"";
131     const std::unordered_map<std::string, std::string>* props = h->get_properties();
132     if (h->get_core_count() > 1)
133       ss << " core=\"" << h->get_core_count() << "\"";
134
135     // Sort the properties before displaying them, so that the tests are perfectly reproducible
136     std::vector<std::string> keys;
137     for (auto const& [key, _] : *props)
138       keys.push_back(key);
139     if (not keys.empty()) {
140       ss << ">\n";
141       std::sort(keys.begin(), keys.end());
142       for (const std::string& key : keys)
143         ss << "    <prop id=\"" << key << "\" value=\"" << props->at(key) << "\"/>\n";
144       ss << "  </host>\n";
145     } else {
146       ss << "/>\n";
147     }
148   }
149
150   // Routers
151   std::vector<simgrid::kernel::routing::NetPoint*> netpoints = engine.get_all_netpoints();
152   std::sort(netpoints.begin(), netpoints.end(),
153             [](const simgrid::kernel::routing::NetPoint* a, const simgrid::kernel::routing::NetPoint* b) {
154               return a->get_name() < b->get_name();
155             });
156
157   for (auto const& src : netpoints)
158     if (src->is_router())
159       ss << "  <router id=\"" << src->get_name() << "\"/>\n";
160 }
161
162 static void flatify_links(Engine const& engine, std::stringstream& ss)
163 {
164   std::vector<Link*> links = engine.get_all_links();
165
166   std::sort(links.begin(), links.end(), [](const Link* a, const Link* b) { return a->get_name() < b->get_name(); });
167
168   for (auto const* link : links) {
169     ss << "  <link id=\"" << link->get_name() << "\"";
170     ss << " bandwidth=\"" << link->get_bandwidth() << "\"";
171     ss << " latency=\"" << link->get_latency() << "\"";
172     if (link->get_concurrency_limit() != -1)
173       ss << " concurrency=\"" << link->get_concurrency_limit() << "\"";
174     if (link->is_shared()) {
175       ss << "/>\n";
176     } else {
177       ss << " sharing_policy=\"FATPIPE\"/>\n";
178     }
179   }
180 }
181
182 static void flatify_routes(Engine const& engine, std::stringstream& ss)
183 {
184   auto hosts     = engine.get_all_hosts();
185   auto netpoints = engine.get_all_netpoints();
186   std::sort(netpoints.begin(), netpoints.end(),
187             [](const simgrid::kernel::routing::NetPoint* a, const simgrid::kernel::routing::NetPoint* b) {
188               return a->get_name() < b->get_name();
189             });
190
191   for (auto const* src_host : hosts) { // Routes from host
192     const simgrid::kernel::routing::NetPoint* src = src_host->get_netpoint();
193     for (auto const* dst_host : hosts) { // Routes to host
194       std::vector<simgrid::kernel::resource::StandardLinkImpl*> route;
195       const simgrid::kernel::routing::NetPoint* dst = dst_host->get_netpoint();
196       simgrid::kernel::routing::NetZoneImpl::get_global_route(src, dst, route, nullptr);
197       if (route.empty())
198         continue;
199       ss << "  <route src=\"" << src_host->get_name() << "\" dst=\"" << dst_host->get_name() << "\">\n  ";
200       for (auto const& link : route)
201         ss << "<link_ctn id=\"" << link->get_name() << "\"/>";
202       ss << "\n  </route>\n";
203     }
204
205     for (auto const& dst : netpoints) { // to router
206       if (not dst->is_router())
207         continue;
208       ss << "  <route src=\"" << src_host->get_name() << "\" dst=\"" << dst->get_name() << "\">\n  ";
209       std::vector<simgrid::kernel::resource::StandardLinkImpl*> route;
210       simgrid::kernel::routing::NetZoneImpl::get_global_route(src, dst, route, nullptr);
211       for (auto const& link : route)
212         ss << "<link_ctn id=\"" << link->get_name() << "\"/>";
213       ss << "\n  </route>\n";
214     }
215   }
216
217   for (auto const& value1 : netpoints) { // Routes from router
218     if (not value1->is_router())
219       continue;
220     for (auto const& value2 : netpoints) { // to router
221       if (not value2->is_router())
222         continue;
223       std::vector<simgrid::kernel::resource::StandardLinkImpl*> route;
224       simgrid::kernel::routing::NetZoneImpl::get_global_route(value1, value2, route, nullptr);
225       if (route.empty())
226         continue;
227       ss << "  <route src=\"" << value1->get_name() << "\" dst=\"" << value2->get_name() << "\">\n  ";
228       for (auto const& link : route)
229         ss << "<link_ctn id=\"" << link->get_name() << "\"/>";
230       ss << "\n  </route>\n";
231     }
232     for (auto const* dst_host : hosts) { // Routes to host
233       ss << "  <route src=\"" << value1->get_name() << "\" dst=\"" << dst_host->get_name() << "\">\n  ";
234       std::vector<simgrid::kernel::resource::StandardLinkImpl*> route;
235       const simgrid::kernel::routing::NetPoint* netcardDst = dst_host->get_netpoint();
236       simgrid::kernel::routing::NetZoneImpl::get_global_route(value1, netcardDst, route, nullptr);
237       for (auto const& link : route)
238         ss << "<link_ctn id=\"" << link->get_name() << "\"/>";
239       ss << "\n  </route>\n";
240     }
241   }
242 }
243 std::string Engine::flatify_platform() const
244 {
245   std::string version = "4.1";
246   std::stringstream ss;
247
248   ss << "<?xml version='1.0'?>\n";
249   ss << "<!DOCTYPE platform SYSTEM \"https://simgrid.org/simgrid.dtd\">\n";
250   ss << "<platform version=\"" << version << "\">\n";
251   ss << "<AS id=\"" << get_netzone_root()->get_name() << "\" routing=\"Full\">\n";
252
253   flatify_hosts(*this, ss);
254   flatify_links(*this, ss);
255   flatify_routes(*this, ss);
256
257   ss << "</AS>\n";
258   ss << "</platform>\n";
259   return ss.str();
260 }
261
262 /** Registers the main function of an actor that will be launched from the deployment file */
263 void Engine::register_function(const std::string& name, const std::function<void(int, char**)>& code)
264 {
265   kernel::actor::ActorCodeFactory code_factory = [code](std::vector<std::string> args) {
266     return xbt::wrap_main(code, std::move(args));
267   };
268   register_function(name, code_factory);
269 }
270
271 /** Registers the main function of an actor that will be launched from the deployment file */
272 void Engine::register_function(const std::string& name, const std::function<void(std::vector<std::string>)>& code)
273 {
274   kernel::actor::ActorCodeFactory code_factory = [code{code}](std::vector<std::string> args) mutable {
275     return std::bind(std::move(code), std::move(args));
276   };
277   register_function(name, code_factory);
278 }
279 /** Registers a function as the default main function of actors
280  *
281  * It will be used as fallback when the function requested from the deployment file was not registered.
282  * It is used for trace-based simulations (see examples/cpp/replay-comms and similar).
283  */
284 void Engine::register_default(const std::function<void(int, char**)>& code)
285 {
286   register_default([code](std::vector<std::string> args) { return xbt::wrap_main(code, std::move(args)); });
287 }
288 void Engine::register_default(const kernel::actor::ActorCodeFactory& code)
289 {
290   simgrid::kernel::actor::simcall_answered([this, &code]() { pimpl->register_default(code); });
291 }
292
293 void Engine::register_function(const std::string& name, const kernel::actor::ActorCodeFactory& code)
294 {
295   simgrid::kernel::actor::simcall_answered([this, name, &code]() { pimpl->register_function(name, code); });
296 }
297
298 /** Load a deployment file and launch the actors that it contains
299  *
300  * @beginrst
301  * See also: :ref:`deploy`.
302  * @endrst
303  */
304 void Engine::load_deployment(const std::string& deploy) const
305 {
306   pimpl->load_deployment(deploy);
307 }
308
309 /** Returns the amount of hosts in the platform */
310 size_t Engine::get_host_count() const
311 {
312   return get_all_hosts().size();
313 }
314
315 std::vector<Host*> Engine::get_all_hosts() const
316 {
317   return get_filtered_hosts([](const Host*) { return true; });
318 }
319
320 std::vector<Host*> Engine::get_filtered_hosts(const std::function<bool(Host*)>& filter) const
321 {
322   std::vector<Host*> hosts;
323   if (pimpl->netzone_root_) {
324     hosts = pimpl->netzone_root_->get_filtered_hosts(filter);
325   }
326   /* Sort hosts in lexicographical order: keep same behavior when the hosts were saved on Engine
327    * Some tests do a get_all_hosts() and selects hosts in this order */
328   std::sort(hosts.begin(), hosts.end(), [](const auto* h1, const auto* h2) { return h1->get_name() < h2->get_name(); });
329
330   return hosts;
331 }
332
333 /** @brief Find a host from its name.
334  *
335  *  @throw std::invalid_argument if the searched host does not exist.
336  */
337 Host* Engine::host_by_name(const std::string& name) const
338 {
339   auto* host = host_by_name_or_null(name);
340   if (not host)
341     throw std::invalid_argument("Host not found: '" + name + "'");
342   return host;
343 }
344
345 /** @brief Find a host from its name (or nullptr if that host does not exist) */
346 Host* Engine::host_by_name_or_null(const std::string& name) const
347 {
348   Host* host = nullptr;
349   if (pimpl->netzone_root_) {
350     auto* host_impl = pimpl->netzone_root_->get_host_by_name_or_null(name);
351     if (host_impl)
352       host = host_impl->get_iface();
353   }
354   return host;
355 }
356
357 /** @brief Find a link from its name.
358  *
359  *  @throw std::invalid_argument if the searched link does not exist.
360  */
361 Link* Engine::link_by_name(const std::string& name) const
362 {
363   auto* link = link_by_name_or_null(name);
364   if (not link)
365     throw std::invalid_argument("Link not found: " + name);
366   return link;
367 }
368
369 SplitDuplexLink* Engine::split_duplex_link_by_name(const std::string& name) const
370 {
371   auto* link_impl = pimpl->netzone_root_ ? pimpl->netzone_root_->get_split_duplex_link_by_name_or_null(name) : nullptr;
372   if (not link_impl)
373     throw std::invalid_argument("Link not found: " + name);
374   return link_impl->get_iface();
375 }
376
377 /** @brief Find a link from its name (or nullptr if that link does not exist) */
378 Link* Engine::link_by_name_or_null(const std::string& name) const
379 {
380   Link* link = nullptr;
381   if (pimpl->netzone_root_) {
382     /* keep behavior where internal __loopback__ link from network model is given to user */
383     if (name == "__loopback__")
384       return pimpl->netzone_root_->get_network_model()->loopback_->get_iface();
385     auto* link_impl = pimpl->netzone_root_->get_link_by_name_or_null(name);
386     if (link_impl)
387       link = link_impl->get_iface();
388   }
389   return link;
390 }
391
392 /** @brief Find a mailbox from its name or create one if it does not exist) */
393 Mailbox* Engine::mailbox_by_name_or_create(const std::string& name) const
394 {
395   /* two actors may have pushed the same mbox_create simcall at the same time */
396   kernel::activity::MailboxImpl* mbox = kernel::actor::simcall_answered([&name, this] {
397     auto [m, inserted] = pimpl->mailboxes_.try_emplace(name, nullptr);
398     if (inserted) {
399       m->second = new kernel::activity::MailboxImpl(name);
400       XBT_DEBUG("Creating a mailbox at %p with name %s", m->second, name.c_str());
401     }
402     return m->second;
403   });
404   return mbox->get_iface();
405 }
406
407 /** @brief Returns the amount of links in the platform */
408 size_t Engine::get_link_count() const
409 {
410   int count = 0;
411   if (pimpl->netzone_root_) {
412     count += pimpl->netzone_root_->get_link_count();
413     /* keep behavior where internal __loopback__ link from network model is given to user */
414     count += pimpl->netzone_root_->get_network_model()->loopback_ ? 1 : 0;
415   }
416   return count;
417 }
418
419 /** @brief Returns the list of all links found in the platform */
420 std::vector<Link*> Engine::get_all_links() const
421 {
422   return get_filtered_links([](const Link*) { return true; });
423 }
424
425 std::vector<Link*> Engine::get_filtered_links(const std::function<bool(Link*)>& filter) const
426 {
427   std::vector<Link*> res;
428   if (pimpl->netzone_root_) {
429     res = pimpl->netzone_root_->get_filtered_links(filter);
430     /* keep behavior where internal __loopback__ link from network model is given to user */
431     if (pimpl->netzone_root_->get_network_model()->loopback_ &&
432         filter(pimpl->netzone_root_->get_network_model()->loopback_->get_iface()))
433       res.push_back(pimpl->netzone_root_->get_network_model()->loopback_->get_iface());
434   }
435   return res;
436 }
437
438 size_t Engine::get_actor_count() const
439 {
440   return pimpl->get_actor_count();
441 }
442
443 std::vector<ActorPtr> Engine::get_all_actors() const
444 {
445   std::vector<ActorPtr> actor_list;
446   for (auto const& [_, actor] : pimpl->get_actor_list()) {
447     actor_list.push_back(actor->get_iface());
448   }
449   return actor_list;
450 }
451
452 std::vector<ActorPtr> Engine::get_filtered_actors(const std::function<bool(ActorPtr)>& filter) const
453 {
454   std::vector<ActorPtr> actor_list;
455   for (auto const& [_, actor] : pimpl->get_actor_list()) {
456     if (filter(actor->get_iface()))
457       actor_list.push_back(actor->get_iface());
458   }
459   return actor_list;
460 }
461
462 void Engine::run() const
463 {
464   run_until(-1);
465 }
466 void Engine::run_until(double max_date) const
467 {
468   if (static bool callback_called = false; not callback_called) {
469     on_simulation_start();
470     callback_called = true;
471   }
472   /* Clean IO before the run */
473   fflush(stdout);
474   fflush(stderr);
475
476   pimpl->run(max_date);
477 }
478
479 void Engine::track_vetoed_activities(std::set<Activity*>* vetoed_activities) const
480 {
481   Activity::set_vetoed_activities(vetoed_activities);
482 }
483
484 /** @brief Retrieve the root netzone, containing all others */
485 s4u::NetZone* Engine::get_netzone_root() const
486 {
487   if (pimpl->netzone_root_)
488     return pimpl->netzone_root_->get_iface();
489   return nullptr;
490 }
491 /** @brief Set the root netzone, containing all others. Once set, it cannot be changed. */
492 void Engine::set_netzone_root(const s4u::NetZone* netzone)
493 {
494   xbt_assert(pimpl->netzone_root_ == nullptr, "The root NetZone cannot be changed once set");
495   pimpl->netzone_root_ = netzone->get_impl();
496 }
497
498 static NetZone* netzone_by_name_recursive(NetZone* current, const std::string& name)
499 {
500   if (current->get_name() == name)
501     return current;
502
503   for (auto const& elem : current->get_children()) {
504     NetZone* tmp = netzone_by_name_recursive(elem, name);
505     if (tmp != nullptr) {
506       return tmp;
507     }
508   }
509   return nullptr;
510 }
511
512 /** @brief Retrieve the NetZone of the given name (or nullptr if not found) */
513 NetZone* Engine::netzone_by_name_or_null(const std::string& name) const
514 {
515   return netzone_by_name_recursive(get_netzone_root(), name);
516 }
517
518 /** @brief Retrieve the netpoint of the given name (or nullptr if not found) */
519 kernel::routing::NetPoint* Engine::netpoint_by_name_or_null(const std::string& name) const
520 {
521   auto netp = pimpl->netpoints_.find(name);
522   return netp == pimpl->netpoints_.end() ? nullptr : netp->second;
523 }
524
525 kernel::routing::NetPoint* Engine::netpoint_by_name(const std::string& name) const
526 {
527   auto netp = netpoint_by_name_or_null(name);
528   if (netp == nullptr) {
529     throw std::invalid_argument("Netpoint not found: " + name);
530   }
531   return netp;
532 }
533
534 std::vector<kernel::routing::NetPoint*> Engine::get_all_netpoints() const
535 {
536   std::vector<kernel::routing::NetPoint*> res;
537   for (auto const& [_, netpoint] : pimpl->netpoints_)
538     res.push_back(netpoint);
539   return res;
540 }
541
542 /** @brief Register a new netpoint to the system */
543 void Engine::netpoint_register(kernel::routing::NetPoint* point)
544 {
545   simgrid::kernel::actor::simcall_answered([this, point] { pimpl->netpoints_[point->get_name()] = point; });
546 }
547
548 /** @brief Unregister a given netpoint */
549 void Engine::netpoint_unregister(kernel::routing::NetPoint* point)
550 {
551   kernel::actor::simcall_answered([this, point] {
552     pimpl->netpoints_.erase(point->get_name());
553     delete point;
554   });
555 }
556
557 bool Engine::is_initialized()
558 {
559   return Engine::instance_ != nullptr;
560 }
561 void Engine::set_config(const std::string& str)
562 {
563   config::set_parse(str);
564 }
565 void Engine::set_config(const std::string& name, int value)
566 {
567   config::set_value(name.c_str(), value);
568 }
569 void Engine::set_config(const std::string& name, double value)
570 {
571   config::set_value(name.c_str(), value);
572 }
573 void Engine::set_config(const std::string& name, bool value)
574 {
575   config::set_value(name.c_str(), value);
576 }
577 void Engine::set_config(const std::string& name, const std::string& value)
578 {
579   config::set_value(name.c_str(), value);
580 }
581
582 Engine* Engine::set_default_comm_data_copy_callback(
583     const std::function<void(kernel::activity::CommImpl*, void*, size_t)>& callback)
584 {
585   kernel::activity::CommImpl::set_copy_data_callback(callback);
586   return this;
587 }
588
589 } // namespace simgrid::s4u
590
591 /* **************************** Public C interface *************************** */
592 void simgrid_init(int* argc, char** argv)
593 {
594   simgrid::s4u::Engine::get_instance(argc, argv);
595 }
596 void simgrid_load_platform(const char* file)
597 {
598   simgrid::s4u::Engine::get_instance()->load_platform(file);
599 }
600
601 void simgrid_load_deployment(const char* file)
602 {
603   simgrid::s4u::Engine::get_instance()->load_deployment(file);
604 }
605 void simgrid_run()
606 {
607   simgrid::s4u::Engine::get_instance()->run();
608 }
609 void simgrid_run_until(double max_date)
610 {
611   simgrid::s4u::Engine::get_instance()->run_until(max_date);
612 }
613 void simgrid_register_function(const char* name, void (*code)(int, char**))
614 {
615   simgrid::s4u::Engine::get_instance()->register_function(name, code);
616 }
617 void simgrid_register_default(void (*code)(int, char**))
618 {
619   simgrid::s4u::Engine::get_instance()->register_default(code);
620 }
621 double simgrid_get_clock()
622 {
623   return simgrid::s4u::Engine::get_clock();
624 }
625
626 void simgrid_set_maestro(void (*code)(void*), void* data)
627 {
628   maestro_code = std::bind(code, data);
629 }