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. */
7 #include "simgrid/Exception.hpp"
8 #include "simgrid/s4u/Actor.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"
19 #include "src/surf/HostImpl.hpp"
20 #include "src/surf/cpu_interface.hpp"
22 #include <boost/core/demangle.hpp>
26 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(simix_process, simix, "Logging specific to SIMIX (process)");
29 * @brief Returns the current agent.
31 * This functions returns the currently running SIMIX process.
33 * @return The SIMIX process
35 smx_actor_t SIMIX_process_self()
37 return simgrid::kernel::actor::ActorImpl::self();
44 static unsigned long maxpid = 0;
45 unsigned long get_maxpid()
49 unsigned long* get_maxpid_addr()
53 ActorImpl* ActorImpl::by_pid(aid_t pid)
55 return EngineImpl::get_instance()->get_actor_by_pid(pid);
58 ActorImpl* ActorImpl::self()
60 const context::Context* self_context = context::Context::self();
62 return (self_context != nullptr) ? self_context->get_actor() : nullptr;
65 ActorImpl::ActorImpl(xbt::string name, s4u::Host* host) : host_(host), name_(std::move(name)), piface_(this)
68 simcall_.issuer_ = this;
69 stacksize_ = smx_context_stack_size;
72 ActorImpl::~ActorImpl()
74 if (simix_global != nullptr && not simix_global->is_maestro(this))
75 s4u::Actor::on_destruction(*get_ciface());
78 /* Become an actor in the simulation
80 * Currently this can only be called by the main thread (once) and only work with some thread factories
81 * (currently ThreadContextFactory).
83 * In the future, it might be extended in order to attach other threads created by a third party library.
86 ActorImplPtr ActorImpl::attach(const std::string& name, void* data, s4u::Host* host)
88 // This is mostly a copy/paste from create(), it'd be nice to share some code between those two functions.
89 auto* engine = EngineImpl::get_instance();
90 XBT_DEBUG("Attach actor %s on host '%s'", name.c_str(), host->get_cname());
92 if (not host->is_on()) {
93 XBT_WARN("Cannot attach actor '%s' on failed host '%s'", name.c_str(), host->get_cname());
94 throw HostFailureException(XBT_THROW_POINT, "Cannot attach actor on failed host.");
97 auto* actor = new ActorImpl(xbt::string(name), host);
99 actor->set_user_data(data);
100 actor->code_ = nullptr;
102 XBT_VERB("Create context %s", actor->get_cname());
103 xbt_assert(simix_global != nullptr, "simix is not initialized, please call MSG_init first");
104 actor->context_.reset(simix_global->get_context_factory()->attach(actor));
106 /* Add the actor to it's host actor list */
107 host->get_impl()->add_actor(actor);
109 /* Now insert it in the global actor list and in the actors to run list */
110 engine->add_actor(actor->get_pid(), actor);
111 engine->add_actor_to_run_list_no_check(actor);
112 intrusive_ptr_add_ref(actor);
114 auto* context = dynamic_cast<context::AttachContext*>(actor->context_.get());
115 xbt_assert(nullptr != context, "Not a suitable context");
116 context->attach_start();
118 /* The on_creation() signal must be delayed until there, where the pid and everything is set */
119 s4u::Actor::on_creation(*actor->get_ciface());
121 return ActorImplPtr(actor);
123 /** @brief Detach an actor attached with `attach()`
125 * This is called when the current actor has finished its job.
126 * Used in the main thread, it waits for the simulation to finish before returning. When it returns, the other
127 * simulated actors and the maestro are destroyed.
129 void ActorImpl::detach()
131 auto* context = dynamic_cast<context::AttachContext*>(context::Context::self());
132 xbt_assert(context != nullptr, "Not a suitable context");
134 context->get_actor()->cleanup();
135 context->attach_stop();
138 void ActorImpl::cleanup_from_simix()
140 auto* engine = EngineImpl::get_instance();
141 const std::lock_guard<std::mutex> lock(engine->get_mutex());
142 engine->remove_actor(pid_);
143 if (host_ && host_actor_list_hook.is_linked())
144 host_->get_impl()->remove_actor(this);
145 if (not kernel_destroy_list_hook.is_linked()) {
147 engine->add_dead_actor_to_dynar(this);
149 engine->add_actor_to_destroy_list(*this);
153 void ActorImpl::cleanup()
157 if (has_to_auto_restart() && not get_host()->is_on()) {
158 XBT_DEBUG("Insert host %s to watched_hosts because it's off and %s needs to restart", get_host()->get_cname(),
160 watched_hosts().insert(get_host()->get_name());
164 // Execute the termination callbacks
165 bool failed = context_->wannadie();
166 for (auto exit_fun = on_exit->crbegin(); exit_fun != on_exit->crend(); ++exit_fun)
172 /* cancel non-blocking activities */
173 for (auto activity : activities_)
177 XBT_DEBUG("%s@%s(%ld) should not run anymore", get_cname(), get_host()->get_cname(), get_pid());
179 if (simix_global->is_maestro(this)) /* Do not cleanup maestro */
182 XBT_DEBUG("Cleanup actor %s (%p), waiting synchro %p", get_cname(), this, waiting_synchro_.get());
184 /* Unregister associated timers if any */
185 if (kill_timer_ != nullptr) {
186 kill_timer_->remove();
187 kill_timer_ = nullptr;
189 if (simcall_.timeout_cb_) {
190 simcall_.timeout_cb_->remove();
191 simcall_.timeout_cb_ = nullptr;
194 cleanup_from_simix();
196 context_->set_wannadie(false); // don't let the simcall's yield() do a Context::stop(), to avoid infinite loops
197 actor::simcall([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 (waiting_synchro_ != nullptr) {
209 waiting_synchro_->cancel();
210 waiting_synchro_->state_ = activity::State::FAILED;
212 activity::ExecImplPtr exec = boost::dynamic_pointer_cast<activity::ExecImpl>(waiting_synchro_);
213 activity::CommImplPtr comm = boost::dynamic_pointer_cast<activity::CommImpl>(waiting_synchro_);
215 if (exec != nullptr) {
216 exec->clean_action();
217 } else if (comm != nullptr) {
218 comm->unregister_simcall(&simcall_);
220 activity::ActivityImplPtr(waiting_synchro_)->finish();
223 activities_.remove(waiting_synchro_);
224 waiting_synchro_ = nullptr;
226 for (auto const& activity : activities_)
230 // Forcefully kill the actor if its host is turned off. Not a HostFailureException because you should not survive that
231 this->throw_exception(std::make_exception_ptr(ForcefulKillException(host_->is_on() ? "exited" : "host failed")));
234 void ActorImpl::kill(ActorImpl* actor) const
236 xbt_assert(not simix_global->is_maestro(actor), "Killing maestro is a rather bad idea");
237 if (actor->finished_) {
238 XBT_DEBUG("Ignoring request to kill actor %s@%s that is already dead", actor->get_cname(),
239 actor->host_->get_cname());
243 XBT_DEBUG("Actor '%s'@%s is killing actor '%s'@%s", get_cname(), host_ ? host_->get_cname() : "", actor->get_cname(),
244 actor->host_ ? actor->host_->get_cname() : "");
249 XBT_DEBUG("Go on, this is a suicide,");
251 EngineImpl::get_instance()->add_actor_to_run_list(actor);
254 void ActorImpl::kill_all() const
256 for (auto const& kv : EngineImpl::get_instance()->get_actor_list())
257 if (kv.second != this)
258 this->kill(kv.second);
261 void ActorImpl::set_kill_time(double kill_time)
263 if (kill_time <= SIMIX_get_clock())
265 XBT_DEBUG("Set kill time %f for actor %s@%s", kill_time, get_cname(), host_->get_cname());
266 kill_timer_ = timer::Timer::set(kill_time, [this] {
268 kill_timer_ = nullptr;
272 double ActorImpl::get_kill_time() const
274 return kill_timer_ ? kill_timer_->get_date() : 0.0;
277 void ActorImpl::yield()
279 XBT_DEBUG("Yield actor '%s'", get_cname());
281 /* Go into sleep and return control to maestro */
284 /* Ok, maestro returned control to us */
285 XBT_DEBUG("Control returned to me: '%s'", get_cname());
287 if (context_->wannadie()) {
288 XBT_DEBUG("Actor %s@%s is dead", get_cname(), host_->get_cname());
294 XBT_DEBUG("Hey! I'm suspended.");
295 xbt_assert(exception_ == nullptr, "Gasp! This exception may be lost by subsequent calls.");
296 yield(); // Yield back to maestro without proceeding with my execution. I'll get rescheduled by resume()
299 if (exception_ != nullptr) {
300 XBT_DEBUG("Wait, maestro left me an exception");
301 std::exception_ptr exception = std::move(exception_);
302 exception_ = nullptr;
304 std::rethrow_exception(std::move(exception));
305 } catch (const simgrid::Exception& e) {
306 e.rethrow_nested(XBT_THROW_POINT, boost::core::demangle(typeid(e).name()) + " raised in kernel mode.");
310 if (SMPI_switch_data_segment && not finished_) {
311 SMPI_switch_data_segment(get_iface());
315 /** This actor will be terminated automatically when the last non-daemon actor finishes */
316 void ActorImpl::daemonize()
320 EngineImpl::get_instance()->add_daemon(this);
324 void ActorImpl::undaemonize()
328 EngineImpl::get_instance()->remove_daemon(this);
332 s4u::Actor* ActorImpl::restart()
334 xbt_assert(not simix_global->is_maestro(this), "Restarting maestro is not supported");
336 XBT_DEBUG("Restarting actor %s on %s", get_cname(), host_->get_cname());
338 // retrieve the arguments of the old actor
339 ProcessArg arg(host_, this);
341 // kill the old actor
342 context::Context::self()->get_actor()->kill(this);
344 // start the new actor
345 ActorImplPtr actor = ActorImpl::create(arg.name, arg.code, arg.data, arg.host, nullptr);
346 actor->set_properties(arg.properties);
347 *actor->on_exit = std::move(*arg.on_exit);
348 actor->set_kill_time(arg.kill_time);
349 actor->set_auto_restart(arg.auto_restart);
351 return actor->get_ciface();
354 void ActorImpl::suspend()
357 XBT_DEBUG("Actor '%s' is already suspended", get_cname());
363 /* Suspend the activities associated with this actor. */
364 for (auto const& activity : activities_)
368 void ActorImpl::resume()
370 XBT_IN("actor = %p", this);
372 if (context_->wannadie()) {
373 XBT_VERB("Ignoring request to suspend an actor that is currently dying.");
381 /* resume the activities that were blocked when suspending the actor. */
382 for (auto const& activity : activities_)
384 if (not waiting_synchro_) // Reschedule the actor if it was forcefully unscheduled in yield()
385 EngineImpl::get_instance()->add_actor_to_run_list_no_check(this);
390 activity::ActivityImplPtr ActorImpl::join(const ActorImpl* actor, double timeout)
392 activity::ActivityImplPtr sleep = this->sleep(timeout);
393 actor->on_exit->emplace_back([sleep](bool) {
394 if (sleep->surf_action_)
395 sleep->surf_action_->finish(resource::Action::State::FINISHED);
400 activity::ActivityImplPtr ActorImpl::sleep(double duration)
402 if (not host_->is_on())
403 throw_exception(std::make_exception_ptr(HostFailureException(
404 XBT_THROW_POINT, std::string("Host ") + host_->get_cname() + " failed, you cannot sleep there.")));
406 auto sleep = new activity::SleepImpl();
407 sleep->set_name("sleep").set_host(host_).set_duration(duration).start();
408 return activity::SleepImplPtr(sleep);
411 void ActorImpl::throw_exception(std::exception_ptr e)
418 /* cancel the blocking synchro if any */
419 if (waiting_synchro_) {
420 waiting_synchro_->cancel();
421 activities_.remove(waiting_synchro_);
422 waiting_synchro_ = nullptr;
426 void ActorImpl::simcall_answer()
428 if (not simix_global->is_maestro(this)) {
429 XBT_DEBUG("Answer simcall %s issued by %s (%p)", SIMIX_simcall_name(simcall_), get_cname(), this);
430 xbt_assert(simcall_.call_ != simix::Simcall::NONE);
431 simcall_.call_ = simix::Simcall::NONE;
432 auto* engine = EngineImpl::get_instance();
433 const auto& actors_to_run = engine->get_actors_to_run();
434 xbt_assert(not XBT_LOG_ISENABLED(simix_process, xbt_log_priority_debug) ||
435 std::find(begin(actors_to_run), end(actors_to_run), this) == end(actors_to_run),
436 "Actor %p should not exist in actors_to_run!", this);
437 engine->add_actor_to_run_list_no_check(this);
441 void ActorImpl::set_host(s4u::Host* dest)
443 host_->get_impl()->remove_actor(this);
445 dest->get_impl()->add_actor(this);
448 ActorImplPtr ActorImpl::init(const std::string& name, s4u::Host* host) const
450 auto* actor = new ActorImpl(xbt::string(name), host);
451 actor->set_ppid(this->pid_);
453 intrusive_ptr_add_ref(actor);
454 /* The on_creation() signal must be delayed until there, where the pid and everything is set */
455 s4u::Actor::on_creation(*actor->get_ciface());
457 return ActorImplPtr(actor);
460 ActorImpl* ActorImpl::start(const ActorCode& code)
462 xbt_assert(code && host_ != nullptr, "Invalid parameters");
463 auto* engine = EngineImpl::get_instance();
465 if (not host_->is_on()) {
466 XBT_WARN("Cannot launch actor '%s' on failed host '%s'", name_.c_str(), host_->get_cname());
467 intrusive_ptr_release(this);
468 throw HostFailureException(XBT_THROW_POINT, "Cannot start actor on failed host.");
472 XBT_VERB("Create context %s", get_cname());
473 context_.reset(simix_global->get_context_factory()->create_context(ActorCode(code), this));
475 XBT_DEBUG("Start context '%s'", get_cname());
477 /* Add the actor to its host's actor list */
478 host_->get_impl()->add_actor(this);
479 engine->add_actor(pid_, this);
481 /* Now insert it in the global actor list and in the actor to run list */
482 engine->add_actor_to_run_list_no_check(this);
487 ActorImplPtr ActorImpl::create(const std::string& name, const ActorCode& code, void* data, s4u::Host* host,
488 const ActorImpl* parent_actor)
490 XBT_DEBUG("Start actor %s@'%s'", name.c_str(), host->get_cname());
493 if (parent_actor != nullptr)
494 actor = parent_actor->init(xbt::string(name), host);
496 actor = self()->init(xbt::string(name), host);
499 actor->set_user_data(data);
506 void create_maestro(const std::function<void()>& code)
508 /* Create maestro actor and initialize it */
509 auto* maestro = new ActorImpl(xbt::string(""), /*host*/ nullptr);
512 maestro->context_.reset(simix_global->get_context_factory()->create_context(ActorCode(), maestro));
514 maestro->context_.reset(simix_global->get_context_factory()->create_maestro(ActorCode(code), maestro));
517 maestro->simcall_.issuer_ = maestro;
518 simix_global->set_maestro(maestro);
522 } // namespace kernel
523 } // namespace simgrid
525 int SIMIX_process_count() // XBT_ATTRIB_DEPRECATED_v329
527 return simgrid::kernel::EngineImpl::get_instance()->get_actor_list().size();
530 void* SIMIX_process_self_get_data() // XBT_ATTRIB_DEPRECATED_v329
532 smx_actor_t self = simgrid::kernel::actor::ActorImpl::self();
534 if (self == nullptr) {
537 return self->get_user_data();
540 void SIMIX_process_self_set_data(void* data) // XBT_ATTRIB_DEPRECATED_v329
542 simgrid::kernel::actor::ActorImpl::self()->set_user_data(data);
545 /* needs to be public and without simcall because it is called
546 by exceptions and logging events */
547 const char* SIMIX_process_self_get_name()
549 return SIMIX_is_maestro() ? "maestro" : simgrid::kernel::actor::ActorImpl::self()->get_cname();
552 /** @brief Returns the process from PID. */
553 smx_actor_t SIMIX_process_from_PID(aid_t pid)
555 return simgrid::kernel::actor::ActorImpl::by_pid(pid);
558 void SIMIX_process_on_exit(smx_actor_t actor,
559 const std::function<void(bool /*failed*/)>& fun) // XBT_ATTRIB_DEPRECATED_v329
561 xbt_assert(actor, "current process not found: are you in maestro context ?");
562 actor->on_exit->emplace_back(fun);
565 void simcall_process_set_data(smx_actor_t process, void* data) // XBT_ATTRIB_DEPRECATED_v329
567 simgrid::kernel::actor::simcall([process, data] { process->set_user_data(data); });