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 smx_actor_t SIMIX_process_self() // XBT_ATTRIB_DEPRECATED_v333
34 return simgrid::kernel::actor::ActorImpl::self();
41 static unsigned long maxpid = 0;
42 unsigned long get_maxpid()
46 unsigned long* get_maxpid_addr()
50 ActorImpl* ActorImpl::by_pid(aid_t pid)
52 return EngineImpl::get_instance()->get_actor_by_pid(pid);
55 ActorImpl* ActorImpl::self()
57 const context::Context* self_context = context::Context::self();
59 return (self_context != nullptr) ? self_context->get_actor() : nullptr;
62 ActorImpl::ActorImpl(xbt::string name, s4u::Host* host) : host_(host), name_(std::move(name)), piface_(this)
65 simcall_.issuer_ = this;
66 stacksize_ = context::stack_size;
69 ActorImpl::~ActorImpl()
71 if (EngineImpl::has_instance() && not EngineImpl::get_instance()->is_maestro(this))
72 s4u::Actor::on_destruction(*get_ciface());
75 /* Become an actor in the simulation
77 * Currently this can only be called by the main thread (once) and only work with some thread factories
78 * (currently ThreadContextFactory).
80 * In the future, it might be extended in order to attach other threads created by a third party library.
83 ActorImplPtr ActorImpl::attach(const std::string& name, void* data, s4u::Host* host)
85 // This is mostly a copy/paste from create(), it'd be nice to share some code between those two functions.
86 auto* engine = EngineImpl::get_instance();
87 XBT_DEBUG("Attach actor %s on host '%s'", name.c_str(), host->get_cname());
89 if (not host->is_on()) {
90 XBT_WARN("Cannot attach actor '%s' on failed host '%s'", name.c_str(), host->get_cname());
91 throw HostFailureException(XBT_THROW_POINT, "Cannot attach actor on failed host.");
94 auto* actor = new ActorImpl(xbt::string(name), host);
96 actor->piface_.set_data(data);
97 actor->code_ = nullptr;
99 XBT_VERB("Create context %s", actor->get_cname());
100 actor->context_.reset(engine->get_context_factory()->attach(actor));
102 /* Add the actor to it's host actor list */
103 host->get_impl()->add_actor(actor);
105 /* Now insert it in the global actor list and in the actors to run list */
106 engine->add_actor(actor->get_pid(), actor);
107 engine->add_actor_to_run_list_no_check(actor);
108 intrusive_ptr_add_ref(actor);
110 auto* context = dynamic_cast<context::AttachContext*>(actor->context_.get());
111 xbt_assert(nullptr != context, "Not a suitable context");
112 context->attach_start();
114 /* The on_creation() signal must be delayed until there, where the pid and everything is set */
115 s4u::Actor::on_creation(*actor->get_ciface());
117 return ActorImplPtr(actor);
119 /** @brief Detach an actor attached with `attach()`
121 * This is called when the current actor has finished its job.
122 * Used in the main thread, it waits for the simulation to finish before returning. When it returns, the other
123 * simulated actors and the maestro are destroyed.
125 void ActorImpl::detach()
127 auto* context = dynamic_cast<context::AttachContext*>(context::Context::self());
128 xbt_assert(context != nullptr, "Not a suitable context");
130 context->get_actor()->cleanup_from_self();
131 context->attach_stop();
134 /** Whether this actor is actually maestro */
135 bool ActorImpl::is_maestro() const
137 return context_->is_maestro();
140 void ActorImpl::cleanup_from_kernel()
142 xbt_assert(s4u::Actor::is_maestro(), "Cleanup_from_kernel called from '%s' on '%s'", ActorImpl::self()->get_cname(),
145 auto* engine = EngineImpl::get_instance();
146 engine->remove_actor(pid_);
147 if (host_ && host_actor_list_hook.is_linked())
148 host_->get_impl()->remove_actor(this);
149 if (not kernel_destroy_list_hook.is_linked())
150 engine->add_actor_to_destroy_list(*this);
152 if (has_to_auto_restart() && not get_host()->is_on()) {
153 XBT_DEBUG("Insert host %s to watched_hosts because it's off and %s needs to restart", get_host()->get_cname(),
155 watched_hosts().insert(get_host()->get_name());
160 while (not mailboxes.empty())
161 mailboxes.back()->set_receiver(nullptr);
164 /* Do all the cleanups from the actor context. Warning, the simcall mechanism was not reignited so doing simcalls in
165 * this context is dangerous */
166 void ActorImpl::cleanup_from_self()
168 xbt_assert(not ActorImpl::is_maestro(), "Cleanup_from_self called from maestro on '%s'", get_cname());
169 context_->set_to_be_freed();
172 // Execute the termination callbacks
173 bool failed = context_->wannadie();
174 for (auto exit_fun = on_exit->crbegin(); exit_fun != on_exit->crend(); ++exit_fun)
179 /* cancel non-blocking activities */
180 for (auto activity : activities_)
184 XBT_DEBUG("%s@%s(%ld) should not run anymore", get_cname(), get_host()->get_cname(), get_pid());
186 /* Unregister associated timers if any */
187 if (kill_timer_ != nullptr) {
188 kill_timer_->remove();
189 kill_timer_ = nullptr;
191 if (simcall_.timeout_cb_) {
192 simcall_.timeout_cb_->remove();
193 simcall_.timeout_cb_ = nullptr;
196 context_->set_wannadie(false); // don't let the simcall's yield() do a Context::stop(), to avoid infinite loops
197 actor::simcall_answered([this] { s4u::Actor::on_termination(*get_ciface()); });
198 context_->set_wannadie();
201 void ActorImpl::exit()
203 context_->set_wannadie();
205 exception_ = nullptr;
207 /* destroy the blocking synchro if any */
208 if (auto activity = waiting_synchro_) {
209 activities_.remove(waiting_synchro_);
210 waiting_synchro_ = nullptr;
213 activity->set_state(activity::State::FAILED);
216 for (auto const& activity : activities_)
220 while (not mailboxes.empty())
221 mailboxes.back()->set_receiver(nullptr);
223 // Forcefully kill the actor if its host is turned off. Not a HostFailureException because you should not survive that
224 this->throw_exception(std::make_exception_ptr(ForcefulKillException(host_->is_on() ? "exited" : "host failed")));
227 void ActorImpl::kill(ActorImpl* actor) const
229 xbt_assert(not actor->is_maestro(), "Killing maestro is a rather bad idea.");
230 if (actor->context_->wannadie()) {
231 XBT_DEBUG("Ignoring request to kill actor %s@%s that is already dead", actor->get_cname(),
232 actor->host_->get_cname());
236 XBT_DEBUG("Actor '%s'@%s is killing actor '%s'@%s", get_cname(), host_ ? host_->get_cname() : "", actor->get_cname(),
237 actor->host_ ? actor->host_->get_cname() : "");
242 XBT_DEBUG("Go on, this is a suicide,");
244 EngineImpl::get_instance()->add_actor_to_run_list(actor);
247 void ActorImpl::kill_all() const
249 for (auto const& kv : EngineImpl::get_instance()->get_actor_list())
250 if (kv.second != this)
251 this->kill(kv.second);
254 void ActorImpl::set_kill_time(double kill_time)
256 if (kill_time <= s4u::Engine::get_clock())
258 XBT_DEBUG("Set kill time %f for actor %s@%s", kill_time, get_cname(), host_->get_cname());
259 kill_timer_ = timer::Timer::set(kill_time, [this] {
261 kill_timer_ = nullptr;
265 double ActorImpl::get_kill_time() const
267 return kill_timer_ ? kill_timer_->get_date() : 0.0;
270 void ActorImpl::yield()
272 XBT_DEBUG("Yield actor '%s'", get_cname());
274 /* Go into sleep and return control to maestro */
276 /* Ok, maestro returned control to us */
277 XBT_DEBUG("Control returned to me: '%s'", get_cname());
279 if (context_->wannadie()) {
280 XBT_DEBUG("Actor %s@%s is dead", get_cname(), host_->get_cname());
286 XBT_DEBUG("Hey! I'm suspended.");
287 xbt_assert(exception_ == nullptr, "Gasp! This exception may be lost by subsequent calls.");
288 yield(); // Yield back to maestro without proceeding with my execution. I'll get rescheduled by resume()
291 if (exception_ != nullptr) {
292 XBT_DEBUG("Wait, maestro left me an exception");
293 std::exception_ptr exception = std::move(exception_);
294 exception_ = nullptr;
296 std::rethrow_exception(std::move(exception));
297 } catch (const simgrid::Exception& e) {
298 e.rethrow_nested(XBT_THROW_POINT, boost::core::demangle(typeid(e).name()) + " raised in kernel mode.");
302 if (not context_->wannadie())
303 smpi_switch_data_segment(get_iface());
307 /** This actor will be terminated automatically when the last non-daemon actor finishes */
308 void ActorImpl::daemonize()
312 EngineImpl::get_instance()->add_daemon(this);
316 void ActorImpl::undaemonize()
320 EngineImpl::get_instance()->remove_daemon(this);
324 s4u::Actor* ActorImpl::restart()
326 xbt_assert(not this->is_maestro(), "Restarting maestro is not supported");
328 XBT_DEBUG("Restarting actor %s on %s", get_cname(), host_->get_cname());
330 // retrieve the arguments of the old actor
331 ProcessArg args(host_, this);
333 // kill the old actor
334 context::Context::self()->get_actor()->kill(this);
336 // start the new actor
337 return create(&args)->get_ciface();
340 void ActorImpl::suspend()
343 XBT_DEBUG("Actor '%s' is already suspended", get_cname());
349 /* Suspend the activities associated with this actor. */
350 for (auto const& activity : activities_)
354 void ActorImpl::resume()
356 XBT_IN("actor = %p", this);
358 if (context_->wannadie()) {
359 XBT_VERB("Ignoring request to resume an actor that is currently dying.");
367 /* resume the activities that were blocked when suspending the actor. */
368 for (auto const& activity : activities_)
370 if (not waiting_synchro_) // Reschedule the actor if it was forcefully unscheduled in yield()
371 EngineImpl::get_instance()->add_actor_to_run_list_no_check(this);
376 activity::ActivityImplPtr ActorImpl::join(const ActorImpl* actor, double timeout)
378 activity::ActivityImplPtr sleep = this->sleep(timeout);
379 actor->on_exit->emplace_back([sleep](bool) {
380 if (sleep->surf_action_)
381 sleep->surf_action_->finish(resource::Action::State::FINISHED);
386 activity::ActivityImplPtr ActorImpl::sleep(double duration)
388 if (not host_->is_on())
389 throw_exception(std::make_exception_ptr(HostFailureException(
390 XBT_THROW_POINT, std::string("Host ") + host_->get_cname() + " failed, you cannot sleep there.")));
392 auto sleep = new activity::SleepImpl();
393 sleep->set_name("sleep").set_host(host_).set_duration(duration).start();
394 return activity::SleepImplPtr(sleep);
397 void ActorImpl::throw_exception(std::exception_ptr e)
404 /* cancel the blocking synchro if any */
405 if (waiting_synchro_) {
406 waiting_synchro_->cancel();
407 activities_.remove(waiting_synchro_);
408 waiting_synchro_ = nullptr;
412 void ActorImpl::simcall_answer()
414 auto* engine = EngineImpl::get_instance();
415 if (not this->is_maestro()) {
416 XBT_DEBUG("Answer simcall %s issued by %s (%p)", simcall_.get_cname(), get_cname(), this);
417 xbt_assert(simcall_.call_ != Simcall::Type::NONE);
418 simcall_.call_ = Simcall::Type::NONE;
419 const auto& actors_to_run = engine->get_actors_to_run();
420 xbt_assert(not XBT_LOG_ISENABLED(ker_actor, xbt_log_priority_debug) ||
421 std::find(begin(actors_to_run), end(actors_to_run), this) == end(actors_to_run),
422 "Actor %p should not exist in actors_to_run!", this);
423 engine->add_actor_to_run_list_no_check(this);
427 void ActorImpl::set_host(s4u::Host* dest)
429 host_->get_impl()->remove_actor(this);
431 dest->get_impl()->add_actor(this);
434 ActorImplPtr ActorImpl::init(const std::string& name, s4u::Host* host) const
436 auto* actor = new ActorImpl(xbt::string(name), host);
437 actor->set_ppid(this->pid_);
439 intrusive_ptr_add_ref(actor);
440 /* The on_creation() signal must be delayed until there, where the pid and everything is set */
441 s4u::Actor::on_creation(*actor->get_ciface());
443 return ActorImplPtr(actor);
446 ActorImpl* ActorImpl::start(const ActorCode& code)
448 xbt_assert(code && host_ != nullptr, "Invalid parameters");
449 auto* engine = EngineImpl::get_instance();
451 if (not host_->is_on()) {
452 XBT_WARN("Cannot launch actor '%s' on failed host '%s'", name_.c_str(), host_->get_cname());
453 intrusive_ptr_release(this);
454 throw HostFailureException(XBT_THROW_POINT, "Cannot start actor on failed host.");
458 XBT_VERB("Create context %s", get_cname());
459 context_.reset(engine->get_context_factory()->create_context(ActorCode(code), this));
461 XBT_DEBUG("Start context '%s'", get_cname());
463 /* Add the actor to its host's actor list */
464 host_->get_impl()->add_actor(this);
465 engine->add_actor(pid_, this);
467 /* Now insert it in the global actor list and in the actor to run list */
468 engine->add_actor_to_run_list_no_check(this);
473 ActorImplPtr ActorImpl::create(const std::string& name, const ActorCode& code, void* data, s4u::Host* host,
474 const ActorImpl* parent_actor)
476 XBT_DEBUG("Start actor %s@'%s'", name.c_str(), host->get_cname());
479 if (parent_actor != nullptr)
480 actor = parent_actor->init(xbt::string(name), host);
482 actor = self()->init(xbt::string(name), host);
484 actor->piface_.set_data(data); /* actor data */
490 ActorImplPtr ActorImpl::create(ProcessArg* args)
492 ActorImplPtr actor = ActorImpl::create(args->name, args->code, nullptr, args->host, nullptr);
493 actor->restart_count_ = args->restart_count_;
494 actor->set_properties(args->properties);
496 *actor->on_exit = *args->on_exit;
497 if (args->kill_time >= 0)
498 actor->set_kill_time(args->kill_time);
499 if (args->auto_restart)
500 actor->set_auto_restart(args->auto_restart);
506 void create_maestro(const std::function<void()>& code)
508 auto* engine = EngineImpl::get_instance();
509 /* Create maestro actor and initialize it */
510 auto* maestro = new ActorImpl(xbt::string(""), /*host*/ nullptr);
513 maestro->context_.reset(engine->get_context_factory()->create_context(ActorCode(), maestro));
515 maestro->context_.reset(engine->get_context_factory()->create_maestro(ActorCode(code), maestro));
518 maestro->simcall_.issuer_ = maestro;
519 engine->set_maestro(maestro);
523 } // namespace kernel
524 } // namespace simgrid
526 /* needs to be public and without simcall because it is called by exceptions and logging events */
527 const char* SIMIX_process_self_get_name() // XBT_ATTRIB_DEPRECATED_v333
529 return simgrid::s4u::Actor::is_maestro() ? "maestro" : simgrid::kernel::actor::ActorImpl::self()->get_cname();
532 int SIMIX_is_maestro() // XBT_ATTRIB_DEPRECATED_v333
534 const auto* self = simgrid::kernel::actor::ActorImpl::self();
535 return self != nullptr && self->is_maestro();