1 /* Copyright (c) 2007-2021. 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/s4u/Actor.hpp"
8 #include "simgrid/Exception.hpp"
9 #include "simgrid/s4u/Exec.hpp"
10 #include "src/kernel/EngineImpl.hpp"
11 #include "src/kernel/activity/CommImpl.hpp"
12 #include "src/kernel/activity/ExecImpl.hpp"
13 #include "src/kernel/activity/IoImpl.hpp"
14 #include "src/kernel/activity/SleepImpl.hpp"
15 #include "src/kernel/activity/SynchroRaw.hpp"
16 #include "src/mc/mc_replay.hpp"
17 #include "src/mc/remote/AppSide.hpp"
18 #include "src/simix/smx_private.hpp"
20 #include "src/smpi/include/private.hpp"
22 #include "src/surf/HostImpl.hpp"
23 #include "src/surf/cpu_interface.hpp"
25 #include <boost/core/demangle.hpp>
29 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(simix_process, simix, "Logging specific to SIMIX (process)");
32 * @brief Returns the current agent.
34 * This functions returns the currently running SIMIX process.
36 * @return The SIMIX process
38 smx_actor_t SIMIX_process_self()
40 return simgrid::kernel::actor::ActorImpl::self();
47 static unsigned long maxpid = 0;
48 unsigned long get_maxpid()
52 unsigned long* get_maxpid_addr()
56 ActorImpl* ActorImpl::by_pid(aid_t pid)
58 return EngineImpl::get_instance()->get_actor_by_pid(pid);
61 ActorImpl* ActorImpl::self()
63 const context::Context* self_context = context::Context::self();
65 return (self_context != nullptr) ? self_context->get_actor() : nullptr;
68 ActorImpl::ActorImpl(xbt::string name, s4u::Host* host) : host_(host), name_(std::move(name)), piface_(this)
71 simcall_.issuer_ = this;
72 stacksize_ = smx_context_stack_size;
75 ActorImpl::~ActorImpl()
77 if (simix_global != nullptr && not simix_global->is_maestro(this))
78 s4u::Actor::on_destruction(*get_ciface());
81 /* Become an actor in the simulation
83 * Currently this can only be called by the main thread (once) and only work with some thread factories
84 * (currently ThreadContextFactory).
86 * In the future, it might be extended in order to attach other threads created by a third party library.
89 ActorImplPtr ActorImpl::attach(const std::string& name, void* data, s4u::Host* host)
91 // This is mostly a copy/paste from create(), it'd be nice to share some code between those two functions.
92 auto* engine = EngineImpl::get_instance();
93 XBT_DEBUG("Attach actor %s on host '%s'", name.c_str(), host->get_cname());
95 if (not host->is_on()) {
96 XBT_WARN("Cannot attach actor '%s' on failed host '%s'", name.c_str(), host->get_cname());
97 throw HostFailureException(XBT_THROW_POINT, "Cannot attach actor on failed host.");
100 auto* actor = new ActorImpl(xbt::string(name), host);
102 actor->set_user_data(data);
103 actor->code_ = nullptr;
105 XBT_VERB("Create context %s", actor->get_cname());
106 xbt_assert(simix_global != nullptr, "simix is not initialized, please call MSG_init first");
107 actor->context_.reset(simix_global->get_context_factory()->attach(actor));
109 /* Add the actor to it's host actor list */
110 host->get_impl()->add_actor(actor);
112 /* Now insert it in the global actor list and in the actors to run list */
113 engine->add_actor(actor->get_pid(), actor);
114 engine->add_actor_to_run_list_no_check(actor);
115 intrusive_ptr_add_ref(actor);
117 auto* context = dynamic_cast<context::AttachContext*>(actor->context_.get());
118 xbt_assert(nullptr != context, "Not a suitable context");
119 context->attach_start();
121 /* The on_creation() signal must be delayed until there, where the pid and everything is set */
122 s4u::Actor::on_creation(*actor->get_ciface());
124 return ActorImplPtr(actor);
126 /** @brief Detach an actor attached with `attach()`
128 * This is called when the current actor has finished its job.
129 * Used in the main thread, it waits for the simulation to finish before returning. When it returns, the other
130 * simulated actors and the maestro are destroyed.
132 void ActorImpl::detach()
134 auto* context = dynamic_cast<context::AttachContext*>(context::Context::self());
135 xbt_assert(context != nullptr, "Not a suitable context");
137 context->get_actor()->cleanup();
138 context->attach_stop();
141 void ActorImpl::cleanup_from_simix()
143 auto* engine = EngineImpl::get_instance();
144 const std::lock_guard<std::mutex> lock(engine->get_mutex());
145 engine->remove_actor(pid_);
146 if (host_ && host_actor_list_hook.is_linked())
147 host_->get_impl()->remove_actor(this);
148 if (not kernel_destroy_list_hook.is_linked()) {
150 engine->add_dead_actor_to_dynar(this);
152 engine->add_actor_to_destroy_list(*this);
156 void ActorImpl::cleanup()
160 if (has_to_auto_restart() && not get_host()->is_on()) {
161 XBT_DEBUG("Insert host %s to watched_hosts because it's off and %s needs to restart", get_host()->get_cname(),
163 watched_hosts().insert(get_host()->get_name());
167 // Execute the termination callbacks
168 bool failed = context_->wannadie();
169 for (auto exit_fun = on_exit->crbegin(); exit_fun != on_exit->crend(); ++exit_fun)
175 /* cancel non-blocking activities */
176 for (auto activity : activities_)
180 XBT_DEBUG("%s@%s(%ld) should not run anymore", get_cname(), get_host()->get_cname(), get_pid());
182 if (simix_global->is_maestro(this)) /* Do not cleanup maestro */
185 XBT_DEBUG("Cleanup actor %s (%p), waiting synchro %p", get_cname(), this, waiting_synchro_.get());
187 /* Unregister associated timers if any */
188 if (kill_timer_ != nullptr) {
189 kill_timer_->remove();
190 kill_timer_ = nullptr;
192 if (simcall_.timeout_cb_) {
193 simcall_.timeout_cb_->remove();
194 simcall_.timeout_cb_ = nullptr;
197 cleanup_from_simix();
199 context_->set_wannadie(false); // don't let the simcall's yield() do a Context::stop(), to avoid infinite loops
200 actor::simcall([this] { s4u::Actor::on_termination(*get_ciface()); });
201 context_->set_wannadie();
204 void ActorImpl::exit()
206 context_->set_wannadie();
208 exception_ = nullptr;
210 /* destroy the blocking synchro if any */
211 if (waiting_synchro_ != nullptr) {
212 waiting_synchro_->cancel();
213 waiting_synchro_->state_ = activity::State::FAILED;
215 activity::ExecImplPtr exec = boost::dynamic_pointer_cast<activity::ExecImpl>(waiting_synchro_);
216 activity::CommImplPtr comm = boost::dynamic_pointer_cast<activity::CommImpl>(waiting_synchro_);
218 if (exec != nullptr) {
219 exec->clean_action();
220 } else if (comm != nullptr) {
221 comm->unregister_simcall(&simcall_);
223 activity::ActivityImplPtr(waiting_synchro_)->finish();
226 activities_.remove(waiting_synchro_);
227 waiting_synchro_ = nullptr;
229 for (auto const& activity : activities_)
233 // Forcefully kill the actor if its host is turned off. Not a HostFailureException because you should not survive that
234 this->throw_exception(std::make_exception_ptr(ForcefulKillException(host_->is_on() ? "exited" : "host failed")));
237 void ActorImpl::kill(ActorImpl* actor) const
239 xbt_assert(not simix_global->is_maestro(actor), "Killing maestro is a rather bad idea");
240 if (actor->finished_) {
241 XBT_DEBUG("Ignoring request to kill actor %s@%s that is already dead", actor->get_cname(),
242 actor->host_->get_cname());
246 XBT_DEBUG("Actor '%s'@%s is killing actor '%s'@%s", get_cname(), host_ ? host_->get_cname() : "", actor->get_cname(),
247 actor->host_ ? actor->host_->get_cname() : "");
252 XBT_DEBUG("Go on, this is a suicide,");
254 EngineImpl::get_instance()->add_actor_to_run_list(actor);
257 void ActorImpl::kill_all() const
259 for (auto const& kv : EngineImpl::get_instance()->get_actor_list())
260 if (kv.second != this)
261 this->kill(kv.second);
264 void ActorImpl::set_kill_time(double kill_time)
266 if (kill_time <= s4u::Engine::get_clock())
268 XBT_DEBUG("Set kill time %f for actor %s@%s", kill_time, get_cname(), host_->get_cname());
269 kill_timer_ = timer::Timer::set(kill_time, [this] {
271 kill_timer_ = nullptr;
275 double ActorImpl::get_kill_time() const
277 return kill_timer_ ? kill_timer_->get_date() : 0.0;
280 void ActorImpl::yield()
282 XBT_DEBUG("Yield actor '%s'", get_cname());
284 /* Go into sleep and return control to maestro */
287 /* Ok, maestro returned control to us */
288 XBT_DEBUG("Control returned to me: '%s'", get_cname());
290 if (context_->wannadie()) {
291 XBT_DEBUG("Actor %s@%s is dead", get_cname(), host_->get_cname());
297 XBT_DEBUG("Hey! I'm suspended.");
298 xbt_assert(exception_ == nullptr, "Gasp! This exception may be lost by subsequent calls.");
299 yield(); // Yield back to maestro without proceeding with my execution. I'll get rescheduled by resume()
302 if (exception_ != nullptr) {
303 XBT_DEBUG("Wait, maestro left me an exception");
304 std::exception_ptr exception = std::move(exception_);
305 exception_ = nullptr;
307 std::rethrow_exception(std::move(exception));
308 } catch (const simgrid::Exception& e) {
309 e.rethrow_nested(XBT_THROW_POINT, boost::core::demangle(typeid(e).name()) + " raised in kernel mode.");
315 smpi_switch_data_segment(get_iface());
319 /** This actor will be terminated automatically when the last non-daemon actor finishes */
320 void ActorImpl::daemonize()
324 EngineImpl::get_instance()->add_daemon(this);
328 void ActorImpl::undaemonize()
332 EngineImpl::get_instance()->remove_daemon(this);
336 s4u::Actor* ActorImpl::restart()
338 xbt_assert(not simix_global->is_maestro(this), "Restarting maestro is not supported");
340 XBT_DEBUG("Restarting actor %s on %s", get_cname(), host_->get_cname());
342 // retrieve the arguments of the old actor
343 ProcessArg arg(host_, this);
345 // kill the old actor
346 context::Context::self()->get_actor()->kill(this);
348 // start the new actor
349 ActorImplPtr actor = ActorImpl::create(arg.name, arg.code, arg.data, arg.host, nullptr);
350 actor->set_properties(arg.properties);
351 *actor->on_exit = std::move(*arg.on_exit);
352 actor->set_kill_time(arg.kill_time);
353 actor->set_auto_restart(arg.auto_restart);
355 return actor->get_ciface();
358 void ActorImpl::suspend()
361 XBT_DEBUG("Actor '%s' is already suspended", get_cname());
367 /* Suspend the activities associated with this actor. */
368 for (auto const& activity : activities_)
372 void ActorImpl::resume()
374 XBT_IN("actor = %p", this);
376 if (context_->wannadie()) {
377 XBT_VERB("Ignoring request to suspend an actor that is currently dying.");
385 /* resume the activities that were blocked when suspending the actor. */
386 for (auto const& activity : activities_)
388 if (not waiting_synchro_) // Reschedule the actor if it was forcefully unscheduled in yield()
389 EngineImpl::get_instance()->add_actor_to_run_list_no_check(this);
394 activity::ActivityImplPtr ActorImpl::join(const ActorImpl* actor, double timeout)
396 activity::ActivityImplPtr sleep = this->sleep(timeout);
397 actor->on_exit->emplace_back([sleep](bool) {
398 if (sleep->surf_action_)
399 sleep->surf_action_->finish(resource::Action::State::FINISHED);
404 activity::ActivityImplPtr ActorImpl::sleep(double duration)
406 if (not host_->is_on())
407 throw_exception(std::make_exception_ptr(HostFailureException(
408 XBT_THROW_POINT, std::string("Host ") + host_->get_cname() + " failed, you cannot sleep there.")));
410 auto sleep = new activity::SleepImpl();
411 sleep->set_name("sleep").set_host(host_).set_duration(duration).start();
412 return activity::SleepImplPtr(sleep);
415 void ActorImpl::throw_exception(std::exception_ptr e)
422 /* cancel the blocking synchro if any */
423 if (waiting_synchro_) {
424 waiting_synchro_->cancel();
425 activities_.remove(waiting_synchro_);
426 waiting_synchro_ = nullptr;
430 void ActorImpl::simcall_answer()
432 if (not simix_global->is_maestro(this)) {
433 XBT_DEBUG("Answer simcall %s issued by %s (%p)", SIMIX_simcall_name(simcall_), get_cname(), this);
434 xbt_assert(simcall_.call_ != simix::Simcall::NONE);
435 simcall_.call_ = simix::Simcall::NONE;
436 auto* engine = EngineImpl::get_instance();
437 const auto& actors_to_run = engine->get_actors_to_run();
438 xbt_assert(not XBT_LOG_ISENABLED(simix_process, xbt_log_priority_debug) ||
439 std::find(begin(actors_to_run), end(actors_to_run), this) == end(actors_to_run),
440 "Actor %p should not exist in actors_to_run!", this);
441 engine->add_actor_to_run_list_no_check(this);
445 void ActorImpl::set_host(s4u::Host* dest)
447 host_->get_impl()->remove_actor(this);
449 dest->get_impl()->add_actor(this);
452 ActorImplPtr ActorImpl::init(const std::string& name, s4u::Host* host) const
454 auto* actor = new ActorImpl(xbt::string(name), host);
455 actor->set_ppid(this->pid_);
457 intrusive_ptr_add_ref(actor);
458 /* The on_creation() signal must be delayed until there, where the pid and everything is set */
459 s4u::Actor::on_creation(*actor->get_ciface());
461 return ActorImplPtr(actor);
464 ActorImpl* ActorImpl::start(const ActorCode& code)
466 xbt_assert(code && host_ != nullptr, "Invalid parameters");
467 auto* engine = EngineImpl::get_instance();
469 if (not host_->is_on()) {
470 XBT_WARN("Cannot launch actor '%s' on failed host '%s'", name_.c_str(), host_->get_cname());
471 intrusive_ptr_release(this);
472 throw HostFailureException(XBT_THROW_POINT, "Cannot start actor on failed host.");
476 XBT_VERB("Create context %s", get_cname());
477 context_.reset(simix_global->get_context_factory()->create_context(ActorCode(code), this));
479 XBT_DEBUG("Start context '%s'", get_cname());
481 /* Add the actor to its host's actor list */
482 host_->get_impl()->add_actor(this);
483 engine->add_actor(pid_, this);
485 /* Now insert it in the global actor list and in the actor to run list */
486 engine->add_actor_to_run_list_no_check(this);
491 ActorImplPtr ActorImpl::create(const std::string& name, const ActorCode& code, void* data, s4u::Host* host,
492 const ActorImpl* parent_actor)
494 XBT_DEBUG("Start actor %s@'%s'", name.c_str(), host->get_cname());
497 if (parent_actor != nullptr)
498 actor = parent_actor->init(xbt::string(name), host);
500 actor = self()->init(xbt::string(name), host);
503 actor->set_user_data(data);
510 void create_maestro(const std::function<void()>& code)
512 /* Create maestro actor and initialize it */
513 auto* maestro = new ActorImpl(xbt::string(""), /*host*/ nullptr);
516 maestro->context_.reset(simix_global->get_context_factory()->create_context(ActorCode(), maestro));
518 maestro->context_.reset(simix_global->get_context_factory()->create_maestro(ActorCode(code), maestro));
521 maestro->simcall_.issuer_ = maestro;
522 simix_global->set_maestro(maestro);
526 } // namespace kernel
527 } // namespace simgrid
529 int SIMIX_process_count() // XBT_ATTRIB_DEPRECATED_v329
531 return simgrid::kernel::EngineImpl::get_instance()->get_actor_list().size();
534 void* SIMIX_process_self_get_data() // XBT_ATTRIB_DEPRECATED_v329
536 smx_actor_t self = simgrid::kernel::actor::ActorImpl::self();
538 if (self == nullptr) {
541 return self->get_user_data();
544 void SIMIX_process_self_set_data(void* data) // XBT_ATTRIB_DEPRECATED_v329
546 simgrid::kernel::actor::ActorImpl::self()->set_user_data(data);
549 /* needs to be public and without simcall because it is called
550 by exceptions and logging events */
551 const char* SIMIX_process_self_get_name()
553 return SIMIX_is_maestro() ? "maestro" : simgrid::kernel::actor::ActorImpl::self()->get_cname();
556 /** @brief Returns the process from PID. */
557 smx_actor_t SIMIX_process_from_PID(aid_t pid)
559 return simgrid::kernel::actor::ActorImpl::by_pid(pid);
562 void SIMIX_process_on_exit(smx_actor_t actor,
563 const std::function<void(bool /*failed*/)>& fun) // XBT_ATTRIB_DEPRECATED_v329
565 xbt_assert(actor, "current process not found: are you in maestro context ?");
566 actor->on_exit->emplace_back(fun);
569 void simcall_process_set_data(smx_actor_t process, void* data) // XBT_ATTRIB_DEPRECATED_v329
571 simgrid::kernel::actor::simcall([process, data] { process->set_user_data(data); });