Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
migrate actors_to_run and actors_that_ran to EngineImpl
[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   actors_to_run_.clear();
45   actors_that_ran_.clear();
46 }
47
48 void EngineImpl::load_deployment(const std::string& file) const
49 {
50   sg_platf_exit();
51   sg_platf_init();
52
53   surf_parse_open(file);
54   surf_parse();
55   surf_parse_close();
56 }
57
58 void EngineImpl::register_function(const std::string& name, const actor::ActorCodeFactory& code)
59 {
60   registered_functions[name] = code;
61 }
62 void EngineImpl::register_default(const actor::ActorCodeFactory& code)
63 {
64   default_function = code;
65 }
66
67 void EngineImpl::add_model(std::shared_ptr<resource::Model> model, const std::vector<resource::Model*>& dependencies)
68 {
69   auto model_name = model->get_name();
70   xbt_assert(models_prio_.find(model_name) == models_prio_.end(),
71              "Model %s already exists, use model.set_name() to change its name", model_name.c_str());
72
73   for (const auto dep : dependencies) {
74     xbt_assert(models_prio_.find(dep->get_name()) != models_prio_.end(),
75                "Model %s doesn't exists. Impossible to use it as dependency.", dep->get_name().c_str());
76   }
77   models_.push_back(model.get());
78   models_prio_[model_name] = std::move(model);
79 }
80
81 /** Wake up all actors waiting for a Surf action to finish */
82 void EngineImpl::wake_all_waiting_actors() const
83 {
84   for (auto const& model : models_) {
85     XBT_DEBUG("Handling the failed actions (if any)");
86     while (auto* action = model->extract_failed_action()) {
87       XBT_DEBUG("   Handling Action %p", action);
88       if (action->get_activity() != nullptr)
89         activity::ActivityImplPtr(action->get_activity())->post();
90     }
91     XBT_DEBUG("Handling the terminated actions (if any)");
92     while (auto* action = model->extract_done_action()) {
93       XBT_DEBUG("   Handling Action %p", action);
94       if (action->get_activity() == nullptr)
95         XBT_DEBUG("probably vcpu's action %p, skip", action);
96       else
97         activity::ActivityImplPtr(action->get_activity())->post();
98     }
99   }
100 }
101 /**
102  * @brief Executes the actors in actors_to_run.
103  *
104  * The actors in actors_to_run are run (in parallel if possible). On exit, actors_to_run is empty, and actors_that_ran
105  * contains the list of actors that just ran.  The two lists are swapped so, be careful when using them before and after
106  * a call to this function.
107  */
108 void EngineImpl::run_all_actors()
109 {
110   simix_global->context_factory->run_all();
111
112   actors_to_run_.swap(actors_that_ran_);
113   actors_to_run_.clear();
114 }
115
116 /** Execute all the tasks that are queued, e.g. `.then()` callbacks of futures. */
117 bool EngineImpl::execute_tasks()
118 {
119   xbt_assert(tasksTemp.empty());
120
121   if (tasks.empty())
122     return false;
123
124   do {
125     // We don't want the callbacks to modify the vector we are iterating over:
126     tasks.swap(tasksTemp);
127
128     // Execute all the queued tasks:
129     for (auto& task : tasksTemp)
130       task();
131
132     tasksTemp.clear();
133   } while (not tasks.empty());
134
135   return true;
136 }
137
138 void EngineImpl::rm_daemon(actor::ActorImpl* actor)
139 {
140   auto it = daemons_.find(actor);
141   xbt_assert(it != daemons_.end(), "The dying daemon is not a daemon after all. Please report that bug.");
142   daemons_.erase(it);
143 }
144
145 void EngineImpl::add_actor_to_run_list_no_check(actor::ActorImpl* actor)
146 {
147   XBT_DEBUG("Inserting [%p] %s(%s) in the to_run list", actor, actor->get_cname(), actor->get_host()->get_cname());
148   actors_to_run_.push_back(actor);
149 }
150
151 void EngineImpl::add_actor_to_run_list(actor::ActorImpl* actor)
152 {
153   if (std::find(begin(actors_to_run_), end(actors_to_run_), actor) != end(actors_to_run_)) {
154     XBT_DEBUG("Actor %s is already in the to_run list", actor->get_cname());
155   } else {
156     XBT_DEBUG("Inserting [%p] %s(%s) in the to_run list", actor, actor->get_cname(), actor->get_host()->get_cname());
157     actors_to_run_.push_back(actor);
158   }
159 }
160
161 void EngineImpl::run()
162 {
163   if (MC_record_replay_is_active()) {
164     mc::replay(MC_record_path());
165     return;
166   }
167
168   double time = 0;
169
170   do {
171     XBT_DEBUG("New Schedule Round; size(queue)=%zu", actors_to_run_.size());
172
173     if (cfg_breakpoint >= 0.0 && surf_get_clock() >= cfg_breakpoint) {
174       XBT_DEBUG("Breakpoint reached (%g)", cfg_breakpoint.get());
175       cfg_breakpoint = -1.0;
176 #ifdef SIGTRAP
177       std::raise(SIGTRAP);
178 #else
179       std::raise(SIGABRT);
180 #endif
181     }
182
183     execute_tasks();
184
185     while (not actors_to_run_.empty()) {
186       XBT_DEBUG("New Sub-Schedule Round; size(queue)=%zu", actors_to_run_.size());
187
188       /* Run all actors that are ready to run, possibly in parallel */
189       run_all_actors();
190
191       /* answer sequentially and in a fixed arbitrary order all the simcalls that were issued during that sub-round */
192
193       /* WARNING, the order *must* be fixed or you'll jeopardize the simulation reproducibility (see RR-7653) */
194
195       /* Here, the order is ok because:
196        *
197        *   Short proof: only maestro adds stuff to the actors_to_run array, so the execution order of user contexts do
198        *   not impact its order.
199        *
200        *   Long proof: actors remain sorted through an arbitrary (implicit, complex but fixed) order in all cases.
201        *
202        *   - if there is no kill during the simulation, actors remain sorted according by their PID.
203        *     Rationale: This can be proved inductively.
204        *        Assume that actors_to_run is sorted at a beginning of one round (it is at round 0: the deployment file
205        *        is parsed linearly).
206        *        Let's show that it is still so at the end of this round.
207        *        - if an actor is added when being created, that's from maestro. It can be either at startup
208        *          time (and then in PID order), or in response to a process_create simcall. Since simcalls are handled
209        *          in arbitrary order (inductive hypothesis), we are fine.
210        *        - If an actor is added because it's getting killed, its subsequent actions shouldn't matter
211        *        - If an actor gets added to actors_to_run because one of their blocking action constituting the meat
212        *          of a simcall terminates, we're still good. Proof:
213        *          - You are added from ActorImpl::simcall_answer() only. When this function is called depends on the
214        *            resource kind (network, cpu, disk, whatever), but the same arguments hold. Let's take communications
215        *            as an example.
216        *          - For communications, this function is called from SIMIX_comm_finish().
217        *            This function itself don't mess with the order since simcalls are handled in FIFO order.
218        *            The function is called:
219        *            - before the comm starts (invalid parameters, or resource already dead or whatever).
220        *              The order then trivial holds since maestro didn't interrupt its handling of the simcall yet
221        *            - because the communication failed or were canceled after startup. In this case, it's called from
222        *              the function we are in, by the chunk:
223        *                       set = model->states.failed_action_set;
224        *                       while ((synchro = extract(set)))
225        *                          SIMIX_simcall_post((smx_synchro_t) synchro->data);
226        *              This order is also fixed because it depends of the order in which the surf actions were
227        *              added to the system, and only maestro can add stuff this way, through simcalls.
228        *              We thus use the inductive hypothesis once again to conclude that the order in which synchros are
229        *              popped out of the set does not depend on the user code's execution order.
230        *            - because the communication terminated. In this case, synchros are served in the order given by
231        *                       set = model->states.done_action_set;
232        *                       while ((synchro = extract(set)))
233        *                          SIMIX_simcall_post((smx_synchro_t) synchro->data);
234        *              and the argument is very similar to the previous one.
235        *            So, in any case, the orders of calls to CommImpl::finish() do not depend on the order in which user
236        *            actors are executed.
237        *          So, in any cases, the orders of actors within actors_to_run do not depend on the order in which
238        *          user actors were executed previously.
239        *     So, if there is no killing in the simulation, the simulation reproducibility is not jeopardized.
240        *   - If there is some actor killings, the order is changed by this decision that comes from user-land
241        *     But this decision may not have been motivated by a situation that were different because the simulation is
242        *     not reproducible.
243        *     So, even the order change induced by the actor killing is perfectly reproducible.
244        *
245        *   So science works, bitches [http://xkcd.com/54/].
246        *
247        *   We could sort the actors_that_ran array completely so that we can describe the order in which simcalls are
248        *   handled (like "according to the PID of issuer"), but it's not mandatory (order is fixed already even if
249        *   unfriendly).
250        *   That would thus be a pure waste of time.
251        */
252
253       for (auto const& actor : actors_that_ran_) {
254         if (actor->simcall_.call_ != simix::Simcall::NONE) {
255           actor->simcall_handle(0);
256         }
257       }
258
259       execute_tasks();
260       do {
261         wake_all_waiting_actors();
262       } while (execute_tasks());
263
264       /* If only daemon actors remain, cancel their actions, mark them to die and reschedule them */
265       if (simix_global->process_list.size() == daemons_.size())
266         for (auto const& dmon : daemons_) {
267           XBT_DEBUG("Kill %s", dmon->get_cname());
268           simix_global->maestro_->kill(dmon);
269         }
270     }
271
272     time = timer::Timer::next();
273     if (time > -1.0 || not simix_global->process_list.empty()) {
274       XBT_DEBUG("Calling surf_solve");
275       time = surf_solve(time);
276       XBT_DEBUG("Moving time ahead : %g", time);
277     }
278
279     /* Notify all the hosts that have failed */
280     /* FIXME: iterate through the list of failed host and mark each of them */
281     /* as failed. On each host, signal all the running actors with host_fail */
282
283     // Execute timers and tasks until there isn't anything to be done:
284     bool again = false;
285     do {
286       again = timer::Timer::execute_all();
287       if (execute_tasks())
288         again = true;
289       wake_all_waiting_actors();
290     } while (again);
291
292     /* Clean actors to destroy */
293     simix_global->empty_trash();
294
295     XBT_DEBUG("### time %f, #actors %zu, #to_run %zu", time, simix_global->process_list.size(), actors_to_run_.size());
296
297     if (time < 0. && actors_to_run_.empty() && not simix_global->process_list.empty()) {
298       if (simix_global->process_list.size() <= daemons_.size()) {
299         XBT_CRITICAL("Oops! Daemon actors cannot do any blocking activity (communications, synchronization, etc) "
300                      "once the simulation is over. Please fix your on_exit() functions.");
301       } else {
302         XBT_CRITICAL("Oops! Deadlock or code not perfectly clean.");
303       }
304       simix_global->display_all_actor_status();
305       simgrid::s4u::Engine::on_deadlock();
306       for (auto const& kv : simix_global->process_list) {
307         XBT_DEBUG("Kill %s", kv.second->get_cname());
308         simix_global->maestro_->kill(kv.second);
309       }
310     }
311   } while (time > -1.0 || has_actors_to_run());
312
313   if (not simix_global->process_list.empty())
314     THROW_IMPOSSIBLE;
315
316   simgrid::s4u::Engine::on_simulation_end();
317 }
318 } // namespace kernel
319 } // namespace simgrid