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 #define SIMIX_H_NO_DEPRECATED_WARNING // avoid deprecation warning on include (remove with XBT_ATTRIB_DEPRECATED_v333)
11 #include <simgrid/simix.h>
13 #include "src/kernel/EngineImpl.hpp"
15 #include "src/smpi/include/private.hpp"
17 #include "src/surf/HostImpl.hpp"
19 #include <boost/core/demangle.hpp>
23 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(ker_actor, kernel, "Logging specific to Actor's kernel side");
26 * @brief Returns the current agent.
28 * This functions returns the currently running SIMIX process.
30 * @return The SIMIX process
32 simgrid::kernel::actor::ActorImpl* SIMIX_process_self() // XBT_ATTRIB_DEPRECATED_v333
34 return simgrid::kernel::actor::ActorImpl::self();
37 namespace simgrid::kernel::actor {
39 /*------------------------- [ ActorIDTrait ] -------------------------*/
40 unsigned long ActorIDTrait::maxpid_ = 0;
42 ActorIDTrait::ActorIDTrait(const std::string& name, aid_t ppid) : name_(name), pid_(maxpid_++), ppid_(ppid) {}
44 ActorImpl* ActorImpl::self()
46 const context::Context* self_context = context::Context::self();
48 return (self_context != nullptr) ? self_context->get_actor() : nullptr;
51 ActorImpl::ActorImpl(xbt::string name, s4u::Host* host, aid_t ppid)
52 : ActorIDTrait(std::move(name), ppid), host_(host), piface_(this)
54 simcall_.issuer_ = this;
55 stacksize_ = context::stack_size;
58 ActorImpl::~ActorImpl()
60 if (EngineImpl::has_instance() && not EngineImpl::get_instance()->is_maestro(this))
61 s4u::Actor::on_destruction(*get_ciface());
64 /* Become an actor in the simulation
66 * Currently this can only be called by the main thread (once) and only work with some thread factories
67 * (currently ThreadContextFactory).
69 * In the future, it might be extended in order to attach other threads created by a third party library.
72 ActorImplPtr ActorImpl::attach(const std::string& name, void* data, s4u::Host* host)
74 // This is mostly a copy/paste from create(), it'd be nice to share some code between those two functions.
75 auto* engine = EngineImpl::get_instance();
76 XBT_DEBUG("Attach actor %s on host '%s'", name.c_str(), host->get_cname());
78 if (not host->is_on()) {
79 XBT_WARN("Cannot attach actor '%s' on failed host '%s'", name.c_str(), host->get_cname());
80 throw HostFailureException(XBT_THROW_POINT, "Cannot attach actor on failed host.");
83 auto* actor = new ActorImpl(xbt::string(name), host, /*ppid*/ -1);
85 actor->piface_.set_data(data);
86 actor->code_ = nullptr;
88 XBT_VERB("Create context %s", actor->get_cname());
89 actor->context_.reset(engine->get_context_factory()->attach(actor));
91 /* Add the actor to it's host actor list */
92 host->get_impl()->add_actor(actor);
94 /* Now insert it in the global actor list and in the actors to run list */
95 engine->add_actor(actor->get_pid(), actor);
96 engine->add_actor_to_run_list_no_check(actor);
97 intrusive_ptr_add_ref(actor);
99 auto* context = dynamic_cast<context::AttachContext*>(actor->context_.get());
100 xbt_assert(nullptr != context, "Not a suitable context");
101 context->attach_start();
103 /* The on_creation() signal must be delayed until there, where the pid and everything is set */
104 s4u::Actor::on_creation(*actor->get_ciface());
106 return ActorImplPtr(actor);
108 /** @brief Detach an actor attached with `attach()`
110 * This is called when the current actor has finished its job.
111 * Used in the main thread, it waits for the simulation to finish before returning. When it returns, the other
112 * simulated actors and the maestro are destroyed.
114 void ActorImpl::detach()
116 auto* context = dynamic_cast<context::AttachContext*>(context::Context::self());
117 xbt_assert(context != nullptr, "Not a suitable context");
119 context->get_actor()->cleanup_from_self();
120 context->attach_stop();
123 /** Whether this actor is actually maestro */
124 bool ActorImpl::is_maestro() const
126 return context_->is_maestro();
129 void ActorImpl::cleanup_from_kernel()
131 xbt_assert(s4u::Actor::is_maestro(), "Cleanup_from_kernel must be called in maestro context");
133 auto* engine = EngineImpl::get_instance();
134 if (engine->get_actor_by_pid(get_pid()) == nullptr)
135 return; // Already cleaned
137 engine->remove_actor(get_pid());
138 if (host_ && host_actor_list_hook.is_linked())
139 host_->get_impl()->remove_actor(this);
140 if (not kernel_destroy_list_hook.is_linked())
141 engine->add_actor_to_destroy_list(*this);
143 if (has_to_auto_restart() && not get_host()->is_on()) {
144 XBT_DEBUG("Insert host %s to watched_hosts because it's off and %s needs to restart", get_host()->get_cname(),
146 watched_hosts().insert(get_host()->get_name());
150 s4u::Actor::on_termination(*get_ciface());
152 while (not mailboxes_.empty())
153 mailboxes_.back()->set_receiver(nullptr);
156 /* Do all the cleanups from the actor context. Warning, the simcall mechanism was not reignited so doing simcalls in
157 * this context is dangerous */
158 void ActorImpl::cleanup_from_self()
160 xbt_assert(not ActorImpl::is_maestro(), "Cleanup_from_self called from maestro on '%s'", get_cname());
164 // Execute the termination callbacks
165 bool failed = wannadie();
166 for (auto exit_fun = on_exit->crbegin(); exit_fun != on_exit->crend(); ++exit_fun)
171 /* cancel non-blocking activities */
172 for (auto activity : activities_)
176 XBT_DEBUG("%s@%s(%ld) should not run anymore", get_cname(), get_host()->get_cname(), get_pid());
178 /* Unregister associated timers if any */
179 if (kill_timer_ != nullptr) {
180 kill_timer_->remove();
181 kill_timer_ = nullptr;
183 if (simcall_.timeout_cb_) {
184 simcall_.timeout_cb_->remove();
185 simcall_.timeout_cb_ = nullptr;
188 /* maybe the actor was killed during a simcall, reset its observer */
189 simcall_.observer_ = nullptr;
194 void ActorImpl::exit()
198 exception_ = nullptr;
200 if (waiting_synchro_ != nullptr) {
201 /* Take an extra reference on the activity object that may be unref by Comm::finish() or friends */
202 activity::ActivityImplPtr activity = waiting_synchro_;
204 activity->set_state(activity::State::FAILED);
207 activities_.remove(waiting_synchro_);
208 waiting_synchro_ = nullptr;
210 for (auto const& activity : activities_)
214 // Forcefully kill the actor if its host is turned off. Not a HostFailureException because you should not survive that
215 this->throw_exception(std::make_exception_ptr(ForcefulKillException(host_->is_on() ? "exited" : "host failed")));
218 void ActorImpl::kill(ActorImpl* actor) const
220 xbt_assert(not actor->is_maestro(), "Killing maestro is a rather bad idea.");
221 if (actor->wannadie()) {
222 XBT_DEBUG("Ignoring request to kill actor %s@%s that is already dead", actor->get_cname(),
223 actor->host_->get_cname());
227 XBT_DEBUG("Actor '%s'@%s is killing actor '%s'@%s", get_cname(), host_ ? host_->get_cname() : "", actor->get_cname(),
228 actor->host_ ? actor->host_->get_cname() : "");
233 XBT_DEBUG("Go on, this is a suicide,");
235 EngineImpl::get_instance()->add_actor_to_run_list(actor);
238 void ActorImpl::kill_all() const
240 for (auto const& [_, actor] : EngineImpl::get_instance()->get_actor_list())
245 void ActorImpl::set_kill_time(double kill_time)
247 if (kill_time <= s4u::Engine::get_clock())
249 XBT_DEBUG("Set kill time %f for actor %s@%s", kill_time, get_cname(), host_->get_cname());
250 kill_timer_ = timer::Timer::set(kill_time, [this] {
252 kill_timer_ = nullptr;
253 EngineImpl::get_instance()->add_actor_to_run_list(this);
257 double ActorImpl::get_kill_time() const
259 return kill_timer_ ? kill_timer_->get_date() : 0.0;
262 void ActorImpl::yield()
264 XBT_DEBUG("Yield actor '%s'", get_cname());
266 /* Go into sleep and return control to maestro */
268 /* Ok, maestro returned control to us */
269 XBT_DEBUG("Control returned to me: '%s'", get_cname());
272 XBT_DEBUG("Actor %s@%s is dead", get_cname(), host_->get_cname());
278 XBT_DEBUG("Hey! I'm suspended.");
279 xbt_assert(exception_ == nullptr, "Gasp! This exception may be lost by subsequent calls.");
280 yield(); // Yield back to maestro without proceeding with my execution. I'll get rescheduled by resume()
283 if (exception_ != nullptr) {
284 XBT_DEBUG("Wait, maestro left me an exception");
285 std::exception_ptr exception = std::move(exception_);
286 exception_ = nullptr;
288 std::rethrow_exception(std::move(exception));
289 } catch (const simgrid::Exception& e) {
290 e.rethrow_nested(XBT_THROW_POINT, boost::core::demangle(typeid(e).name()) + " raised in kernel mode.");
295 smpi_switch_data_segment(get_iface());
299 /** This actor will be terminated automatically when the last non-daemon actor finishes */
300 void ActorImpl::daemonize()
304 EngineImpl::get_instance()->add_daemon(this);
308 void ActorImpl::undaemonize()
312 EngineImpl::get_instance()->remove_daemon(this);
316 s4u::Actor* ActorImpl::restart()
318 xbt_assert(not this->is_maestro(), "Restarting maestro is not supported");
320 XBT_DEBUG("Restarting actor %s on %s", get_cname(), host_->get_cname());
322 // retrieve the arguments of the old actor
323 ProcessArg args(host_, this);
325 // kill the old actor
326 context::Context::self()->get_actor()->kill(this);
328 // start the new actor
329 return create(&args)->get_ciface();
332 void ActorImpl::suspend()
335 XBT_DEBUG("Actor '%s' is already suspended", get_cname());
341 /* Suspend the activities associated with this actor. */
342 for (auto const& activity : activities_)
346 void ActorImpl::resume()
348 XBT_IN("actor = %p", this);
351 XBT_VERB("Ignoring request to resume an actor that is currently dying.");
359 /* resume the activities that were blocked when suspending the actor. */
360 for (auto const& activity : activities_)
362 if (not waiting_synchro_) // Reschedule the actor if it was forcefully unscheduled in yield()
363 EngineImpl::get_instance()->add_actor_to_run_list_no_check(this);
368 activity::ActivityImplPtr ActorImpl::join(const ActorImpl* actor, double timeout)
370 activity::ActivityImplPtr sleep = this->sleep(timeout);
371 if (actor->wannadie() || actor->to_be_freed()) {
372 if (sleep->surf_action_)
373 sleep->surf_action_->finish(resource::Action::State::FINISHED);
375 actor->on_exit->emplace_back([sleep](bool) {
376 if (sleep->surf_action_)
377 sleep->surf_action_->finish(resource::Action::State::FINISHED);
383 activity::ActivityImplPtr ActorImpl::sleep(double duration)
385 if (not host_->is_on())
386 throw_exception(std::make_exception_ptr(HostFailureException(
387 XBT_THROW_POINT, std::string("Host ") + host_->get_cname() + " failed, you cannot sleep there.")));
389 auto sleep = new activity::SleepImpl();
390 sleep->set_name("sleep").set_host(host_).set_duration(duration).start();
391 return activity::SleepImplPtr(sleep);
394 void ActorImpl::throw_exception(std::exception_ptr e)
401 /* cancel the blocking synchro if any */
402 if (waiting_synchro_) {
403 waiting_synchro_->cancel();
404 activities_.remove(waiting_synchro_);
405 waiting_synchro_ = nullptr;
409 void ActorImpl::simcall_answer()
411 auto* engine = EngineImpl::get_instance();
412 if (not this->is_maestro()) {
413 XBT_DEBUG("Answer simcall %s issued by %s (%p)", simcall_.get_cname(), get_cname(), this);
414 xbt_assert(simcall_.call_ != Simcall::Type::NONE);
415 simcall_.call_ = Simcall::Type::NONE;
416 const auto& actors_to_run = engine->get_actors_to_run();
417 xbt_assert(not XBT_LOG_ISENABLED(ker_actor, xbt_log_priority_debug) ||
418 std::find(begin(actors_to_run), end(actors_to_run), this) == end(actors_to_run),
419 "Actor %p should not exist in actors_to_run!", this);
420 engine->add_actor_to_run_list_no_check(this);
424 void ActorImpl::set_host(s4u::Host* dest)
426 host_->get_impl()->remove_actor(this);
428 dest->get_impl()->add_actor(this);
431 ActorImplPtr ActorImpl::init(const std::string& name, s4u::Host* host) const
433 auto* actor = new ActorImpl(xbt::string(name), host, get_pid());
435 intrusive_ptr_add_ref(actor);
436 /* The on_creation() signal must be delayed until there, where the pid and everything is set */
437 s4u::Actor::on_creation(*actor->get_ciface());
439 return ActorImplPtr(actor);
442 ActorImpl* ActorImpl::start(const ActorCode& code)
444 xbt_assert(code && host_ != nullptr, "Invalid parameters");
445 auto* engine = EngineImpl::get_instance();
447 if (not host_->is_on()) {
448 XBT_WARN("Cannot launch actor '%s' on failed host '%s'", get_cname(), host_->get_cname());
449 intrusive_ptr_release(this);
450 throw HostFailureException(XBT_THROW_POINT, "Cannot start actor on failed host.");
454 XBT_VERB("Create context %s", get_cname());
455 context_.reset(engine->get_context_factory()->create_context(ActorCode(code), this));
457 XBT_DEBUG("Start context '%s'", get_cname());
459 /* Add the actor to its host's actor list */
460 host_->get_impl()->add_actor(this);
461 engine->add_actor(get_pid(), this);
463 /* Now insert it in the global actor list and in the actor to run list */
464 engine->add_actor_to_run_list_no_check(this);
469 ActorImplPtr ActorImpl::create(const std::string& name, const ActorCode& code, void* data, s4u::Host* host,
470 const ActorImpl* parent_actor)
472 XBT_DEBUG("Start actor %s@'%s'", name.c_str(), host->get_cname());
475 if (parent_actor != nullptr)
476 actor = parent_actor->init(xbt::string(name), host);
478 actor = self()->init(xbt::string(name), host);
480 actor->piface_.set_data(data); /* actor data */
486 ActorImplPtr ActorImpl::create(ProcessArg* args)
488 ActorImplPtr actor = ActorImpl::create(args->name, args->code, nullptr, args->host, nullptr);
489 actor->restart_count_ = args->restart_count_;
490 actor->set_properties(args->properties);
492 *actor->on_exit = *args->on_exit;
493 if (args->kill_time >= 0)
494 actor->set_kill_time(args->kill_time);
495 if (args->auto_restart)
496 actor->set_auto_restart(args->auto_restart);
501 void ActorImpl::set_wannadie(bool value)
503 XBT_DEBUG("Actor %s gonna die.", get_cname());
507 void create_maestro(const std::function<void()>& code)
509 auto* engine = EngineImpl::get_instance();
510 /* Create maestro actor and initialize it */
511 auto* maestro = new ActorImpl(xbt::string(""), /*host*/ nullptr, /*ppid*/ -1);
514 maestro->context_.reset(engine->get_context_factory()->create_context(ActorCode(), maestro));
516 maestro->context_.reset(engine->get_context_factory()->create_maestro(ActorCode(code), maestro));
519 maestro->simcall_.issuer_ = maestro;
520 engine->set_maestro(maestro);
523 } // namespace simgrid::kernel::actor
525 /* needs to be public and without simcall because it is called by exceptions and logging events */
526 const char* SIMIX_process_self_get_name() // XBT_ATTRIB_DEPRECATED_v333
528 return simgrid::s4u::Actor::is_maestro() ? "maestro" : simgrid::kernel::actor::ActorImpl::self()->get_cname();
531 int SIMIX_is_maestro() // XBT_ATTRIB_DEPRECATED_v333
533 const auto* self = simgrid::kernel::actor::ActorImpl::self();
534 return self != nullptr && self->is_maestro();