Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge branch 'master' of https://framagit.org/simgrid/simgrid into no_simix_global
[simgrid.git] / src / kernel / EngineImpl.cpp
1 /* Copyright (c) 2016-2021. The SimGrid Team. All rights reserved.          */
2
3 /* This program is free software; you can redistribute it and/or modify it
4  * under the terms of the license (GNU LGPL) which comes with this package. */
5
6 #include "src/kernel/EngineImpl.hpp"
7 #include "mc/mc.h"
8 #include "simgrid/Exception.hpp"
9 #include "simgrid/kernel/Timer.hpp"
10 #include "simgrid/kernel/routing/NetPoint.hpp"
11 #include "simgrid/kernel/routing/NetZoneImpl.hpp"
12 #include "simgrid/s4u/Host.hpp"
13 #include "simgrid/sg_config.hpp"
14 #include "src/include/surf/surf.hpp" //get_clock() and surf_solve()
15 #include "src/kernel/resource/DiskImpl.hpp"
16 #include "src/kernel/resource/profile/Profile.hpp"
17 #include "src/mc/mc_record.hpp"
18 #include "src/mc/mc_replay.hpp"
19 #include "src/simix/smx_private.hpp"
20 #include "src/smpi/include/smpi_actor.hpp"
21 #include "src/surf/network_interface.hpp"
22 #include "src/surf/xml/platf.hpp" // FIXME: KILLME. There must be a better way than mimicking XML here
23
24 #include <boost/algorithm/string/predicate.hpp>
25 #ifndef _WIN32
26 #include <dlfcn.h>
27 #endif /* _WIN32 */
28
29 XBT_LOG_NEW_DEFAULT_CATEGORY(ker_engine, "Logging specific to Engine (kernel)");
30
31 namespace simgrid {
32 namespace kernel {
33 EngineImpl* EngineImpl::instance_ = nullptr; /* That singleton is awful too. */
34
35 config::Flag<double> cfg_breakpoint{"debug/breakpoint",
36                                     "When non-negative, raise a SIGTRAP after given (simulated) time", -1.0};
37 void EngineImpl::shutdown()
38 {
39   static bool already_cleaned_up = false;
40   if (already_cleaned_up)
41     return; // to avoid double cleaning by java and C
42   already_cleaned_up = true;
43   if (not EngineImpl::instance_) {
44     simix_global->destroy_maestro();
45     simix_global->destroy_context_factory();
46     return; // Nothing more to shutdown
47   }
48   XBT_DEBUG("EngineImpl::shutdown() called. Simulation's over.");
49
50   if (instance_->has_actors_to_run() && simgrid_get_clock() <= 0.0) {
51     XBT_CRITICAL("   ");
52     XBT_CRITICAL("The time is still 0, and you still have processes ready to run.");
53     XBT_CRITICAL("It seems that you forgot to run the simulation that you setup.");
54     xbt_die("Bailing out to avoid that stop-before-start madness. Please fix your code.");
55   }
56
57 #if HAVE_SMPI
58   if (not instance_->actor_list_.empty()) {
59     if (smpi_process()->initialized()) {
60       xbt_die("Process exited without calling MPI_Finalize - Killing simulation");
61     } else {
62       XBT_WARN("Process called exit when leaving - Skipping cleanups");
63       return;
64     }
65   }
66 #endif
67
68   /* Kill all actors (but maestro) */
69   simix_global->get_maestro()->kill_all();
70   instance_->run_all_actors();
71   instance_->empty_trash();
72
73   /* Let's free maestro now */
74   simix_global->destroy_maestro();
75
76   /* Finish context module and SURF */
77   simix_global->destroy_context_factory();
78
79   while (not timer::kernel_timers().empty()) {
80     delete timer::kernel_timers().top().second;
81     timer::kernel_timers().pop();
82   }
83
84   tmgr_finalize();
85   sg_platf_exit();
86
87   simgrid::s4u::Engine::shutdown();
88
89   simix_global = nullptr;
90 }
91
92 EngineImpl::~EngineImpl()
93 {
94   /* Since hosts_ is a std::map, the hosts are destroyed in the lexicographic order, which ensures that the output is
95    * reproducible.
96    */
97   while (not hosts_.empty())
98     hosts_.begin()->second->destroy();
99
100   /* Also delete the other data */
101   delete netzone_root_;
102   for (auto const& kv : netpoints_)
103     delete kv.second;
104
105   for (auto const& kv : links_)
106     if (kv.second)
107       kv.second->destroy();
108
109   for (auto const& kv : mailboxes_)
110     delete kv.second;
111
112     /* Free the remaining data structures */
113 #if SIMGRID_HAVE_MC
114   xbt_dynar_free(&actors_vector_);
115   xbt_dynar_free(&dead_actors_vector_);
116 #endif
117   /* clear models before freeing handle, network models can use external callback defined in the handle */
118   models_prio_.clear();
119 }
120
121 void EngineImpl::load_platform(const std::string& platf)
122 {
123   double start = xbt_os_time();
124   if (boost::algorithm::ends_with(platf, ".so") or boost::algorithm::ends_with(platf, ".dylib")) {
125 #ifdef _WIN32
126     xbt_die("loading platform through shared library isn't supported on windows");
127 #else
128     void* handle = dlopen(platf.c_str(), RTLD_LAZY);
129     xbt_assert(handle, "Impossible to open platform file: %s", platf.c_str());
130     platf_handle_           = std::unique_ptr<void, std::function<int(void*)>>(handle, dlclose);
131     using load_fct_t = void (*)(const simgrid::s4u::Engine&);
132     auto callable           = (load_fct_t)dlsym(platf_handle_.get(), "load_platform");
133     const char* dlsym_error = dlerror();
134     xbt_assert(not dlsym_error, "Error: %s", dlsym_error);
135     callable(*simgrid::s4u::Engine::get_instance());
136 #endif /* _WIN32 */
137   } else {
138     parse_platform_file(platf);
139   }
140
141   double end = xbt_os_time();
142   XBT_DEBUG("PARSE TIME: %g", (end - start));
143 }
144
145 void EngineImpl::load_deployment(const std::string& file) const
146 {
147   sg_platf_exit();
148   sg_platf_init();
149
150   surf_parse_open(file);
151   surf_parse();
152   surf_parse_close();
153 }
154
155 void EngineImpl::register_function(const std::string& name, const actor::ActorCodeFactory& code)
156 {
157   registered_functions[name] = code;
158 }
159 void EngineImpl::register_default(const actor::ActorCodeFactory& code)
160 {
161   default_function = code;
162 }
163
164 void EngineImpl::add_model(std::shared_ptr<resource::Model> model, const std::vector<resource::Model*>& dependencies)
165 {
166   auto model_name = model->get_name();
167   xbt_assert(models_prio_.find(model_name) == models_prio_.end(),
168              "Model %s already exists, use model.set_name() to change its name", model_name.c_str());
169
170   for (const auto dep : dependencies) {
171     xbt_assert(models_prio_.find(dep->get_name()) != models_prio_.end(),
172                "Model %s doesn't exists. Impossible to use it as dependency.", dep->get_name().c_str());
173   }
174   models_.push_back(model.get());
175   models_prio_[model_name] = std::move(model);
176 }
177
178 void EngineImpl::add_split_duplex_link(const std::string& name, std::unique_ptr<resource::SplitDuplexLinkImpl> link)
179 {
180   split_duplex_links_[name] = std::move(link);
181 }
182
183 /** Wake up all actors waiting for a Surf action to finish */
184 void EngineImpl::wake_all_waiting_actors() const
185 {
186   for (auto const& model : models_) {
187     XBT_DEBUG("Handling the failed actions (if any)");
188     while (auto* action = model->extract_failed_action()) {
189       XBT_DEBUG("   Handling Action %p", action);
190       if (action->get_activity() != nullptr)
191         activity::ActivityImplPtr(action->get_activity())->post();
192     }
193     XBT_DEBUG("Handling the terminated actions (if any)");
194     while (auto* action = model->extract_done_action()) {
195       XBT_DEBUG("   Handling Action %p", action);
196       if (action->get_activity() == nullptr)
197         XBT_DEBUG("probably vcpu's action %p, skip", action);
198       else
199         activity::ActivityImplPtr(action->get_activity())->post();
200     }
201   }
202 }
203 /**
204  * @brief Executes the actors in actors_to_run.
205  *
206  * The actors in actors_to_run are run (in parallel if possible). On exit, actors_to_run is empty, and actors_that_ran
207  * contains the list of actors that just ran.  The two lists are swapped so, be careful when using them before and after
208  * a call to this function.
209  */
210 void EngineImpl::run_all_actors()
211 {
212   simix_global->get_context_factory()->run_all();
213
214   actors_to_run_.swap(actors_that_ran_);
215   actors_to_run_.clear();
216 }
217
218 actor::ActorImpl* EngineImpl::get_actor_by_pid(aid_t pid)
219 {
220   auto item = actor_list_.find(pid);
221   if (item != actor_list_.end())
222     return item->second;
223
224   // Search the trash
225   for (auto& a : actors_to_destroy_)
226     if (a.get_pid() == pid)
227       return &a;
228   return nullptr; // Not found, even in the trash
229 }
230 /** Execute all the tasks that are queued, e.g. `.then()` callbacks of futures. */
231 bool EngineImpl::execute_tasks()
232 {
233   if (tasks.empty())
234     return false;
235
236   std::vector<xbt::Task<void()>> tasksTemp;
237   do {
238     // We don't want the callbacks to modify the vector we are iterating over:
239     tasks.swap(tasksTemp);
240
241     // Execute all the queued tasks:
242     for (auto& task : tasksTemp)
243       task();
244
245     tasksTemp.clear();
246   } while (not tasks.empty());
247
248   return true;
249 }
250
251 void EngineImpl::remove_daemon(actor::ActorImpl* actor)
252 {
253   auto it = daemons_.find(actor);
254   xbt_assert(it != daemons_.end(), "The dying daemon is not a daemon after all. Please report that bug.");
255   daemons_.erase(it);
256 }
257
258 void EngineImpl::add_actor_to_run_list_no_check(actor::ActorImpl* actor)
259 {
260   XBT_DEBUG("Inserting [%p] %s(%s) in the to_run list", actor, actor->get_cname(), actor->get_host()->get_cname());
261   actors_to_run_.push_back(actor);
262 }
263
264 void EngineImpl::add_actor_to_run_list(actor::ActorImpl* actor)
265 {
266   if (std::find(begin(actors_to_run_), end(actors_to_run_), actor) != end(actors_to_run_)) {
267     XBT_DEBUG("Actor %s is already in the to_run list", actor->get_cname());
268   } else {
269     XBT_DEBUG("Inserting [%p] %s(%s) in the to_run list", actor, actor->get_cname(), actor->get_host()->get_cname());
270     actors_to_run_.push_back(actor);
271   }
272 }
273 void EngineImpl::empty_trash()
274 {
275   while (not actors_to_destroy_.empty()) {
276     actor::ActorImpl* actor = &actors_to_destroy_.front();
277     actors_to_destroy_.pop_front();
278     XBT_DEBUG("Getting rid of %s (refcount: %d)", actor->get_cname(), actor->get_refcount());
279     intrusive_ptr_release(actor);
280   }
281 #if SIMGRID_HAVE_MC
282   xbt_dynar_reset(dead_actors_vector_);
283 #endif
284 }
285
286 void EngineImpl::display_all_actor_status() const
287 {
288   XBT_INFO("%zu actors are still running, waiting for something.", actor_list_.size());
289   /*  List the actors and their state */
290   XBT_INFO("Legend of the following listing: \"Actor <pid> (<name>@<host>): <status>\"");
291   for (auto const& kv : actor_list_) {
292     actor::ActorImpl* actor = kv.second;
293
294     if (actor->waiting_synchro_) {
295       const char* synchro_description = "unknown";
296
297       if (boost::dynamic_pointer_cast<kernel::activity::ExecImpl>(actor->waiting_synchro_) != nullptr)
298         synchro_description = "execution";
299
300       if (boost::dynamic_pointer_cast<kernel::activity::CommImpl>(actor->waiting_synchro_) != nullptr)
301         synchro_description = "communication";
302
303       if (boost::dynamic_pointer_cast<kernel::activity::SleepImpl>(actor->waiting_synchro_) != nullptr)
304         synchro_description = "sleeping";
305
306       if (boost::dynamic_pointer_cast<kernel::activity::RawImpl>(actor->waiting_synchro_) != nullptr)
307         synchro_description = "synchronization";
308
309       if (boost::dynamic_pointer_cast<kernel::activity::IoImpl>(actor->waiting_synchro_) != nullptr)
310         synchro_description = "I/O";
311
312       XBT_INFO("Actor %ld (%s@%s): waiting for %s activity %#zx (%s) in state %d to finish", actor->get_pid(),
313                actor->get_cname(), actor->get_host()->get_cname(), synchro_description,
314                (xbt_log_no_loc ? (size_t)0xDEADBEEF : (size_t)actor->waiting_synchro_.get()),
315                actor->waiting_synchro_->get_cname(), (int)actor->waiting_synchro_->state_);
316     } else {
317       XBT_INFO("Actor %ld (%s@%s) simcall %s", actor->get_pid(), actor->get_cname(), actor->get_host()->get_cname(),
318                SIMIX_simcall_name(actor->simcall_));
319     }
320   }
321 }
322
323 void EngineImpl::run()
324 {
325   if (MC_record_replay_is_active()) {
326     mc::replay(MC_record_path());
327     empty_trash();
328     return;
329   }
330
331   double time = 0;
332
333   do {
334     XBT_DEBUG("New Schedule Round; size(queue)=%zu", actors_to_run_.size());
335
336     if (cfg_breakpoint >= 0.0 && surf_get_clock() >= cfg_breakpoint) {
337       XBT_DEBUG("Breakpoint reached (%g)", cfg_breakpoint.get());
338       cfg_breakpoint = -1.0;
339 #ifdef SIGTRAP
340       std::raise(SIGTRAP);
341 #else
342       std::raise(SIGABRT);
343 #endif
344     }
345
346     execute_tasks();
347
348     while (not actors_to_run_.empty()) {
349       XBT_DEBUG("New Sub-Schedule Round; size(queue)=%zu", actors_to_run_.size());
350
351       /* Run all actors that are ready to run, possibly in parallel */
352       run_all_actors();
353
354       /* answer sequentially and in a fixed arbitrary order all the simcalls that were issued during that sub-round */
355
356       /* WARNING, the order *must* be fixed or you'll jeopardize the simulation reproducibility (see RR-7653) */
357
358       /* Here, the order is ok because:
359        *
360        *   Short proof: only maestro adds stuff to the actors_to_run array, so the execution order of user contexts do
361        *   not impact its order.
362        *
363        *   Long proof: actors remain sorted through an arbitrary (implicit, complex but fixed) order in all cases.
364        *
365        *   - if there is no kill during the simulation, actors remain sorted according by their PID.
366        *     Rationale: This can be proved inductively.
367        *        Assume that actors_to_run is sorted at a beginning of one round (it is at round 0: the deployment file
368        *        is parsed linearly).
369        *        Let's show that it is still so at the end of this round.
370        *        - if an actor is added when being created, that's from maestro. It can be either at startup
371        *          time (and then in PID order), or in response to a process_create simcall. Since simcalls are handled
372        *          in arbitrary order (inductive hypothesis), we are fine.
373        *        - If an actor is added because it's getting killed, its subsequent actions shouldn't matter
374        *        - If an actor gets added to actors_to_run because one of their blocking action constituting the meat
375        *          of a simcall terminates, we're still good. Proof:
376        *          - You are added from ActorImpl::simcall_answer() only. When this function is called depends on the
377        *            resource kind (network, cpu, disk, whatever), but the same arguments hold. Let's take communications
378        *            as an example.
379        *          - For communications, this function is called from SIMIX_comm_finish().
380        *            This function itself don't mess with the order since simcalls are handled in FIFO order.
381        *            The function is called:
382        *            - before the comm starts (invalid parameters, or resource already dead or whatever).
383        *              The order then trivial holds since maestro didn't interrupt its handling of the simcall yet
384        *            - because the communication failed or were canceled after startup. In this case, it's called from
385        *              the function we are in, by the chunk:
386        *                       set = model->states.failed_action_set;
387        *                       while ((synchro = extract(set)))
388        *                          SIMIX_simcall_post((smx_synchro_t) synchro->data);
389        *              This order is also fixed because it depends of the order in which the surf actions were
390        *              added to the system, and only maestro can add stuff this way, through simcalls.
391        *              We thus use the inductive hypothesis once again to conclude that the order in which synchros are
392        *              popped out of the set does not depend on the user code's execution order.
393        *            - because the communication terminated. In this case, synchros are served in the order given by
394        *                       set = model->states.done_action_set;
395        *                       while ((synchro = extract(set)))
396        *                          SIMIX_simcall_post((smx_synchro_t) synchro->data);
397        *              and the argument is very similar to the previous one.
398        *            So, in any case, the orders of calls to CommImpl::finish() do not depend on the order in which user
399        *            actors are executed.
400        *          So, in any cases, the orders of actors within actors_to_run do not depend on the order in which
401        *          user actors were executed previously.
402        *     So, if there is no killing in the simulation, the simulation reproducibility is not jeopardized.
403        *   - If there is some actor killings, the order is changed by this decision that comes from user-land
404        *     But this decision may not have been motivated by a situation that were different because the simulation is
405        *     not reproducible.
406        *     So, even the order change induced by the actor killing is perfectly reproducible.
407        *
408        *   So science works, bitches [http://xkcd.com/54/].
409        *
410        *   We could sort the actors_that_ran array completely so that we can describe the order in which simcalls are
411        *   handled (like "according to the PID of issuer"), but it's not mandatory (order is fixed already even if
412        *   unfriendly).
413        *   That would thus be a pure waste of time.
414        */
415
416       for (auto const& actor : actors_that_ran_) {
417         if (actor->simcall_.call_ != simix::Simcall::NONE) {
418           actor->simcall_handle(0);
419         }
420       }
421
422       execute_tasks();
423       do {
424         wake_all_waiting_actors();
425       } while (execute_tasks());
426
427       /* If only daemon actors remain, cancel their actions, mark them to die and reschedule them */
428       if (actor_list_.size() == daemons_.size())
429         for (auto const& dmon : daemons_) {
430           XBT_DEBUG("Kill %s", dmon->get_cname());
431           simix_global->get_maestro()->kill(dmon);
432         }
433     }
434
435     time = timer::Timer::next();
436     if (time > -1.0 || not actor_list_.empty()) {
437       XBT_DEBUG("Calling surf_solve");
438       time = surf_solve(time);
439       XBT_DEBUG("Moving time ahead : %g", time);
440     }
441
442     /* Notify all the hosts that have failed */
443     /* FIXME: iterate through the list of failed host and mark each of them */
444     /* as failed. On each host, signal all the running actors with host_fail */
445
446     // Execute timers and tasks until there isn't anything to be done:
447     bool again = false;
448     do {
449       again = timer::Timer::execute_all();
450       if (execute_tasks())
451         again = true;
452       wake_all_waiting_actors();
453     } while (again);
454
455     /* Clean actors to destroy */
456     empty_trash();
457
458     XBT_DEBUG("### time %f, #actors %zu, #to_run %zu", time, actor_list_.size(), actors_to_run_.size());
459
460     if (time < 0. && actors_to_run_.empty() && not actor_list_.empty()) {
461       if (actor_list_.size() <= daemons_.size()) {
462         XBT_CRITICAL("Oops! Daemon actors cannot do any blocking activity (communications, synchronization, etc) "
463                      "once the simulation is over. Please fix your on_exit() functions.");
464       } else {
465         XBT_CRITICAL("Oops! Deadlock or code not perfectly clean.");
466       }
467       display_all_actor_status();
468       simgrid::s4u::Engine::on_deadlock();
469       for (auto const& kv : actor_list_) {
470         XBT_DEBUG("Kill %s", kv.second->get_cname());
471         simix_global->get_maestro()->kill(kv.second);
472       }
473     }
474   } while (time > -1.0 || has_actors_to_run());
475
476   if (not actor_list_.empty())
477     THROW_IMPOSSIBLE;
478
479   simgrid::s4u::Engine::on_simulation_end();
480 }
481 } // namespace kernel
482 } // namespace simgrid