Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Use std::fill instead of memset.
[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::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 get_all_hosts().size();
186 }
187
188 std::vector<Host*> Engine::get_all_hosts() const
189 {
190   return get_filtered_hosts([](const Host*) { return true; });
191 }
192
193 std::vector<Host*> Engine::get_filtered_hosts(const std::function<bool(Host*)>& filter) const
194 {
195   std::vector<Host*> hosts;
196   if (pimpl->netzone_root_) {
197     hosts = pimpl->netzone_root_->get_filtered_hosts(filter);
198   }
199   /* Sort hosts in lexicographical order: keep same behavior when the hosts were saved on Engine
200    * Some tests do a get_all_hosts() and selects hosts in this order */
201   std::sort(hosts.begin(), hosts.end(), [](const auto* h1, const auto* h2) { return h1->get_name() < h2->get_name(); });
202
203   return hosts;
204 }
205
206 /** @brief Find a host from its name.
207  *
208  *  @throw std::invalid_argument if the searched host does not exist.
209  */
210 Host* Engine::host_by_name(const std::string& name) const
211 {
212   auto* host = host_by_name_or_null(name);
213   if (not host)
214     throw std::invalid_argument(std::string("Host not found: '") + name + std::string("'"));
215   return host;
216 }
217
218 /** @brief Find a host from its name (or nullptr if that host does not exist) */
219 Host* Engine::host_by_name_or_null(const std::string& name) const
220 {
221   Host* host = nullptr;
222   if (pimpl->netzone_root_) {
223     auto* host_impl = pimpl->netzone_root_->get_host_by_name_or_null(name);
224     if (host_impl)
225       host = host_impl->get_iface();
226   }
227   return host;
228 }
229
230 /** @brief Find a link from its name.
231  *
232  *  @throw std::invalid_argument if the searched link does not exist.
233  */
234 Link* Engine::link_by_name(const std::string& name) const
235 {
236   auto* link = link_by_name_or_null(name);
237   if (not link)
238     throw std::invalid_argument(std::string("Link not found: ") + name);
239   return link;
240 }
241
242 SplitDuplexLink* Engine::split_duplex_link_by_name(const std::string& name) const
243 {
244   auto* link_impl = pimpl->netzone_root_ ? pimpl->netzone_root_->get_split_duplex_link_by_name_or_null(name) : nullptr;
245   if (not link_impl)
246     throw std::invalid_argument(std::string("Link not found: ") + name);
247   return link_impl->get_iface();
248 }
249
250 /** @brief Find a link from its name (or nullptr if that link does not exist) */
251 Link* Engine::link_by_name_or_null(const std::string& name) const
252 {
253   Link* link = nullptr;
254   if (pimpl->netzone_root_) {
255     /* keep behavior where internal __loopback__ link from network model is given to user */
256     if (name == "__loopback__")
257       return pimpl->netzone_root_->get_network_model()->loopback_->get_iface();
258     auto* link_impl = pimpl->netzone_root_->get_link_by_name_or_null(name);
259     if (link_impl)
260       link = link_impl->get_iface();
261   }
262   return link;
263 }
264
265 /** @brief Find a mailbox from its name or create one if it does not exist) */
266 Mailbox* Engine::mailbox_by_name_or_create(const std::string& name) const
267 {
268   /* two actors may have pushed the same mbox_create simcall at the same time */
269   kernel::activity::MailboxImpl* mbox = kernel::actor::simcall_answered([&name, this] {
270     auto [m, inserted] = pimpl->mailboxes_.try_emplace(name, nullptr);
271     if (inserted) {
272       m->second = new kernel::activity::MailboxImpl(name);
273       XBT_DEBUG("Creating a mailbox at %p with name %s", m->second, name.c_str());
274     }
275     return m->second;
276   });
277   return mbox->get_iface();
278 }
279
280 /** @brief Returns the amount of links in the platform */
281 size_t Engine::get_link_count() const
282 {
283   int count = 0;
284   if (pimpl->netzone_root_) {
285     count += pimpl->netzone_root_->get_link_count();
286     /* keep behavior where internal __loopback__ link from network model is given to user */
287     count += pimpl->netzone_root_->get_network_model()->loopback_ ? 1 : 0;
288   }
289   return count;
290 }
291
292 /** @brief Returns the list of all links found in the platform */
293 std::vector<Link*> Engine::get_all_links() const
294 {
295   return get_filtered_links([](const Link*) { return true; });
296 }
297
298 std::vector<Link*> Engine::get_filtered_links(const std::function<bool(Link*)>& filter) const
299 {
300   std::vector<Link*> res;
301   if (pimpl->netzone_root_) {
302     res = pimpl->netzone_root_->get_filtered_links(filter);
303     /* keep behavior where internal __loopback__ link from network model is given to user */
304     if (pimpl->netzone_root_->get_network_model()->loopback_ &&
305         filter(pimpl->netzone_root_->get_network_model()->loopback_->get_iface()))
306       res.push_back(pimpl->netzone_root_->get_network_model()->loopback_->get_iface());
307   }
308   return res;
309 }
310
311 size_t Engine::get_actor_count() const
312 {
313   return pimpl->get_actor_count();
314 }
315
316 std::vector<ActorPtr> Engine::get_all_actors() const
317 {
318   std::vector<ActorPtr> actor_list;
319   for (auto const& [_, actor] : pimpl->get_actor_list()) {
320     actor_list.push_back(actor->get_iface());
321   }
322   return actor_list;
323 }
324
325 std::vector<ActorPtr> Engine::get_filtered_actors(const std::function<bool(ActorPtr)>& filter) const
326 {
327   std::vector<ActorPtr> actor_list;
328   for (auto const& [_, actor] : pimpl->get_actor_list()) {
329     if (filter(actor->get_iface()))
330       actor_list.push_back(actor->get_iface());
331   }
332   return actor_list;
333 }
334
335 void Engine::run() const
336 {
337   run_until(-1);
338 }
339 void Engine::run_until(double max_date) const
340 {
341   if (static bool callback_called = false; not callback_called) {
342     on_simulation_start();
343     callback_called = true;
344   }
345   /* Clean IO before the run */
346   fflush(stdout);
347   fflush(stderr);
348
349   pimpl->run(max_date);
350 }
351
352 void Engine::track_vetoed_activities(std::set<Activity*>* vetoed_activities) const
353 {
354   Activity::set_vetoed_activities(vetoed_activities);
355 }
356
357 /** @brief Retrieve the root netzone, containing all others */
358 s4u::NetZone* Engine::get_netzone_root() const
359 {
360   if (pimpl->netzone_root_)
361     return pimpl->netzone_root_->get_iface();
362   return nullptr;
363 }
364 /** @brief Set the root netzone, containing all others. Once set, it cannot be changed. */
365 void Engine::set_netzone_root(const s4u::NetZone* netzone)
366 {
367   xbt_assert(pimpl->netzone_root_ == nullptr, "The root NetZone cannot be changed once set");
368   pimpl->netzone_root_ = netzone->get_impl();
369 }
370
371 static NetZone* netzone_by_name_recursive(NetZone* current, const std::string& name)
372 {
373   if (current->get_name() == name)
374     return current;
375
376   for (auto const& elem : current->get_children()) {
377     NetZone* tmp = netzone_by_name_recursive(elem, name);
378     if (tmp != nullptr) {
379       return tmp;
380     }
381   }
382   return nullptr;
383 }
384
385 /** @brief Retrieve the NetZone of the given name (or nullptr if not found) */
386 NetZone* Engine::netzone_by_name_or_null(const std::string& name) const
387 {
388   return netzone_by_name_recursive(get_netzone_root(), name);
389 }
390
391 /** @brief Retrieve the netpoint of the given name (or nullptr if not found) */
392 kernel::routing::NetPoint* Engine::netpoint_by_name_or_null(const std::string& name) const
393 {
394   auto netp = pimpl->netpoints_.find(name);
395   return netp == pimpl->netpoints_.end() ? nullptr : netp->second;
396 }
397
398 kernel::routing::NetPoint* Engine::netpoint_by_name(const std::string& name) const
399 {
400   auto netp = netpoint_by_name_or_null(name);
401   if (netp == nullptr) {
402     throw std::invalid_argument(std::string("Netpoint not found: %s") + name);
403   }
404   return netp;
405 }
406
407 std::vector<kernel::routing::NetPoint*> Engine::get_all_netpoints() const
408 {
409   std::vector<kernel::routing::NetPoint*> res;
410   for (auto const& [_, netpoint] : pimpl->netpoints_)
411     res.push_back(netpoint);
412   return res;
413 }
414
415 /** @brief Register a new netpoint to the system */
416 void Engine::netpoint_register(kernel::routing::NetPoint* point)
417 {
418   simgrid::kernel::actor::simcall_answered([this, point] { pimpl->netpoints_[point->get_name()] = point; });
419 }
420
421 /** @brief Unregister a given netpoint */
422 void Engine::netpoint_unregister(kernel::routing::NetPoint* point)
423 {
424   kernel::actor::simcall_answered([this, point] {
425     pimpl->netpoints_.erase(point->get_name());
426     delete point;
427   });
428 }
429
430 bool Engine::is_initialized()
431 {
432   return Engine::instance_ != nullptr;
433 }
434 void Engine::set_config(const std::string& str)
435 {
436   config::set_parse(str);
437 }
438 void Engine::set_config(const std::string& name, int value)
439 {
440   config::set_value(name.c_str(), value);
441 }
442 void Engine::set_config(const std::string& name, double value)
443 {
444   config::set_value(name.c_str(), value);
445 }
446 void Engine::set_config(const std::string& name, bool value)
447 {
448   config::set_value(name.c_str(), value);
449 }
450 void Engine::set_config(const std::string& name, const std::string& value)
451 {
452   config::set_value(name.c_str(), value);
453 }
454
455 Engine* Engine::set_default_comm_data_copy_callback(
456     const std::function<void(kernel::activity::CommImpl*, void*, size_t)>& callback)
457 {
458   kernel::activity::CommImpl::set_copy_data_callback(callback);
459   return this;
460 }
461
462 } // namespace simgrid::s4u
463
464 /* **************************** Public C interface *************************** */
465 void simgrid_init(int* argc, char** argv)
466 {
467   static simgrid::s4u::Engine e(argc, argv);
468 }
469 void simgrid_load_platform(const char* file)
470 {
471   simgrid::s4u::Engine::get_instance()->load_platform(file);
472 }
473
474 void simgrid_load_deployment(const char* file)
475 {
476   simgrid::s4u::Engine::get_instance()->load_deployment(file);
477 }
478 void simgrid_run()
479 {
480   simgrid::s4u::Engine::get_instance()->run();
481 }
482 void simgrid_run_until(double max_date)
483 {
484   simgrid::s4u::Engine::get_instance()->run_until(max_date);
485 }
486 void simgrid_register_function(const char* name, void (*code)(int, char**))
487 {
488   simgrid::s4u::Engine::get_instance()->register_function(name, code);
489 }
490 void simgrid_register_default(void (*code)(int, char**))
491 {
492   simgrid::s4u::Engine::get_instance()->register_default(code);
493 }
494 double simgrid_get_clock()
495 {
496   return simgrid::s4u::Engine::get_clock();
497 }
498
499 void simgrid_set_maestro(void (*code)(void*), void* data)
500 {
501 #ifdef _WIN32
502   XBT_WARN("simgrid_set_maestro is believed to not work on windows. Please help us investigating this issue if "
503            "you need that feature");
504 #endif
505   maestro_code = std::bind(code, data);
506 }
507 void SIMIX_set_maestro(void (*code)(void*), void* data) // XBT_ATTRIB_DEPRECATED_v333
508 {
509   simgrid_set_maestro(code, data);
510 }