1 /* Copyright (c) 2007-2022. 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 <simgrid/Exception.hpp>
7 #include <simgrid/s4u/Actor.hpp>
8 #include <simgrid/s4u/Host.hpp>
10 #include "src/kernel/EngineImpl.hpp"
12 #include "src/smpi/include/private.hpp"
14 #include "src/surf/HostImpl.hpp"
16 #include <boost/core/demangle.hpp>
20 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(ker_actor, kernel, "Logging specific to Actor's kernel side");
22 namespace simgrid::kernel::actor {
24 /*------------------------- [ ActorIDTrait ] -------------------------*/
25 unsigned long ActorIDTrait::maxpid_ = 0;
27 ActorIDTrait::ActorIDTrait(const std::string& name, aid_t ppid) : name_(name), pid_(maxpid_++), ppid_(ppid) {}
29 ActorImpl* ActorImpl::self()
31 const context::Context* self_context = context::Context::self();
33 return (self_context != nullptr) ? self_context->get_actor() : nullptr;
36 ActorImpl::ActorImpl(xbt::string name, s4u::Host* host, aid_t ppid)
37 : ActorIDTrait(std::move(name), ppid), host_(host), piface_(this)
39 simcall_.issuer_ = this;
40 stacksize_ = context::stack_size;
43 ActorImpl::~ActorImpl()
45 if (EngineImpl::has_instance() && not EngineImpl::get_instance()->is_maestro(this))
46 s4u::Actor::on_destruction(*get_ciface());
49 /* Become an actor in the simulation
51 * Currently this can only be called by the main thread (once) and only work with some thread factories
52 * (currently ThreadContextFactory).
54 * In the future, it might be extended in order to attach other threads created by a third party library.
57 ActorImplPtr ActorImpl::attach(const std::string& name, void* data, s4u::Host* host)
59 // This is mostly a copy/paste from create(), it'd be nice to share some code between those two functions.
60 auto* engine = EngineImpl::get_instance();
61 XBT_DEBUG("Attach actor %s on host '%s'", name.c_str(), host->get_cname());
63 if (not host->is_on()) {
64 XBT_WARN("Cannot attach actor '%s' on failed host '%s'", name.c_str(), host->get_cname());
65 throw HostFailureException(XBT_THROW_POINT, "Cannot attach actor on failed host.");
68 auto* actor = new ActorImpl(xbt::string(name), host, /*ppid*/ -1);
70 actor->piface_.set_data(data);
71 actor->code_ = nullptr;
73 XBT_VERB("Create context %s", actor->get_cname());
74 actor->context_.reset(engine->get_context_factory()->attach(actor));
76 /* Add the actor to it's host actor list */
77 host->get_impl()->add_actor(actor);
79 /* Now insert it in the global actor list and in the actors to run list */
80 engine->add_actor(actor->get_pid(), actor);
81 engine->add_actor_to_run_list_no_check(actor);
82 intrusive_ptr_add_ref(actor);
84 auto* context = dynamic_cast<context::AttachContext*>(actor->context_.get());
85 xbt_assert(nullptr != context, "Not a suitable context");
86 context->attach_start();
88 /* The on_creation() signal must be delayed until there, where the pid and everything is set */
89 s4u::Actor::on_creation(*actor->get_ciface());
91 return ActorImplPtr(actor);
93 /** @brief Detach an actor attached with `attach()`
95 * This is called when the current actor has finished its job.
96 * Used in the main thread, it waits for the simulation to finish before returning. When it returns, the other
97 * simulated actors and the maestro are destroyed.
99 void ActorImpl::detach()
101 auto* context = dynamic_cast<context::AttachContext*>(context::Context::self());
102 xbt_assert(context != nullptr, "Not a suitable context");
104 context->get_actor()->cleanup_from_self();
105 context->attach_stop();
108 /** Whether this actor is actually maestro */
109 bool ActorImpl::is_maestro() const
111 return context_->is_maestro();
114 void ActorImpl::cleanup_from_kernel()
116 xbt_assert(s4u::Actor::is_maestro(), "Cleanup_from_kernel must be called in maestro context");
118 auto* engine = EngineImpl::get_instance();
119 if (engine->get_actor_by_pid(get_pid()) == nullptr)
120 return; // Already cleaned
122 engine->remove_actor(get_pid());
123 if (host_ && host_actor_list_hook.is_linked())
124 host_->get_impl()->remove_actor(this);
125 if (not kernel_destroy_list_hook.is_linked())
126 engine->add_actor_to_destroy_list(*this);
128 if (has_to_auto_restart() && not get_host()->is_on()) {
129 XBT_DEBUG("Insert host %s to watched_hosts because it's off and %s needs to restart", get_host()->get_cname(),
131 watched_hosts().insert(get_host()->get_name());
135 s4u::Actor::on_termination(*get_ciface());
137 while (not mailboxes_.empty())
138 mailboxes_.back()->set_receiver(nullptr);
141 /* Do all the cleanups from the actor context. Warning, the simcall mechanism was not reignited so doing simcalls in
142 * this context is dangerous */
143 void ActorImpl::cleanup_from_self()
145 xbt_assert(not ActorImpl::is_maestro(), "Cleanup_from_self called from maestro on '%s'", get_cname());
149 // Execute the termination callbacks
150 bool failed = wannadie();
151 for (auto exit_fun = on_exit->crbegin(); exit_fun != on_exit->crend(); ++exit_fun)
156 /* cancel non-blocking activities */
157 for (auto activity : activities_)
161 XBT_DEBUG("%s@%s(%ld) should not run anymore", get_cname(), get_host()->get_cname(), get_pid());
163 /* Unregister associated timers if any */
164 if (kill_timer_ != nullptr) {
165 kill_timer_->remove();
166 kill_timer_ = nullptr;
168 if (simcall_.timeout_cb_) {
169 simcall_.timeout_cb_->remove();
170 simcall_.timeout_cb_ = nullptr;
173 /* maybe the actor was killed during a simcall, reset its observer */
174 simcall_.observer_ = nullptr;
179 void ActorImpl::exit()
183 exception_ = nullptr;
185 if (waiting_synchro_ != nullptr) {
186 /* Take an extra reference on the activity object that may be unref by Comm::finish() or friends */
187 activity::ActivityImplPtr activity = waiting_synchro_;
189 activity->set_state(activity::State::FAILED);
192 activities_.remove(waiting_synchro_);
193 waiting_synchro_ = nullptr;
195 for (auto const& activity : activities_)
199 // Forcefully kill the actor if its host is turned off. Not a HostFailureException because you should not survive that
200 this->throw_exception(std::make_exception_ptr(ForcefulKillException(host_->is_on() ? "exited" : "host failed")));
203 void ActorImpl::kill(ActorImpl* actor) const
205 xbt_assert(not actor->is_maestro(), "Killing maestro is a rather bad idea.");
206 if (actor->wannadie()) {
207 XBT_DEBUG("Ignoring request to kill actor %s@%s that is already dead", actor->get_cname(),
208 actor->host_->get_cname());
212 XBT_DEBUG("Actor '%s'@%s is killing actor '%s'@%s", get_cname(), host_ ? host_->get_cname() : "", actor->get_cname(),
213 actor->host_ ? actor->host_->get_cname() : "");
218 XBT_DEBUG("Go on, this is a suicide,");
220 EngineImpl::get_instance()->add_actor_to_run_list(actor);
223 void ActorImpl::kill_all() const
225 for (auto const& [_, actor] : EngineImpl::get_instance()->get_actor_list())
230 void ActorImpl::set_kill_time(double kill_time)
232 if (kill_time <= s4u::Engine::get_clock())
234 XBT_DEBUG("Set kill time %f for actor %s@%s", kill_time, get_cname(), host_->get_cname());
235 kill_timer_ = timer::Timer::set(kill_time, [this] {
237 kill_timer_ = nullptr;
238 EngineImpl::get_instance()->add_actor_to_run_list(this);
242 double ActorImpl::get_kill_time() const
244 return kill_timer_ ? kill_timer_->get_date() : 0.0;
247 void ActorImpl::yield()
249 XBT_DEBUG("Yield actor '%s'", get_cname());
251 /* Go into sleep and return control to maestro */
253 /* Ok, maestro returned control to us */
254 XBT_DEBUG("Control returned to me: '%s'", get_cname());
257 XBT_DEBUG("Actor %s@%s is dead", get_cname(), host_->get_cname());
263 XBT_DEBUG("Hey! I'm suspended.");
264 xbt_assert(exception_ == nullptr, "Gasp! This exception may be lost by subsequent calls.");
265 yield(); // Yield back to maestro without proceeding with my execution. I'll get rescheduled by resume()
268 if (exception_ != nullptr) {
269 XBT_DEBUG("Wait, maestro left me an exception");
270 std::exception_ptr exception = std::move(exception_);
271 exception_ = nullptr;
273 std::rethrow_exception(std::move(exception));
274 } catch (const simgrid::Exception& e) {
275 e.rethrow_nested(XBT_THROW_POINT, boost::core::demangle(typeid(e).name()) + " raised in kernel mode.");
280 smpi_switch_data_segment(get_iface());
284 /** This actor will be terminated automatically when the last non-daemon actor finishes */
285 void ActorImpl::daemonize()
289 EngineImpl::get_instance()->add_daemon(this);
293 void ActorImpl::undaemonize()
297 EngineImpl::get_instance()->remove_daemon(this);
301 s4u::Actor* ActorImpl::restart()
303 xbt_assert(not this->is_maestro(), "Restarting maestro is not supported");
305 XBT_DEBUG("Restarting actor %s on %s", get_cname(), host_->get_cname());
307 // retrieve the arguments of the old actor
308 ProcessArg args(host_, this);
310 // kill the old actor
311 context::Context::self()->get_actor()->kill(this);
313 // start the new actor
314 return create(&args)->get_ciface();
317 void ActorImpl::suspend()
320 XBT_DEBUG("Actor '%s' is already suspended", get_cname());
326 /* Suspend the activities associated with this actor. */
327 for (auto const& activity : activities_)
331 void ActorImpl::resume()
333 XBT_IN("actor = %p", this);
336 XBT_VERB("Ignoring request to resume an actor that is currently dying.");
344 /* resume the activities that were blocked when suspending the actor. */
345 for (auto const& activity : activities_)
347 if (not waiting_synchro_) // Reschedule the actor if it was forcefully unscheduled in yield()
348 EngineImpl::get_instance()->add_actor_to_run_list_no_check(this);
353 activity::ActivityImplPtr ActorImpl::join(const ActorImpl* actor, double timeout)
355 activity::ActivityImplPtr sleep_activity = this->sleep(timeout);
356 if (actor->wannadie() || actor->to_be_freed()) {
357 if (sleep_activity->surf_action_)
358 sleep_activity->surf_action_->finish(resource::Action::State::FINISHED);
360 actor->on_exit->emplace_back([sleep_activity](bool) {
361 if (sleep_activity->surf_action_)
362 sleep_activity->surf_action_->finish(resource::Action::State::FINISHED);
365 return sleep_activity;
368 activity::ActivityImplPtr ActorImpl::sleep(double duration)
370 if (not host_->is_on())
371 throw_exception(std::make_exception_ptr(HostFailureException(
372 XBT_THROW_POINT, std::string("Host ") + host_->get_cname() + " failed, you cannot sleep there.")));
374 auto sleep_activity = new activity::SleepImpl();
375 sleep_activity->set_name("sleep").set_host(host_).set_duration(duration).start();
376 return activity::SleepImplPtr(sleep_activity);
379 void ActorImpl::throw_exception(std::exception_ptr e)
386 /* cancel the blocking synchro if any */
387 if (waiting_synchro_) {
388 waiting_synchro_->cancel();
389 activities_.remove(waiting_synchro_);
390 waiting_synchro_ = nullptr;
394 void ActorImpl::simcall_answer()
396 auto* engine = EngineImpl::get_instance();
397 if (not this->is_maestro()) {
398 XBT_DEBUG("Answer simcall %s issued by %s (%p)", simcall_.get_cname(), get_cname(), this);
399 xbt_assert(simcall_.call_ != Simcall::Type::NONE);
400 simcall_.call_ = Simcall::Type::NONE;
401 const auto& actors_to_run = engine->get_actors_to_run();
402 xbt_assert(not XBT_LOG_ISENABLED(ker_actor, xbt_log_priority_debug) ||
403 std::find(begin(actors_to_run), end(actors_to_run), this) == end(actors_to_run),
404 "Actor %p should not exist in actors_to_run!", this);
405 engine->add_actor_to_run_list_no_check(this);
409 void ActorImpl::set_host(s4u::Host* dest)
411 host_->get_impl()->remove_actor(this);
413 dest->get_impl()->add_actor(this);
416 ActorImplPtr ActorImpl::init(const std::string& name, s4u::Host* host) const
418 auto* actor = new ActorImpl(xbt::string(name), host, get_pid());
420 intrusive_ptr_add_ref(actor);
421 /* The on_creation() signal must be delayed until there, where the pid and everything is set */
422 s4u::Actor::on_creation(*actor->get_ciface());
424 return ActorImplPtr(actor);
427 ActorImpl* ActorImpl::start(const ActorCode& code)
429 xbt_assert(code && host_ != nullptr, "Invalid parameters");
430 auto* engine = EngineImpl::get_instance();
432 if (not host_->is_on()) {
433 XBT_WARN("Cannot launch actor '%s' on failed host '%s'", get_cname(), host_->get_cname());
434 intrusive_ptr_release(this);
435 throw HostFailureException(XBT_THROW_POINT, "Cannot start actor on failed host.");
439 XBT_VERB("Create context %s", get_cname());
440 context_.reset(engine->get_context_factory()->create_context(ActorCode(code), this));
442 XBT_DEBUG("Start context '%s'", get_cname());
444 /* Add the actor to its host's actor list */
445 host_->get_impl()->add_actor(this);
446 engine->add_actor(get_pid(), this);
448 /* Now insert it in the global actor list and in the actor to run list */
449 engine->add_actor_to_run_list_no_check(this);
454 ActorImplPtr ActorImpl::create(const std::string& name, const ActorCode& code, void* data, s4u::Host* host,
455 const ActorImpl* parent_actor)
457 XBT_DEBUG("Start actor %s@'%s'", name.c_str(), host->get_cname());
460 if (parent_actor != nullptr)
461 actor = parent_actor->init(xbt::string(name), host);
463 actor = self()->init(xbt::string(name), host);
465 actor->piface_.set_data(data); /* actor data */
471 ActorImplPtr ActorImpl::create(ProcessArg* args)
473 ActorImplPtr actor = ActorImpl::create(args->name, args->code, nullptr, args->host, nullptr);
474 actor->restart_count_ = args->restart_count_;
475 actor->set_properties(args->properties);
477 *actor->on_exit = *args->on_exit;
478 if (args->kill_time >= 0)
479 actor->set_kill_time(args->kill_time);
480 if (args->auto_restart)
481 actor->set_auto_restart(args->auto_restart);
486 void ActorImpl::set_wannadie(bool value)
488 XBT_DEBUG("Actor %s gonna die.", get_cname());
492 void create_maestro(const std::function<void()>& code)
494 auto* engine = EngineImpl::get_instance();
495 /* Create maestro actor and initialize it */
496 auto* maestro = new ActorImpl(xbt::string(""), /*host*/ nullptr, /*ppid*/ -1);
499 maestro->context_.reset(engine->get_context_factory()->create_context(ActorCode(), maestro));
501 maestro->context_.reset(engine->get_context_factory()->create_maestro(ActorCode(code), maestro));
504 maestro->simcall_.issuer_ = maestro;
505 engine->set_maestro(maestro);
508 } // namespace simgrid::kernel::actor