Logo AND Algorithmique Numérique Distribuée

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