Logo AND Algorithmique Numérique Distribuée

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