1 /* Copyright (c) 2007-2023. 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/mc/mc_replay.hpp"
7 #include <simgrid/Exception.hpp>
8 #include <simgrid/s4u/Actor.hpp>
9 #include <simgrid/s4u/Host.hpp>
11 #include "src/internal_config.h"
12 #include "src/kernel/EngineImpl.hpp"
14 #include "src/smpi/include/private.hpp"
16 #include "src/kernel/resource/HostImpl.hpp"
18 #include <boost/core/demangle.hpp>
22 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(ker_actor, kernel, "Logging specific to Actor's kernel side");
24 namespace simgrid::kernel::actor {
26 /*------------------------- [ ActorIDTrait ] -------------------------*/
27 unsigned long ActorIDTrait::maxpid_ = 0;
29 ActorIDTrait::ActorIDTrait(const std::string& name, aid_t ppid) : name_(name), pid_(maxpid_++), ppid_(ppid) {}
31 ActorImpl* ActorImpl::self()
33 const context::Context* self_context = context::Context::self();
35 return (self_context != nullptr) ? self_context->get_actor() : nullptr;
38 ActorImpl::ActorImpl(const std::string& name, s4u::Host* host, aid_t ppid)
39 : ActorIDTrait(name, ppid), host_(host), piface_(this)
41 simcall_.issuer_ = this;
42 stacksize_ = context::Context::stack_size;
45 ActorImpl::~ActorImpl()
47 if (EngineImpl::has_instance() && not EngineImpl::get_instance()->is_maestro(this))
48 s4u::Actor::on_destruction(*get_ciface());
51 /* Become an actor in the simulation
53 * Currently this can only be called by the main thread (once) and only work with some thread factories
54 * (currently ThreadContextFactory).
56 * In the future, it might be extended in order to attach other threads created by a third party library.
59 ActorImplPtr ActorImpl::attach(const std::string& name, void* data, s4u::Host* host)
61 // This is mostly a copy/paste from create(), it'd be nice to share some code between those two functions.
62 auto* engine = EngineImpl::get_instance();
63 XBT_DEBUG("Attach actor %s on host '%s'", name.c_str(), host->get_cname());
65 if (not host->is_on()) {
66 XBT_WARN("Cannot attach actor '%s' on failed host '%s'", name.c_str(), host->get_cname());
67 throw HostFailureException(XBT_THROW_POINT, "Cannot attach actor on failed host.");
70 auto* actor = new ActorImpl(name, host, /*ppid*/ -1);
72 actor->piface_.set_data(data);
73 actor->code_ = nullptr;
75 XBT_VERB("Create context %s", actor->get_cname());
76 actor->context_.reset(engine->get_context_factory()->attach(actor));
78 /* Add the actor to it's host actor list */
79 host->get_impl()->add_actor(actor);
81 /* Now insert it in the global actor list and in the actors to run list */
82 engine->add_actor(actor->get_pid(), actor);
83 engine->add_actor_to_run_list_no_check(actor);
84 intrusive_ptr_add_ref(actor);
86 auto* context = dynamic_cast<context::AttachContext*>(actor->context_.get());
87 xbt_assert(nullptr != context, "Not a suitable context");
88 context->attach_start();
90 /* The on_creation() signal must be delayed until there, where the pid and everything is set */
91 s4u::Actor::on_creation(*actor->get_ciface());
93 return ActorImplPtr(actor);
95 /** @brief Detach an actor attached with `attach()`
97 * This is called when the current actor has finished its job.
98 * Used in the main thread, it waits for the simulation to finish before returning. When it returns, the other
99 * simulated actors and the maestro are destroyed.
101 void ActorImpl::detach()
103 auto* context = dynamic_cast<context::AttachContext*>(context::Context::self());
104 xbt_assert(context != nullptr, "Not a suitable context");
106 context->get_actor()->cleanup_from_self();
107 context->attach_stop();
110 /** Whether this actor is actually maestro */
111 bool ActorImpl::is_maestro() const
113 return context_->is_maestro();
116 void ActorImpl::cleanup_from_kernel()
118 xbt_assert(s4u::Actor::is_maestro(), "Cleanup_from_kernel must be called in maestro context");
120 auto* engine = EngineImpl::get_instance();
121 if (engine->get_actor_by_pid(get_pid()) == nullptr)
122 return; // Already cleaned
124 engine->remove_actor(get_pid());
125 if (host_ && host_actor_list_hook.is_linked())
126 host_->get_impl()->remove_actor(this);
127 if (not kernel_destroy_list_hook.is_linked())
128 engine->add_actor_to_destroy_list(*this);
131 s4u::Actor::on_termination(*get_ciface());
133 while (not mailboxes_.empty())
134 mailboxes_.back()->set_receiver(nullptr);
137 /* Do all the cleanups from the actor context. Warning, the simcall mechanism was not reignited so doing simcalls in
138 * this context is dangerous */
139 void ActorImpl::cleanup_from_self()
141 xbt_assert(not ActorImpl::is_maestro(), "Cleanup_from_self called from maestro on '%s'", get_cname());
145 // Execute the termination callbacks
146 bool failed = wannadie();
147 for (auto exit_fun = on_exit->crbegin(); exit_fun != on_exit->crend(); ++exit_fun)
152 /* cancel non-blocking activities */
153 for (auto activity : activities_)
157 XBT_DEBUG("%s@%s(%ld) should not run anymore", get_cname(), get_host()->get_cname(), get_pid());
159 /* Unregister associated timers if any */
160 if (kill_timer_ != nullptr) {
161 kill_timer_->remove();
162 kill_timer_ = nullptr;
164 if (simcall_.timeout_cb_) {
165 simcall_.timeout_cb_->remove();
166 simcall_.timeout_cb_ = nullptr;
169 /* maybe the actor was killed during a simcall, reset its observer */
170 simcall_.observer_ = nullptr;
175 void ActorImpl::exit()
179 exception_ = nullptr;
181 if (waiting_synchro_ != nullptr) {
182 /* Take an extra reference on the activity object that may be unref by Comm::finish() or friends */
183 activity::ActivityImplPtr activity = waiting_synchro_;
185 activity->set_state(activity::State::FAILED);
188 activities_.erase(waiting_synchro_);
189 waiting_synchro_ = nullptr;
191 for (auto const& activity : activities_)
195 // Forcefully kill the actor if its host is turned off. Not a HostFailureException because you should not survive that
196 this->throw_exception(std::make_exception_ptr(ForcefulKillException(host_->is_on() ? "exited" : "host failed")));
199 void ActorImpl::kill(ActorImpl* actor) const
201 xbt_assert(not actor->is_maestro(), "Killing maestro is a rather bad idea.");
202 if (actor->wannadie()) {
203 XBT_DEBUG("Ignoring request to kill actor %s@%s that is already dead", actor->get_cname(),
204 actor->host_->get_cname());
208 XBT_DEBUG("Actor '%s'@%s is killing actor '%s'@%s", get_cname(), host_ ? host_->get_cname() : "", actor->get_cname(),
209 actor->host_ ? actor->host_->get_cname() : "");
214 XBT_DEBUG("Go on, this is a suicide,");
216 EngineImpl::get_instance()->add_actor_to_run_list(actor);
219 void ActorImpl::kill_all() const
221 for (auto const& [_, actor] : EngineImpl::get_instance()->get_actor_list())
226 void ActorImpl::set_kill_time(double kill_time)
228 if (kill_time <= s4u::Engine::get_clock())
230 XBT_DEBUG("Set kill time %f for actor %s@%s", kill_time, get_cname(), host_->get_cname());
231 kill_timer_ = timer::Timer::set(kill_time, [this] {
233 kill_timer_ = nullptr;
234 EngineImpl::get_instance()->add_actor_to_run_list(this);
238 double ActorImpl::get_kill_time() const
240 return kill_timer_ ? kill_timer_->get_date() : 0.0;
243 void ActorImpl::yield()
245 XBT_DEBUG("Yield actor '%s'", get_cname());
247 /* Go into sleep and return control to maestro */
249 /* Ok, maestro returned control to us */
250 XBT_DEBUG("Control returned to me: '%s'", get_cname());
253 XBT_DEBUG("Actor %s@%s is dead", get_cname(), host_->get_cname());
259 XBT_DEBUG("Hey! I'm suspended.");
260 xbt_assert(exception_ == nullptr, "Gasp! This exception may be lost by subsequent calls.");
261 yield(); // Yield back to maestro without proceeding with my execution. I'll get rescheduled by resume()
264 if (exception_ != nullptr) {
265 XBT_DEBUG("Wait, maestro left me an exception");
266 std::exception_ptr exception = std::move(exception_);
267 exception_ = nullptr;
269 std::rethrow_exception(std::move(exception));
270 } catch (const simgrid::Exception& e) {
271 e.rethrow_nested(XBT_THROW_POINT, boost::core::demangle(typeid(e).name()) + " raised in kernel mode.");
276 smpi_switch_data_segment(get_iface());
278 if (simgrid_mc_replay_show_backtraces)
279 xbt_backtrace_display_current();
282 /** This actor will be terminated automatically when the last non-daemon actor finishes */
283 void ActorImpl::daemonize()
287 EngineImpl::get_instance()->add_daemon(this);
291 void ActorImpl::undaemonize()
295 EngineImpl::get_instance()->remove_daemon(this);
299 s4u::Actor* ActorImpl::restart()
301 xbt_assert(not this->is_maestro(), "Restarting maestro is not supported");
303 XBT_DEBUG("Restarting actor %s on %s", get_cname(), host_->get_cname());
305 // retrieve the arguments of the old actor
306 ProcessArg args(host_, this);
308 // kill the old actor
309 context::Context::self()->get_actor()->kill(this);
311 // start the new actor
312 return create(&args)->get_ciface();
315 void ActorImpl::suspend()
318 XBT_DEBUG("Actor '%s' is already suspended", get_cname());
324 /* Suspend the activities associated with this actor. */
325 for (auto const& activity : activities_)
329 void ActorImpl::resume()
331 XBT_IN("actor = %p", this);
334 XBT_VERB("Ignoring request to resume an actor that is currently dying.");
342 /* resume the activities that were blocked when suspending the actor. */
343 for (auto const& activity : activities_)
345 if (not waiting_synchro_) // Reschedule the actor if it was forcefully unscheduled in yield()
346 EngineImpl::get_instance()->add_actor_to_run_list_no_check(this);
351 activity::ActivityImplPtr ActorImpl::join(const ActorImpl* actor, double timeout)
353 activity::ActivityImplPtr sleep_activity = this->sleep(timeout);
354 if (actor->wannadie() || actor->to_be_freed()) {
355 if (sleep_activity->model_action_)
356 sleep_activity->model_action_->finish(resource::Action::State::FINISHED);
358 actor->on_exit->emplace_back([sleep_activity](bool) {
359 if (sleep_activity->model_action_)
360 sleep_activity->model_action_->finish(resource::Action::State::FINISHED);
363 return sleep_activity;
366 activity::ActivityImplPtr ActorImpl::sleep(double duration)
368 if (not host_->is_on())
369 throw_exception(std::make_exception_ptr(
370 HostFailureException(XBT_THROW_POINT, "Host " + host_->get_name() + " failed, you cannot sleep there.")));
372 auto sleep_activity = new activity::SleepImpl();
373 sleep_activity->set_name("sleep").set_host(host_).set_duration(duration).start();
374 return activity::SleepImplPtr(sleep_activity);
377 void ActorImpl::throw_exception(std::exception_ptr e)
384 /* cancel the blocking synchro if any */
385 if (waiting_synchro_) {
386 waiting_synchro_->cancel();
387 activities_.erase(waiting_synchro_);
388 waiting_synchro_ = nullptr;
392 void ActorImpl::simcall_answer()
394 auto* engine = EngineImpl::get_instance();
395 if (not this->is_maestro()) {
396 XBT_DEBUG("Answer simcall %s issued by %s (%p)", simcall_.get_cname(), get_cname(), this);
397 xbt_assert(simcall_.call_ != Simcall::Type::NONE);
398 simcall_.call_ = Simcall::Type::NONE;
399 const auto& actors_to_run = engine->get_actors_to_run();
400 xbt_assert(not XBT_LOG_ISENABLED(ker_actor, xbt_log_priority_debug) ||
401 std::find(begin(actors_to_run), end(actors_to_run), this) == end(actors_to_run),
402 "Actor %p should not exist in actors_to_run!", this);
403 engine->add_actor_to_run_list_no_check(this);
407 void ActorImpl::set_host(s4u::Host* dest)
409 host_->get_impl()->remove_actor(this);
411 dest->get_impl()->add_actor(this);
414 ActorImplPtr ActorImpl::init(const std::string& name, s4u::Host* host) const
416 auto* actor = new ActorImpl(name, host, get_pid());
418 intrusive_ptr_add_ref(actor);
419 /* The on_creation() signal must be delayed until there, where the pid and everything is set */
420 s4u::Actor::on_creation(*actor->get_ciface());
422 return ActorImplPtr(actor);
425 ActorImpl* ActorImpl::start(const ActorCode& code)
427 xbt_assert(code && host_ != nullptr, "Invalid parameters");
428 auto* engine = EngineImpl::get_instance();
430 if (not host_->is_on()) {
431 XBT_WARN("Cannot launch actor '%s' on failed host '%s'", get_cname(), host_->get_cname());
432 intrusive_ptr_release(this);
433 throw HostFailureException(XBT_THROW_POINT, "Cannot start actor on failed host.");
437 XBT_VERB("Create context %s", get_cname());
438 context_.reset(engine->get_context_factory()->create_context(ActorCode(code), this));
440 XBT_DEBUG("Start context '%s'", get_cname());
442 /* Add the actor to its host's actor list */
443 host_->get_impl()->add_actor(this);
444 engine->add_actor(get_pid(), this);
446 /* Now insert it in the global actor list and in the actor to run list */
447 engine->add_actor_to_run_list_no_check(this);
452 ActorImplPtr ActorImpl::create(const std::string& name, const ActorCode& code, void* data, s4u::Host* host,
453 const ActorImpl* parent_actor)
455 XBT_DEBUG("Start actor %s@'%s'", name.c_str(), host->get_cname());
458 if (parent_actor != nullptr)
459 actor = parent_actor->init(name, host);
461 actor = self()->init(name, host);
463 actor->piface_.set_data(data); /* actor data */
469 ActorImplPtr ActorImpl::create(ProcessArg* args)
471 ActorImplPtr actor = ActorImpl::create(args->name, args->code, nullptr, args->host, nullptr);
472 actor->restart_count_ = args->restart_count_;
473 actor->set_properties(args->properties);
475 *actor->on_exit = *args->on_exit;
476 if (args->kill_time >= 0)
477 actor->set_kill_time(args->kill_time);
478 if (args->auto_restart)
479 actor->set_auto_restart(args->auto_restart);
484 void ActorImpl::set_wannadie(bool value)
486 XBT_DEBUG("Actor %s gonna die.", get_cname());
490 void create_maestro(const std::function<void()>& code)
492 auto* engine = EngineImpl::get_instance();
493 /* Create maestro actor and initialize it */
494 auto* maestro = new ActorImpl(/*name*/ "", /*host*/ nullptr, /*ppid*/ -1);
497 maestro->context_.reset(engine->get_context_factory()->create_context(ActorCode(), maestro));
499 maestro->context_.reset(engine->get_context_factory()->create_maestro(ActorCode(code), maestro));
502 maestro->simcall_.issuer_ = maestro;
503 engine->set_maestro(maestro);
506 /** (in kernel mode) unpack the simcall and activate the handler */
507 void ActorImpl::simcall_handle(int times_considered)
509 XBT_DEBUG("Handling simcall %p: %s(%ld) %s", &simcall_, simcall_.issuer_->get_cname(), simcall_.issuer_->get_pid(),
510 (simcall_.observer_ != nullptr ? simcall_.observer_->to_string().c_str() : simcall_.get_cname()));
511 if (simcall_.observer_ != nullptr)
512 simcall_.observer_->prepare(times_considered);
516 xbt_assert(simcall_.call_ != Simcall::Type::NONE, "Asked to do the noop syscall on %s@%s", get_cname(),
517 get_host()->get_cname());
520 if (simcall_.call_ == Simcall::Type::RUN_ANSWERED)
524 } // namespace simgrid::kernel::actor