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());
49 get_ciface()->on_this_destruction(*get_ciface());
53 /* Become an actor in the simulation
55 * Currently this can only be called by the main thread (once) and only work with some thread factories
56 * (currently ThreadContextFactory).
58 * In the future, it might be extended in order to attach other threads created by a third party library.
61 ActorImplPtr ActorImpl::attach(const std::string& name, void* data, s4u::Host* host)
63 // This is mostly a copy/paste from create(), it'd be nice to share some code between those two functions.
64 auto* engine = EngineImpl::get_instance();
65 XBT_DEBUG("Attach actor %s on host '%s'", name.c_str(), host->get_cname());
67 if (not host->is_on()) {
68 XBT_WARN("Cannot attach actor '%s' on failed host '%s'", name.c_str(), host->get_cname());
69 throw HostFailureException(XBT_THROW_POINT, "Cannot attach actor on failed host.");
72 auto* actor = new ActorImpl(name, host, /*ppid*/ -1);
74 actor->piface_.set_data(data);
75 actor->code_ = nullptr;
77 XBT_VERB("Create context %s", actor->get_cname());
78 actor->context_.reset(engine->get_context_factory()->attach(actor));
80 /* Add the actor to it's host actor list */
81 host->get_impl()->add_actor(actor);
83 /* Now insert it in the global actor list and in the actors to run list */
84 engine->add_actor(actor->get_pid(), actor);
85 engine->add_actor_to_run_list_no_check(actor);
86 intrusive_ptr_add_ref(actor);
88 auto* context = dynamic_cast<context::AttachContext*>(actor->context_.get());
89 xbt_assert(nullptr != context, "Not a suitable context");
90 context->attach_start();
92 /* The on_creation() signal must be delayed until there, where the pid and everything is set */
93 s4u::Actor::on_creation(*actor->get_ciface());
95 return ActorImplPtr(actor);
97 /** @brief Detach an actor attached with `attach()`
99 * This is called when the current actor has finished its job.
100 * Used in the main thread, it waits for the simulation to finish before returning. When it returns, the other
101 * simulated actors and the maestro are destroyed.
103 void ActorImpl::detach()
105 auto* context = dynamic_cast<context::AttachContext*>(context::Context::self());
106 xbt_assert(context != nullptr, "Not a suitable context");
108 context->get_actor()->cleanup_from_self();
109 context->attach_stop();
112 /** Whether this actor is actually maestro */
113 bool ActorImpl::is_maestro() const
115 return context_->is_maestro();
118 void ActorImpl::cleanup_from_kernel()
120 xbt_assert(s4u::Actor::is_maestro(), "Cleanup_from_kernel must be called in maestro context");
122 auto* engine = EngineImpl::get_instance();
123 if (engine->get_actor_by_pid(get_pid()) == nullptr)
124 return; // Already cleaned
126 engine->remove_actor(get_pid());
127 if (host_ && host_actor_list_hook.is_linked())
128 host_->get_impl()->remove_actor(this);
129 if (not kernel_destroy_list_hook.is_linked())
130 engine->add_actor_to_destroy_list(*this);
133 s4u::Actor::on_termination(*get_ciface());
134 get_ciface()->on_this_termination(*get_ciface());
136 while (not mailboxes_.empty())
137 mailboxes_.back()->set_receiver(nullptr);
140 /* Do all the cleanups from the actor context. Warning, the simcall mechanism was not reignited so doing simcalls in
141 * this context is dangerous */
142 void ActorImpl::cleanup_from_self()
144 xbt_assert(not ActorImpl::is_maestro(), "Cleanup_from_self called from maestro on '%s'", get_cname());
148 // Execute the termination callbacks
149 bool failed = wannadie();
150 for (auto exit_fun = on_exit->crbegin(); exit_fun != on_exit->crend(); ++exit_fun)
155 /* cancel non-blocking activities */
156 for (auto activity : activities_)
160 XBT_DEBUG("%s@%s(%ld) should not run anymore", get_cname(), get_host()->get_cname(), get_pid());
162 /* Unregister associated timers if any */
163 if (kill_timer_ != nullptr) {
164 kill_timer_->remove();
165 kill_timer_ = nullptr;
167 if (simcall_.timeout_cb_) {
168 simcall_.timeout_cb_->remove();
169 simcall_.timeout_cb_ = nullptr;
172 /* maybe the actor was killed during a simcall, reset its observer */
173 simcall_.observer_ = nullptr;
178 void ActorImpl::exit()
182 exception_ = nullptr;
184 if (waiting_synchro_ != nullptr) {
185 /* Take an extra reference on the activity object that may be unref by Comm::finish() or friends */
186 activity::ActivityImplPtr activity = waiting_synchro_;
188 activity->set_state(activity::State::FAILED);
191 activities_.erase(waiting_synchro_);
192 waiting_synchro_ = nullptr;
194 for (auto const& activity : activities_)
198 // Forcefully kill the actor if its host is turned off. Not a HostFailureException because you should not survive that
199 this->throw_exception(std::make_exception_ptr(ForcefulKillException(host_->is_on() ? "exited" : "host failed")));
202 void ActorImpl::kill(ActorImpl* actor) const
204 xbt_assert(not actor->is_maestro(), "Killing maestro is a rather bad idea.");
205 if (actor->wannadie()) {
206 XBT_DEBUG("Ignoring request to kill actor %s@%s that is already dead", actor->get_cname(),
207 actor->host_->get_cname());
211 XBT_DEBUG("Actor '%s'@%s is killing actor '%s'@%s", get_cname(), host_ ? host_->get_cname() : "", actor->get_cname(),
212 actor->host_ ? actor->host_->get_cname() : "");
217 XBT_DEBUG("Go on, this is a suicide,");
219 EngineImpl::get_instance()->add_actor_to_run_list(actor);
222 void ActorImpl::kill_all() const
224 for (auto const& [_, actor] : EngineImpl::get_instance()->get_actor_list())
229 void ActorImpl::set_kill_time(double kill_time)
231 if (kill_time <= s4u::Engine::get_clock())
233 XBT_DEBUG("Set kill time %f for actor %s@%s", kill_time, get_cname(), host_->get_cname());
234 kill_timer_ = timer::Timer::set(kill_time, [this] {
236 kill_timer_ = nullptr;
237 EngineImpl::get_instance()->add_actor_to_run_list(this);
241 double ActorImpl::get_kill_time() const
243 return kill_timer_ ? kill_timer_->get_date() : 0.0;
246 void ActorImpl::yield()
248 XBT_DEBUG("Yield actor '%s'", get_cname());
250 /* Go into sleep and return control to maestro */
252 /* Ok, maestro returned control to us */
253 XBT_DEBUG("Control returned to me: '%s'", get_cname());
256 XBT_DEBUG("Actor %s@%s is dead", get_cname(), host_->get_cname());
262 XBT_DEBUG("Hey! I'm suspended.");
263 xbt_assert(exception_ == nullptr, "Gasp! This exception may be lost by subsequent calls.");
264 yield(); // Yield back to maestro without proceeding with my execution. I'll get rescheduled by resume()
267 if (exception_ != nullptr) {
268 XBT_DEBUG("Wait, maestro left me an exception");
269 std::exception_ptr exception = std::move(exception_);
270 exception_ = nullptr;
272 std::rethrow_exception(std::move(exception));
273 } catch (const simgrid::Exception& e) {
274 e.rethrow_nested(XBT_THROW_POINT, boost::core::demangle(typeid(e).name()) + " raised in kernel mode.");
279 smpi_switch_data_segment(get_iface());
281 if (simgrid_mc_replay_show_backtraces)
282 xbt_backtrace_display_current();
285 /** This actor will be terminated automatically when the last non-daemon actor finishes */
286 void ActorImpl::daemonize()
290 EngineImpl::get_instance()->add_daemon(this);
294 void ActorImpl::undaemonize()
298 EngineImpl::get_instance()->remove_daemon(this);
302 s4u::Actor* ActorImpl::restart()
304 xbt_assert(not this->is_maestro(), "Restarting maestro is not supported");
306 XBT_DEBUG("Restarting actor %s on %s", get_cname(), host_->get_cname());
308 // retrieve the arguments of the old actor
309 ProcessArg args(host_, this);
311 // kill the old actor
312 context::Context::self()->get_actor()->kill(this);
314 // start the new actor
315 return create(&args)->get_ciface();
318 void ActorImpl::suspend()
321 XBT_DEBUG("Actor '%s' is already suspended", get_cname());
327 /* Suspend the activities associated with this actor. */
328 for (auto const& activity : activities_)
332 void ActorImpl::resume()
334 XBT_IN("actor = %p", this);
337 XBT_VERB("Ignoring request to resume an actor that is currently dying.");
345 /* resume the activities that were blocked when suspending the actor. */
346 for (auto const& activity : activities_)
348 if (not waiting_synchro_) // Reschedule the actor if it was forcefully unscheduled in yield()
349 EngineImpl::get_instance()->add_actor_to_run_list_no_check(this);
354 activity::ActivityImplPtr ActorImpl::join(const ActorImpl* actor, double timeout)
356 activity::ActivityImplPtr sleep_activity = this->sleep(timeout);
357 if (actor->wannadie() || actor->to_be_freed()) {
358 if (sleep_activity->model_action_)
359 sleep_activity->model_action_->finish(resource::Action::State::FINISHED);
361 actor->on_exit->emplace_back([sleep_activity](bool) {
362 if (sleep_activity->model_action_)
363 sleep_activity->model_action_->finish(resource::Action::State::FINISHED);
366 return sleep_activity;
369 activity::ActivityImplPtr ActorImpl::sleep(double duration)
371 if (not host_->is_on())
372 throw_exception(std::make_exception_ptr(
373 HostFailureException(XBT_THROW_POINT, "Host " + host_->get_name() + " failed, you cannot sleep there.")));
375 auto sleep_activity = new activity::SleepImpl();
376 sleep_activity->set_name("sleep").set_host(host_).set_duration(duration).start();
377 return activity::SleepImplPtr(sleep_activity);
380 void ActorImpl::throw_exception(std::exception_ptr e)
387 /* cancel the blocking synchro if any */
388 if (waiting_synchro_) {
389 waiting_synchro_->cancel();
390 activities_.erase(waiting_synchro_);
391 waiting_synchro_ = nullptr;
395 void ActorImpl::simcall_answer()
397 auto* engine = EngineImpl::get_instance();
398 if (not this->is_maestro()) {
399 XBT_DEBUG("Answer simcall %s issued by %s (%p)", simcall_.get_cname(), get_cname(), this);
400 xbt_assert(simcall_.call_ != Simcall::Type::NONE);
401 simcall_.call_ = Simcall::Type::NONE;
402 const auto& actors_to_run = engine->get_actors_to_run();
403 xbt_assert(not XBT_LOG_ISENABLED(ker_actor, xbt_log_priority_debug) ||
404 std::find(begin(actors_to_run), end(actors_to_run), this) == end(actors_to_run),
405 "Actor %p should not exist in actors_to_run!", this);
406 engine->add_actor_to_run_list_no_check(this);
410 void ActorImpl::set_host(s4u::Host* dest)
412 host_->get_impl()->remove_actor(this);
414 dest->get_impl()->add_actor(this);
417 ActorImplPtr ActorImpl::init(const std::string& name, s4u::Host* host) const
419 auto* actor = new ActorImpl(name, host, get_pid());
421 intrusive_ptr_add_ref(actor);
422 /* The on_creation() signal must be delayed until there, where the pid and everything is set */
423 s4u::Actor::on_creation(*actor->get_ciface());
425 return ActorImplPtr(actor);
428 ActorImpl* ActorImpl::start(const ActorCode& code)
430 xbt_assert(code && host_ != nullptr, "Invalid parameters");
431 auto* engine = EngineImpl::get_instance();
433 if (not host_->is_on()) {
434 XBT_WARN("Cannot launch actor '%s' on failed host '%s'", get_cname(), host_->get_cname());
435 intrusive_ptr_release(this);
436 throw HostFailureException(XBT_THROW_POINT, "Cannot start actor on failed host.");
440 XBT_VERB("Create context %s", get_cname());
441 context_.reset(engine->get_context_factory()->create_context(ActorCode(code), this));
443 XBT_DEBUG("Start context '%s'", get_cname());
445 /* Add the actor to its host's actor list */
446 host_->get_impl()->add_actor(this);
447 engine->add_actor(get_pid(), this);
449 /* Now insert it in the global actor list and in the actor to run list */
450 engine->add_actor_to_run_list_no_check(this);
455 ActorImplPtr ActorImpl::create(const std::string& name, const ActorCode& code, void* data, s4u::Host* host,
456 const ActorImpl* parent_actor)
458 XBT_DEBUG("Start actor %s@'%s'", name.c_str(), host->get_cname());
461 if (parent_actor != nullptr)
462 actor = parent_actor->init(name, host);
464 actor = self()->init(name, host);
466 actor->piface_.set_data(data); /* actor data */
472 ActorImplPtr ActorImpl::create(ProcessArg* args)
474 ActorImplPtr actor = ActorImpl::create(args->name, args->code, nullptr, args->host, nullptr);
475 actor->restart_count_ = args->restart_count_;
476 actor->set_properties(args->properties);
478 *actor->on_exit = *args->on_exit;
479 if (args->kill_time >= 0)
480 actor->set_kill_time(args->kill_time);
481 if (args->auto_restart)
482 actor->set_auto_restart(args->auto_restart);
487 void ActorImpl::set_wannadie(bool value)
489 XBT_DEBUG("Actor %s gonna die.", get_cname());
493 void create_maestro(const std::function<void()>& code)
495 auto* engine = EngineImpl::get_instance();
496 /* Create maestro actor and initialize it */
497 auto* maestro = new ActorImpl(/*name*/ "", /*host*/ nullptr, /*ppid*/ -1);
500 maestro->context_.reset(engine->get_context_factory()->create_context(ActorCode(), maestro));
502 maestro->context_.reset(engine->get_context_factory()->create_maestro(ActorCode(code), maestro));
505 maestro->simcall_.issuer_ = maestro;
506 engine->set_maestro(maestro);
509 /** (in kernel mode) unpack the simcall and activate the handler */
510 void ActorImpl::simcall_handle(int times_considered)
512 XBT_DEBUG("Handling simcall %p: %s(%ld) %s", &simcall_, simcall_.issuer_->get_cname(), simcall_.issuer_->get_pid(),
513 (simcall_.observer_ != nullptr ? simcall_.observer_->to_string().c_str() : simcall_.get_cname()));
514 if (simcall_.observer_ != nullptr)
515 simcall_.observer_->prepare(times_considered);
519 xbt_assert(simcall_.call_ != Simcall::Type::NONE, "Asked to do the noop syscall on %s@%s", get_cname(),
520 get_host()->get_cname());
523 if (simcall_.call_ == Simcall::Type::RUN_ANSWERED)
527 } // namespace simgrid::kernel::actor