1 /* Copyright (c) 2016-2021. The SimGrid Team. All rights reserved. */
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. */
6 #include "src/kernel/EngineImpl.hpp"
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
23 XBT_LOG_NEW_DEFAULT_CATEGORY(ker_engine, "Logging specific to Engine (kernel)");
28 config::Flag<double> cfg_breakpoint{"debug/breakpoint",
29 "When non-negative, raise a SIGTRAP after given (simulated) time", -1.0};
30 EngineImpl::~EngineImpl()
33 while (not timer::kernel_timers().empty()) {
34 delete timer::kernel_timers().top().second;
35 timer::kernel_timers().pop();
38 /* Since hosts_ is a std::map, the hosts are destroyed in the lexicographic order, which ensures that the output is
41 while (not hosts_.empty())
42 hosts_.begin()->second->destroy();
44 /* Also delete the other data */
46 for (auto const& kv : netpoints_)
49 for (auto const& kv : links_)
53 /* Free the remaining data structures */
55 xbt_dynar_free(&actors_vector_);
56 xbt_dynar_free(&dead_actors_vector_);
60 void EngineImpl::load_deployment(const std::string& file) const
65 surf_parse_open(file);
70 void EngineImpl::register_function(const std::string& name, const actor::ActorCodeFactory& code)
72 registered_functions[name] = code;
74 void EngineImpl::register_default(const actor::ActorCodeFactory& code)
76 default_function = code;
79 void EngineImpl::add_model(std::shared_ptr<resource::Model> model, const std::vector<resource::Model*>& dependencies)
81 auto model_name = model->get_name();
82 xbt_assert(models_prio_.find(model_name) == models_prio_.end(),
83 "Model %s already exists, use model.set_name() to change its name", model_name.c_str());
85 for (const auto dep : dependencies) {
86 xbt_assert(models_prio_.find(dep->get_name()) != models_prio_.end(),
87 "Model %s doesn't exists. Impossible to use it as dependency.", dep->get_name().c_str());
89 models_.push_back(model.get());
90 models_prio_[model_name] = std::move(model);
93 /** Wake up all actors waiting for a Surf action to finish */
94 void EngineImpl::wake_all_waiting_actors() const
96 for (auto const& model : models_) {
97 XBT_DEBUG("Handling the failed actions (if any)");
98 while (auto* action = model->extract_failed_action()) {
99 XBT_DEBUG(" Handling Action %p", action);
100 if (action->get_activity() != nullptr)
101 activity::ActivityImplPtr(action->get_activity())->post();
103 XBT_DEBUG("Handling the terminated actions (if any)");
104 while (auto* action = model->extract_done_action()) {
105 XBT_DEBUG(" Handling Action %p", action);
106 if (action->get_activity() == nullptr)
107 XBT_DEBUG("probably vcpu's action %p, skip", action);
109 activity::ActivityImplPtr(action->get_activity())->post();
114 * @brief Executes the actors in actors_to_run.
116 * The actors in actors_to_run are run (in parallel if possible). On exit, actors_to_run is empty, and actors_that_ran
117 * contains the list of actors that just ran. The two lists are swapped so, be careful when using them before and after
118 * a call to this function.
120 void EngineImpl::run_all_actors()
122 simix_global->context_factory->run_all();
124 actors_to_run_.swap(actors_that_ran_);
125 actors_to_run_.clear();
128 actor::ActorImpl* EngineImpl::get_actor_by_pid(aid_t pid)
130 auto item = actor_list_.find(pid);
131 if (item != actor_list_.end())
135 for (auto& a : actors_to_destroy_)
136 if (a.get_pid() == pid)
138 return nullptr; // Not found, even in the trash
140 /** Execute all the tasks that are queued, e.g. `.then()` callbacks of futures. */
141 bool EngineImpl::execute_tasks()
143 xbt_assert(tasksTemp.empty());
149 // We don't want the callbacks to modify the vector we are iterating over:
150 tasks.swap(tasksTemp);
152 // Execute all the queued tasks:
153 for (auto& task : tasksTemp)
157 } while (not tasks.empty());
162 void EngineImpl::remove_daemon(actor::ActorImpl* actor)
164 auto it = daemons_.find(actor);
165 xbt_assert(it != daemons_.end(), "The dying daemon is not a daemon after all. Please report that bug.");
169 void EngineImpl::add_actor_to_run_list_no_check(actor::ActorImpl* actor)
171 XBT_DEBUG("Inserting [%p] %s(%s) in the to_run list", actor, actor->get_cname(), actor->get_host()->get_cname());
172 actors_to_run_.push_back(actor);
175 void EngineImpl::add_actor_to_run_list(actor::ActorImpl* actor)
177 if (std::find(begin(actors_to_run_), end(actors_to_run_), actor) != end(actors_to_run_)) {
178 XBT_DEBUG("Actor %s is already in the to_run list", actor->get_cname());
180 XBT_DEBUG("Inserting [%p] %s(%s) in the to_run list", actor, actor->get_cname(), actor->get_host()->get_cname());
181 actors_to_run_.push_back(actor);
184 void EngineImpl::empty_trash()
186 while (not actors_to_destroy_.empty()) {
187 actor::ActorImpl* actor = &actors_to_destroy_.front();
188 actors_to_destroy_.pop_front();
189 XBT_DEBUG("Getting rid of %s (refcount: %d)", actor->get_cname(), actor->get_refcount());
190 intrusive_ptr_release(actor);
193 xbt_dynar_reset(dead_actors_vector_);
197 void EngineImpl::display_all_actor_status() const
199 XBT_INFO("%zu actors are still running, waiting for something.", actor_list_.size());
200 /* List the actors and their state */
201 XBT_INFO("Legend of the following listing: \"Actor <pid> (<name>@<host>): <status>\"");
202 for (auto const& kv : actor_list_) {
203 actor::ActorImpl* actor = kv.second;
205 if (actor->waiting_synchro_) {
206 const char* synchro_description = "unknown";
208 if (boost::dynamic_pointer_cast<kernel::activity::ExecImpl>(actor->waiting_synchro_) != nullptr)
209 synchro_description = "execution";
211 if (boost::dynamic_pointer_cast<kernel::activity::CommImpl>(actor->waiting_synchro_) != nullptr)
212 synchro_description = "communication";
214 if (boost::dynamic_pointer_cast<kernel::activity::SleepImpl>(actor->waiting_synchro_) != nullptr)
215 synchro_description = "sleeping";
217 if (boost::dynamic_pointer_cast<kernel::activity::RawImpl>(actor->waiting_synchro_) != nullptr)
218 synchro_description = "synchronization";
220 if (boost::dynamic_pointer_cast<kernel::activity::IoImpl>(actor->waiting_synchro_) != nullptr)
221 synchro_description = "I/O";
223 XBT_INFO("Actor %ld (%s@%s): waiting for %s activity %#zx (%s) in state %d to finish", actor->get_pid(),
224 actor->get_cname(), actor->get_host()->get_cname(), synchro_description,
225 (xbt_log_no_loc ? (size_t)0xDEADBEEF : (size_t)actor->waiting_synchro_.get()),
226 actor->waiting_synchro_->get_cname(), (int)actor->waiting_synchro_->state_);
228 XBT_INFO("Actor %ld (%s@%s) simcall %s", actor->get_pid(), actor->get_cname(), actor->get_host()->get_cname(),
229 SIMIX_simcall_name(actor->simcall_));
234 void EngineImpl::run()
236 if (MC_record_replay_is_active()) {
237 mc::replay(MC_record_path());
244 XBT_DEBUG("New Schedule Round; size(queue)=%zu", actors_to_run_.size());
246 if (cfg_breakpoint >= 0.0 && surf_get_clock() >= cfg_breakpoint) {
247 XBT_DEBUG("Breakpoint reached (%g)", cfg_breakpoint.get());
248 cfg_breakpoint = -1.0;
258 while (not actors_to_run_.empty()) {
259 XBT_DEBUG("New Sub-Schedule Round; size(queue)=%zu", actors_to_run_.size());
261 /* Run all actors that are ready to run, possibly in parallel */
264 /* answer sequentially and in a fixed arbitrary order all the simcalls that were issued during that sub-round */
266 /* WARNING, the order *must* be fixed or you'll jeopardize the simulation reproducibility (see RR-7653) */
268 /* Here, the order is ok because:
270 * Short proof: only maestro adds stuff to the actors_to_run array, so the execution order of user contexts do
271 * not impact its order.
273 * Long proof: actors remain sorted through an arbitrary (implicit, complex but fixed) order in all cases.
275 * - if there is no kill during the simulation, actors remain sorted according by their PID.
276 * Rationale: This can be proved inductively.
277 * Assume that actors_to_run is sorted at a beginning of one round (it is at round 0: the deployment file
278 * is parsed linearly).
279 * Let's show that it is still so at the end of this round.
280 * - if an actor is added when being created, that's from maestro. It can be either at startup
281 * time (and then in PID order), or in response to a process_create simcall. Since simcalls are handled
282 * in arbitrary order (inductive hypothesis), we are fine.
283 * - If an actor is added because it's getting killed, its subsequent actions shouldn't matter
284 * - If an actor gets added to actors_to_run because one of their blocking action constituting the meat
285 * of a simcall terminates, we're still good. Proof:
286 * - You are added from ActorImpl::simcall_answer() only. When this function is called depends on the
287 * resource kind (network, cpu, disk, whatever), but the same arguments hold. Let's take communications
289 * - For communications, this function is called from SIMIX_comm_finish().
290 * This function itself don't mess with the order since simcalls are handled in FIFO order.
291 * The function is called:
292 * - before the comm starts (invalid parameters, or resource already dead or whatever).
293 * The order then trivial holds since maestro didn't interrupt its handling of the simcall yet
294 * - because the communication failed or were canceled after startup. In this case, it's called from
295 * the function we are in, by the chunk:
296 * set = model->states.failed_action_set;
297 * while ((synchro = extract(set)))
298 * SIMIX_simcall_post((smx_synchro_t) synchro->data);
299 * This order is also fixed because it depends of the order in which the surf actions were
300 * added to the system, and only maestro can add stuff this way, through simcalls.
301 * We thus use the inductive hypothesis once again to conclude that the order in which synchros are
302 * popped out of the set does not depend on the user code's execution order.
303 * - because the communication terminated. In this case, synchros are served in the order given by
304 * set = model->states.done_action_set;
305 * while ((synchro = extract(set)))
306 * SIMIX_simcall_post((smx_synchro_t) synchro->data);
307 * and the argument is very similar to the previous one.
308 * So, in any case, the orders of calls to CommImpl::finish() do not depend on the order in which user
309 * actors are executed.
310 * So, in any cases, the orders of actors within actors_to_run do not depend on the order in which
311 * user actors were executed previously.
312 * So, if there is no killing in the simulation, the simulation reproducibility is not jeopardized.
313 * - If there is some actor killings, the order is changed by this decision that comes from user-land
314 * But this decision may not have been motivated by a situation that were different because the simulation is
316 * So, even the order change induced by the actor killing is perfectly reproducible.
318 * So science works, bitches [http://xkcd.com/54/].
320 * We could sort the actors_that_ran array completely so that we can describe the order in which simcalls are
321 * handled (like "according to the PID of issuer"), but it's not mandatory (order is fixed already even if
323 * That would thus be a pure waste of time.
326 for (auto const& actor : actors_that_ran_) {
327 if (actor->simcall_.call_ != simix::Simcall::NONE) {
328 actor->simcall_handle(0);
334 wake_all_waiting_actors();
335 } while (execute_tasks());
337 /* If only daemon actors remain, cancel their actions, mark them to die and reschedule them */
338 if (actor_list_.size() == daemons_.size())
339 for (auto const& dmon : daemons_) {
340 XBT_DEBUG("Kill %s", dmon->get_cname());
341 simix_global->maestro_->kill(dmon);
345 time = timer::Timer::next();
346 if (time > -1.0 || not actor_list_.empty()) {
347 XBT_DEBUG("Calling surf_solve");
348 time = surf_solve(time);
349 XBT_DEBUG("Moving time ahead : %g", time);
352 /* Notify all the hosts that have failed */
353 /* FIXME: iterate through the list of failed host and mark each of them */
354 /* as failed. On each host, signal all the running actors with host_fail */
356 // Execute timers and tasks until there isn't anything to be done:
359 again = timer::Timer::execute_all();
362 wake_all_waiting_actors();
365 /* Clean actors to destroy */
368 XBT_DEBUG("### time %f, #actors %zu, #to_run %zu", time, actor_list_.size(), actors_to_run_.size());
370 if (time < 0. && actors_to_run_.empty() && not actor_list_.empty()) {
371 if (actor_list_.size() <= daemons_.size()) {
372 XBT_CRITICAL("Oops! Daemon actors cannot do any blocking activity (communications, synchronization, etc) "
373 "once the simulation is over. Please fix your on_exit() functions.");
375 XBT_CRITICAL("Oops! Deadlock or code not perfectly clean.");
377 display_all_actor_status();
378 simgrid::s4u::Engine::on_deadlock();
379 for (auto const& kv : actor_list_) {
380 XBT_DEBUG("Kill %s", kv.second->get_cname());
381 simix_global->maestro_->kill(kv.second);
384 } while (time > -1.0 || has_actors_to_run());
386 if (not actor_list_.empty())
389 simgrid::s4u::Engine::on_simulation_end();
391 } // namespace kernel
392 } // namespace simgrid