Logo AND Algorithmique Numérique Distribuée

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