Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Prefer using "try_emplace" (sonar, c++17).
[simgrid.git] / src / s4u / s4u_Engine.cpp
1 /* s4u::Engine Simulation Engine and global functions. */
2
3 /* Copyright (c) 2006-2022. 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 #define SIMIX_H_NO_DEPRECATED_WARNING // avoid deprecation warning on include (remove with XBT_ATTRIB_DEPRECATED_v333)
13 #include <simgrid/simix.h>
14
15 #include "mc/mc.h"
16 #include "src/instr/instr_private.hpp"
17 #include "src/kernel/EngineImpl.hpp"
18 #include "src/kernel/resource/NetworkModel.hpp"
19 #include "src/kernel/resource/SplitDuplexLinkImpl.hpp"
20 #include "src/kernel/resource/StandardLinkImpl.hpp"
21 #include "src/mc/mc_replay.hpp"
22 #include "src/surf/HostImpl.hpp"
23 #include "xbt/config.hpp"
24
25 #include <algorithm>
26 #include <string>
27
28 XBT_LOG_NEW_CATEGORY(s4u, "Log channels of the S4U (Simgrid for you) interface");
29 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(s4u_engine, s4u, "Logging specific to S4U (engine)");
30
31 static simgrid::kernel::actor::ActorCode maestro_code;
32
33 namespace simgrid {
34 namespace s4u {
35 xbt::signal<void()> Engine::on_platform_creation;
36 xbt::signal<void()> Engine::on_platform_created;
37 xbt::signal<void()> Engine::on_simulation_start;
38 xbt::signal<void()> Engine::on_simulation_end;
39 xbt::signal<void(double)> Engine::on_time_advance;
40 xbt::signal<void(void)> Engine::on_deadlock;
41
42 Engine* Engine::instance_ = nullptr; /* This singleton is awful, but I don't see no other solution right now. */
43
44 void Engine::initialize(int* argc, char** argv)
45 {
46   xbt_assert(Engine::instance_ == nullptr, "It is currently forbidden to create more than one instance of s4u::Engine");
47   Engine::instance_ = this;
48   instr::init();
49   pimpl->initialize(argc, argv);
50   // Either create a new context with maestro or create
51   // a context object with the current context maestro):
52   kernel::actor::create_maestro(maestro_code);
53 }
54
55 Engine::Engine(std::string name) : pimpl(new kernel::EngineImpl())
56 {
57   int argc   = 1;
58   char* argv = &name[0];
59   initialize(&argc, &argv);
60 }
61
62 Engine::Engine(int* argc, char** argv) : pimpl(new kernel::EngineImpl())
63 {
64   initialize(argc, argv);
65 }
66
67 Engine::~Engine()
68 {
69   kernel::EngineImpl::shutdown();
70   Engine::instance_ = nullptr;
71 }
72
73 /** @brief Retrieve the engine singleton */
74 Engine* Engine::get_instance()
75 {
76   int argc   = 0;
77   char* argv = nullptr;
78   return get_instance(&argc, &argv);
79 }
80 Engine* Engine::get_instance(int* argc, char** argv)
81 {
82   if (Engine::instance_ == nullptr) {
83     auto e = new Engine(argc, argv);
84     xbt_assert(Engine::instance_ == e);
85   }
86   return Engine::instance_;
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 /**
115  * Creates a new platform, including hosts, links, and the routing table.
116  *
117  * @beginrst
118  * See also: :ref:`platform`.
119  * @endrst
120  */
121 void Engine::load_platform(const std::string& platf) const
122 {
123   pimpl->load_platform(platf);
124 }
125
126 /**
127  * @brief Seals the platform, finishing the creation of its resources.
128  *
129  * This method is optional. The seal() is done automatically when you call Engine::run.
130  */
131 void Engine::seal_platform() const
132 {
133   pimpl->seal_platform();
134 }
135
136 /** Registers the main function of an actor that will be launched from the deployment file */
137 void Engine::register_function(const std::string& name, const std::function<void(int, char**)>& code)
138 {
139   kernel::actor::ActorCodeFactory code_factory = [code](std::vector<std::string> args) {
140     return xbt::wrap_main(code, std::move(args));
141   };
142   register_function(name, code_factory);
143 }
144
145 /** Registers the main function of an actor that will be launched from the deployment file */
146 void Engine::register_function(const std::string& name, const std::function<void(std::vector<std::string>)>& code)
147 {
148   kernel::actor::ActorCodeFactory code_factory = [code{code}](std::vector<std::string> args) mutable {
149     return std::bind(std::move(code), std::move(args));
150   };
151   register_function(name, code_factory);
152 }
153 /** Registers a function as the default main function of actors
154  *
155  * It will be used as fallback when the function requested from the deployment file was not registered.
156  * It is used for trace-based simulations (see examples/cpp/replay-comms and similar).
157  */
158 void Engine::register_default(const std::function<void(int, char**)>& code)
159 {
160   register_default([code](std::vector<std::string> args) { return xbt::wrap_main(code, std::move(args)); });
161 }
162 void Engine::register_default(const kernel::actor::ActorCodeFactory& code)
163 {
164   simgrid::kernel::actor::simcall_answered([this, &code]() { pimpl->register_default(code); });
165 }
166
167 void Engine::register_function(const std::string& name, const kernel::actor::ActorCodeFactory& code)
168 {
169   simgrid::kernel::actor::simcall_answered([this, name, &code]() { pimpl->register_function(name, code); });
170 }
171
172 /** Load a deployment file and launch the actors that it contains
173  *
174  * @beginrst
175  * See also: :ref:`deploy`.
176  * @endrst
177  */
178 void Engine::load_deployment(const std::string& deploy) const
179 {
180   pimpl->load_deployment(deploy);
181 }
182
183 /** Returns the amount of hosts in the platform */
184 size_t Engine::get_host_count() const
185 {
186   return get_all_hosts().size();
187 }
188
189 std::vector<Host*> Engine::get_all_hosts() const
190 {
191   return get_filtered_hosts([](const Host*) { return true; });
192 }
193
194 std::vector<Host*> Engine::get_filtered_hosts(const std::function<bool(Host*)>& filter) const
195 {
196   std::vector<Host*> hosts;
197   if (pimpl->netzone_root_) {
198     hosts = pimpl->netzone_root_->get_filtered_hosts(filter);
199   }
200   /* Sort hosts in lexicographical order: keep same behavior when the hosts were saved on Engine
201    * Some tests do a get_all_hosts() and selects hosts in this order */
202   std::sort(hosts.begin(), hosts.end(), [](const auto* h1, const auto* h2) { return h1->get_name() < h2->get_name(); });
203
204   return hosts;
205 }
206
207 /** @brief Find a host from its name.
208  *
209  *  @throw std::invalid_argument if the searched host does not exist.
210  */
211 Host* Engine::host_by_name(const std::string& name) const
212 {
213   auto* host = host_by_name_or_null(name);
214   if (not host)
215     throw std::invalid_argument(std::string("Host not found: '") + name + std::string("'"));
216   return host;
217 }
218
219 /** @brief Find a host from its name (or nullptr if that host does not exist) */
220 Host* Engine::host_by_name_or_null(const std::string& name) const
221 {
222   Host* host = nullptr;
223   if (pimpl->netzone_root_) {
224     auto* host_impl = pimpl->netzone_root_->get_host_by_name_or_null(name);
225     if (host_impl)
226       host = host_impl->get_iface();
227   }
228   return host;
229 }
230
231 /** @brief Find a link from its name.
232  *
233  *  @throw std::invalid_argument if the searched link does not exist.
234  */
235 Link* Engine::link_by_name(const std::string& name) const
236 {
237   auto* link = link_by_name_or_null(name);
238   if (not link)
239     throw std::invalid_argument(std::string("Link not found: ") + name);
240   return link;
241 }
242
243 SplitDuplexLink* Engine::split_duplex_link_by_name(const std::string& name) const
244 {
245   auto* link_impl = pimpl->netzone_root_ ? pimpl->netzone_root_->get_split_duplex_link_by_name_or_null(name) : nullptr;
246   if (not link_impl)
247     throw std::invalid_argument(std::string("Link not found: ") + name);
248   return link_impl->get_iface();
249 }
250
251 /** @brief Find a link from its name (or nullptr if that link does not exist) */
252 Link* Engine::link_by_name_or_null(const std::string& name) const
253 {
254   Link* link = nullptr;
255   if (pimpl->netzone_root_) {
256     /* keep behavior where internal __loopback__ link from network model is given to user */
257     if (name == "__loopback__")
258       return pimpl->netzone_root_->get_network_model()->loopback_->get_iface();
259     auto* link_impl = pimpl->netzone_root_->get_link_by_name_or_null(name);
260     if (link_impl)
261       link = link_impl->get_iface();
262   }
263   return link;
264 }
265
266 /** @brief Find a mailbox from its name or create one if it does not exist) */
267 Mailbox* Engine::mailbox_by_name_or_create(const std::string& name) const
268 {
269   /* two actors may have pushed the same mbox_create simcall at the same time */
270   kernel::activity::MailboxImpl* mbox = kernel::actor::simcall_answered([&name, this] {
271     auto m = pimpl->mailboxes_.try_emplace(name, nullptr);
272     if (m.second) {
273       m.first->second = new kernel::activity::MailboxImpl(name);
274       XBT_DEBUG("Creating a mailbox at %p with name %s", m.first->second, name.c_str());
275     }
276     return m.first->second;
277   });
278   return mbox->get_iface();
279 }
280
281 /** @brief Returns the amount of links in the platform */
282 size_t Engine::get_link_count() const
283 {
284   int count = 0;
285   if (pimpl->netzone_root_) {
286     count += pimpl->netzone_root_->get_link_count();
287     /* keep behavior where internal __loopback__ link from network model is given to user */
288     count += pimpl->netzone_root_->get_network_model()->loopback_ ? 1 : 0;
289   }
290   return count;
291 }
292
293 /** @brief Returns the list of all links found in the platform */
294 std::vector<Link*> Engine::get_all_links() const
295 {
296   return get_filtered_links([](const Link*) { return true; });
297 }
298
299 std::vector<Link*> Engine::get_filtered_links(const std::function<bool(Link*)>& filter) const
300 {
301   std::vector<Link*> res;
302   if (pimpl->netzone_root_) {
303     res = pimpl->netzone_root_->get_filtered_links(filter);
304     /* keep behavior where internal __loopback__ link from network model is given to user */
305     if (pimpl->netzone_root_->get_network_model()->loopback_ &&
306         filter(pimpl->netzone_root_->get_network_model()->loopback_->get_iface()))
307       res.push_back(pimpl->netzone_root_->get_network_model()->loopback_->get_iface());
308   }
309   return res;
310 }
311
312 size_t Engine::get_actor_count() const
313 {
314   return pimpl->get_actor_count();
315 }
316
317 std::vector<ActorPtr> Engine::get_all_actors() const
318 {
319   std::vector<ActorPtr> actor_list;
320   for (auto const& kv : pimpl->get_actor_list()) {
321     actor_list.push_back(kv.second->get_iface());
322   }
323   return actor_list;
324 }
325
326 std::vector<ActorPtr> Engine::get_filtered_actors(const std::function<bool(ActorPtr)>& filter) const
327 {
328   std::vector<ActorPtr> actor_list;
329   for (auto const& kv : pimpl->get_actor_list()) {
330     if (filter(kv.second->get_iface()))
331       actor_list.push_back(kv.second->get_iface());
332   }
333   return actor_list;
334 }
335
336 void Engine::run() const
337 {
338   run_until(-1);
339 }
340 void Engine::run_until(double max_date) const
341 {
342   static bool callback_called = false;
343   if (not callback_called) {
344     on_simulation_start();
345     callback_called = true;
346   }
347   /* Clean IO before the run */
348   fflush(stdout);
349   fflush(stderr);
350
351   pimpl->run(max_date);
352 }
353
354 void Engine::track_vetoed_activities(std::set<Activity*>* vetoed_activities) const
355 {
356   Activity::set_vetoed_activities(vetoed_activities);
357 }
358
359 /** @brief Retrieve the root netzone, containing all others */
360 s4u::NetZone* Engine::get_netzone_root() const
361 {
362   if (pimpl->netzone_root_)
363     return pimpl->netzone_root_->get_iface();
364   return nullptr;
365 }
366 /** @brief Set the root netzone, containing all others. Once set, it cannot be changed. */
367 void Engine::set_netzone_root(const s4u::NetZone* netzone)
368 {
369   xbt_assert(pimpl->netzone_root_ == nullptr, "The root NetZone cannot be changed once set");
370   pimpl->netzone_root_ = netzone->get_impl();
371 }
372
373 static NetZone* netzone_by_name_recursive(NetZone* current, const std::string& name)
374 {
375   if (current->get_name() == name)
376     return current;
377
378   for (auto const& elem : current->get_children()) {
379     NetZone* tmp = netzone_by_name_recursive(elem, name);
380     if (tmp != nullptr) {
381       return tmp;
382     }
383   }
384   return nullptr;
385 }
386
387 /** @brief Retrieve the NetZone of the given name (or nullptr if not found) */
388 NetZone* Engine::netzone_by_name_or_null(const std::string& name) const
389 {
390   return netzone_by_name_recursive(get_netzone_root(), name);
391 }
392
393 /** @brief Retrieve the netpoint of the given name (or nullptr if not found) */
394 kernel::routing::NetPoint* Engine::netpoint_by_name_or_null(const std::string& name) const
395 {
396   auto netp = pimpl->netpoints_.find(name);
397   return netp == pimpl->netpoints_.end() ? nullptr : netp->second;
398 }
399
400 kernel::routing::NetPoint* Engine::netpoint_by_name(const std::string& name) const
401 {
402   auto netp = netpoint_by_name_or_null(name);
403   if (netp == nullptr) {
404     throw std::invalid_argument(std::string("Netpoint not found: %s") + name);
405   }
406   return netp;
407 }
408
409 std::vector<kernel::routing::NetPoint*> Engine::get_all_netpoints() const
410 {
411   std::vector<kernel::routing::NetPoint*> res;
412   for (auto const& kv : pimpl->netpoints_)
413     res.push_back(kv.second);
414   return res;
415 }
416
417 /** @brief Register a new netpoint to the system */
418 void Engine::netpoint_register(kernel::routing::NetPoint* point)
419 {
420   simgrid::kernel::actor::simcall_answered([this, point] { pimpl->netpoints_[point->get_name()] = point; });
421 }
422
423 /** @brief Unregister a given netpoint */
424 void Engine::netpoint_unregister(kernel::routing::NetPoint* point)
425 {
426   kernel::actor::simcall_answered([this, point] {
427     pimpl->netpoints_.erase(point->get_name());
428     delete point;
429   });
430 }
431
432 bool Engine::is_initialized()
433 {
434   return Engine::instance_ != nullptr;
435 }
436 void Engine::set_config(const std::string& str)
437 {
438   config::set_parse(str);
439 }
440 void Engine::set_config(const std::string& name, int value)
441 {
442   config::set_value(name.c_str(), value);
443 }
444 void Engine::set_config(const std::string& name, double value)
445 {
446   config::set_value(name.c_str(), value);
447 }
448 void Engine::set_config(const std::string& name, bool value)
449 {
450   config::set_value(name.c_str(), value);
451 }
452 void Engine::set_config(const std::string& name, const std::string& value)
453 {
454   config::set_value(name.c_str(), value);
455 }
456
457 Engine* Engine::set_default_comm_data_copy_callback(
458     const std::function<void(kernel::activity::CommImpl*, void*, size_t)>& callback)
459 {
460   kernel::activity::CommImpl::set_copy_data_callback(callback);
461   return this;
462 }
463
464 } // namespace s4u
465 } // namespace simgrid
466
467 /* **************************** Public C interface *************************** */
468 void simgrid_init(int* argc, char** argv)
469 {
470   static simgrid::s4u::Engine e(argc, argv);
471 }
472 void simgrid_load_platform(const char* file)
473 {
474   simgrid::s4u::Engine::get_instance()->load_platform(file);
475 }
476
477 void simgrid_load_deployment(const char* file)
478 {
479   simgrid::s4u::Engine::get_instance()->load_deployment(file);
480 }
481 void simgrid_run()
482 {
483   simgrid::s4u::Engine::get_instance()->run();
484 }
485 void simgrid_run_until(double max_date)
486 {
487   simgrid::s4u::Engine::get_instance()->run_until(max_date);
488 }
489 void simgrid_register_function(const char* name, void (*code)(int, char**))
490 {
491   simgrid::s4u::Engine::get_instance()->register_function(name, code);
492 }
493 void simgrid_register_default(void (*code)(int, char**))
494 {
495   simgrid::s4u::Engine::get_instance()->register_default(code);
496 }
497 double simgrid_get_clock()
498 {
499   return simgrid::s4u::Engine::get_clock();
500 }
501
502 void simgrid_set_maestro(void (*code)(void*), void* data)
503 {
504 #ifdef _WIN32
505   XBT_WARN("simgrid_set_maestro is believed to not work on windows. Please help us investigating this issue if "
506            "you need that feature");
507 #endif
508   maestro_code = std::bind(code, data);
509 }
510 void SIMIX_set_maestro(void (*code)(void*), void* data) // XBT_ATTRIB_DEPRECATED_v333
511 {
512   simgrid_set_maestro(code, data);
513 }