Logo AND Algorithmique Numérique Distribuée

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