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");
23 * @brief Returns the current agent.
25 * This functions returns the currently running SIMIX process.
27 * @return The SIMIX process
29 smx_actor_t SIMIX_process_self() // XBT_ATTRIB_DEPRECATED_v333
31 return simgrid::kernel::actor::ActorImpl::self();
38 static unsigned long maxpid = 0;
39 unsigned long get_maxpid()
43 unsigned long* get_maxpid_addr()
47 ActorImpl* ActorImpl::by_pid(aid_t pid)
49 return EngineImpl::get_instance()->get_actor_by_pid(pid);
52 ActorImpl* ActorImpl::self()
54 const context::Context* self_context = context::Context::self();
56 return (self_context != nullptr) ? self_context->get_actor() : nullptr;
59 ActorImpl::ActorImpl(xbt::string name, s4u::Host* host) : host_(host), name_(std::move(name)), piface_(this)
62 simcall_.issuer_ = this;
63 stacksize_ = context::stack_size;
66 ActorImpl::~ActorImpl()
68 if (EngineImpl::has_instance() && not EngineImpl::get_instance()->is_maestro(this))
69 s4u::Actor::on_destruction(*get_ciface());
72 /* Become an actor in the simulation
74 * Currently this can only be called by the main thread (once) and only work with some thread factories
75 * (currently ThreadContextFactory).
77 * In the future, it might be extended in order to attach other threads created by a third party library.
80 ActorImplPtr ActorImpl::attach(const std::string& name, void* data, s4u::Host* host)
82 // This is mostly a copy/paste from create(), it'd be nice to share some code between those two functions.
83 auto* engine = EngineImpl::get_instance();
84 XBT_DEBUG("Attach actor %s on host '%s'", name.c_str(), host->get_cname());
86 if (not host->is_on()) {
87 XBT_WARN("Cannot attach actor '%s' on failed host '%s'", name.c_str(), host->get_cname());
88 throw HostFailureException(XBT_THROW_POINT, "Cannot attach actor on failed host.");
91 auto* actor = new ActorImpl(xbt::string(name), host);
93 actor->piface_.set_data(data);
94 actor->code_ = nullptr;
96 XBT_VERB("Create context %s", actor->get_cname());
97 actor->context_.reset(engine->get_context_factory()->attach(actor));
99 /* Add the actor to it's host actor list */
100 host->get_impl()->add_actor(actor);
102 /* Now insert it in the global actor list and in the actors to run list */
103 engine->add_actor(actor->get_pid(), actor);
104 engine->add_actor_to_run_list_no_check(actor);
105 intrusive_ptr_add_ref(actor);
107 auto* context = dynamic_cast<context::AttachContext*>(actor->context_.get());
108 xbt_assert(nullptr != context, "Not a suitable context");
109 context->attach_start();
111 /* The on_creation() signal must be delayed until there, where the pid and everything is set */
112 s4u::Actor::on_creation(*actor->get_ciface());
114 return ActorImplPtr(actor);
116 /** @brief Detach an actor attached with `attach()`
118 * This is called when the current actor has finished its job.
119 * Used in the main thread, it waits for the simulation to finish before returning. When it returns, the other
120 * simulated actors and the maestro are destroyed.
122 void ActorImpl::detach()
124 auto* context = dynamic_cast<context::AttachContext*>(context::Context::self());
125 xbt_assert(context != nullptr, "Not a suitable context");
127 context->get_actor()->cleanup();
128 context->attach_stop();
131 /** Whether this actor is actually maestro */
132 bool ActorImpl::is_maestro() const
134 return context_->is_maestro();
137 void ActorImpl::cleanup_from_simix()
139 auto* engine = EngineImpl::get_instance();
140 const std::lock_guard<std::mutex> lock(engine->get_mutex());
141 engine->remove_actor(pid_);
142 if (host_ && host_actor_list_hook.is_linked())
143 host_->get_impl()->remove_actor(this);
144 if (not kernel_destroy_list_hook.is_linked())
145 engine->add_actor_to_destroy_list(*this);
148 void ActorImpl::cleanup()
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());
159 // Execute the termination callbacks
160 bool failed = context_->wannadie();
161 for (auto exit_fun = on_exit->crbegin(); exit_fun != on_exit->crend(); ++exit_fun)
167 /* cancel non-blocking activities */
168 for (auto activity : activities_)
172 XBT_DEBUG("%s@%s(%ld) should not run anymore", get_cname(), get_host()->get_cname(), get_pid());
174 if (EngineImpl::get_instance()->is_maestro(this)) /* Do not cleanup maestro */
177 XBT_DEBUG("Cleanup actor %s (%p), waiting synchro %p", get_cname(), this, waiting_synchro_.get());
179 /* Unregister associated timers if any */
180 if (kill_timer_ != nullptr) {
181 kill_timer_->remove();
182 kill_timer_ = nullptr;
184 if (simcall_.timeout_cb_) {
185 simcall_.timeout_cb_->remove();
186 simcall_.timeout_cb_ = nullptr;
189 cleanup_from_simix();
191 context_->set_wannadie(false); // don't let the simcall's yield() do a Context::stop(), to avoid infinite loops
192 actor::simcall_answered([this] { s4u::Actor::on_termination(*get_ciface()); });
193 context_->set_wannadie();
196 void ActorImpl::exit()
198 context_->set_wannadie();
200 exception_ = nullptr;
202 /* destroy the blocking synchro if any */
203 if (waiting_synchro_ != nullptr) {
204 waiting_synchro_->cancel();
205 waiting_synchro_->set_state(activity::State::FAILED);
207 if (auto exec = boost::dynamic_pointer_cast<activity::ExecImpl>(waiting_synchro_)) {
208 exec->clean_action();
209 } else if (auto comm = boost::dynamic_pointer_cast<activity::CommImpl>(waiting_synchro_)) {
210 comm->unregister_simcall(&simcall_);
212 waiting_synchro_->finish();
215 activities_.remove(waiting_synchro_);
216 waiting_synchro_ = nullptr;
218 for (auto const& activity : activities_)
222 // Forcefully kill the actor if its host is turned off. Not a HostFailureException because you should not survive that
223 this->throw_exception(std::make_exception_ptr(ForcefulKillException(host_->is_on() ? "exited" : "host failed")));
226 void ActorImpl::kill(ActorImpl* actor) const
228 xbt_assert(not actor->is_maestro(), "Killing maestro is a rather bad idea.");
229 if (actor->finished_) {
230 XBT_DEBUG("Ignoring request to kill actor %s@%s that is already dead", actor->get_cname(),
231 actor->host_->get_cname());
235 XBT_DEBUG("Actor '%s'@%s is killing actor '%s'@%s", get_cname(), host_ ? host_->get_cname() : "", actor->get_cname(),
236 actor->host_ ? actor->host_->get_cname() : "");
241 XBT_DEBUG("Go on, this is a suicide,");
243 EngineImpl::get_instance()->add_actor_to_run_list(actor);
246 void ActorImpl::kill_all() const
248 for (auto const& kv : EngineImpl::get_instance()->get_actor_list())
249 if (kv.second != this)
250 this->kill(kv.second);
253 void ActorImpl::set_kill_time(double kill_time)
255 if (kill_time <= s4u::Engine::get_clock())
257 XBT_DEBUG("Set kill time %f for actor %s@%s", kill_time, get_cname(), host_->get_cname());
258 kill_timer_ = timer::Timer::set(kill_time, [this] {
260 kill_timer_ = nullptr;
264 double ActorImpl::get_kill_time() const
266 return kill_timer_ ? kill_timer_->get_date() : 0.0;
269 void ActorImpl::yield()
271 XBT_DEBUG("Yield actor '%s'", get_cname());
273 /* Go into sleep and return control to maestro */
275 /* Ok, maestro returned control to us */
276 XBT_DEBUG("Control returned to me: '%s'", get_cname());
278 if (context_->wannadie()) {
279 XBT_DEBUG("Actor %s@%s is dead", get_cname(), host_->get_cname());
285 XBT_DEBUG("Hey! I'm suspended.");
286 xbt_assert(exception_ == nullptr, "Gasp! This exception may be lost by subsequent calls.");
287 yield(); // Yield back to maestro without proceeding with my execution. I'll get rescheduled by resume()
290 if (exception_ != nullptr) {
291 XBT_DEBUG("Wait, maestro left me an exception");
292 std::exception_ptr exception = std::move(exception_);
293 exception_ = nullptr;
295 std::rethrow_exception(std::move(exception));
296 } catch (const simgrid::Exception& e) {
297 e.rethrow_nested(XBT_THROW_POINT, boost::core::demangle(typeid(e).name()) + " raised in kernel mode.");
302 smpi_switch_data_segment(get_iface());
306 /** This actor will be terminated automatically when the last non-daemon actor finishes */
307 void ActorImpl::daemonize()
311 EngineImpl::get_instance()->add_daemon(this);
315 void ActorImpl::undaemonize()
319 EngineImpl::get_instance()->remove_daemon(this);
323 s4u::Actor* ActorImpl::restart()
325 xbt_assert(not this->is_maestro(), "Restarting maestro is not supported");
327 XBT_DEBUG("Restarting actor %s on %s", get_cname(), host_->get_cname());
329 // retrieve the arguments of the old actor
330 ProcessArg arg(host_, this);
332 // kill the old actor
333 context::Context::self()->get_actor()->kill(this);
335 // start the new actor
336 ActorImplPtr actor = ActorImpl::create(arg.name, arg.code, arg.data, arg.host, nullptr);
337 actor->set_properties(arg.properties);
338 *actor->on_exit = std::move(*arg.on_exit);
339 actor->set_kill_time(arg.kill_time);
340 actor->set_auto_restart(arg.auto_restart);
342 return actor->get_ciface();
345 void ActorImpl::suspend()
348 XBT_DEBUG("Actor '%s' is already suspended", get_cname());
354 /* Suspend the activities associated with this actor. */
355 for (auto const& activity : activities_)
359 void ActorImpl::resume()
361 XBT_IN("actor = %p", this);
363 if (context_->wannadie()) {
364 XBT_VERB("Ignoring request to suspend an actor that is currently dying.");
372 /* resume the activities that were blocked when suspending the actor. */
373 for (auto const& activity : activities_)
375 if (not waiting_synchro_) // Reschedule the actor if it was forcefully unscheduled in yield()
376 EngineImpl::get_instance()->add_actor_to_run_list_no_check(this);
381 activity::ActivityImplPtr ActorImpl::join(const ActorImpl* actor, double timeout)
383 activity::ActivityImplPtr sleep = this->sleep(timeout);
384 actor->on_exit->emplace_back([sleep](bool) {
385 if (sleep->surf_action_)
386 sleep->surf_action_->finish(resource::Action::State::FINISHED);
391 activity::ActivityImplPtr ActorImpl::sleep(double duration)
393 if (not host_->is_on())
394 throw_exception(std::make_exception_ptr(HostFailureException(
395 XBT_THROW_POINT, std::string("Host ") + host_->get_cname() + " failed, you cannot sleep there.")));
397 auto sleep = new activity::SleepImpl();
398 sleep->set_name("sleep").set_host(host_).set_duration(duration).start();
399 return activity::SleepImplPtr(sleep);
402 void ActorImpl::throw_exception(std::exception_ptr e)
409 /* cancel the blocking synchro if any */
410 if (waiting_synchro_) {
411 waiting_synchro_->cancel();
412 activities_.remove(waiting_synchro_);
413 waiting_synchro_ = nullptr;
417 void ActorImpl::simcall_answer()
419 auto* engine = EngineImpl::get_instance();
420 if (not this->is_maestro()) {
421 XBT_DEBUG("Answer simcall %s issued by %s (%p)", SIMIX_simcall_name(simcall_), get_cname(), this);
422 xbt_assert(simcall_.call_ != simix::Simcall::NONE);
423 simcall_.call_ = simix::Simcall::NONE;
424 const auto& actors_to_run = engine->get_actors_to_run();
425 xbt_assert(not XBT_LOG_ISENABLED(ker_actor, xbt_log_priority_debug) ||
426 std::find(begin(actors_to_run), end(actors_to_run), this) == end(actors_to_run),
427 "Actor %p should not exist in actors_to_run!", this);
428 engine->add_actor_to_run_list_no_check(this);
432 void ActorImpl::set_host(s4u::Host* dest)
434 host_->get_impl()->remove_actor(this);
436 dest->get_impl()->add_actor(this);
439 ActorImplPtr ActorImpl::init(const std::string& name, s4u::Host* host) const
441 auto* actor = new ActorImpl(xbt::string(name), host);
442 actor->set_ppid(this->pid_);
444 intrusive_ptr_add_ref(actor);
445 /* The on_creation() signal must be delayed until there, where the pid and everything is set */
446 s4u::Actor::on_creation(*actor->get_ciface());
448 return ActorImplPtr(actor);
451 ActorImpl* ActorImpl::start(const ActorCode& code)
453 xbt_assert(code && host_ != nullptr, "Invalid parameters");
454 auto* engine = EngineImpl::get_instance();
456 if (not host_->is_on()) {
457 XBT_WARN("Cannot launch actor '%s' on failed host '%s'", name_.c_str(), host_->get_cname());
458 intrusive_ptr_release(this);
459 throw HostFailureException(XBT_THROW_POINT, "Cannot start actor on failed host.");
463 XBT_VERB("Create context %s", get_cname());
464 context_.reset(engine->get_context_factory()->create_context(ActorCode(code), this));
466 XBT_DEBUG("Start context '%s'", get_cname());
468 /* Add the actor to its host's actor list */
469 host_->get_impl()->add_actor(this);
470 engine->add_actor(pid_, this);
472 /* Now insert it in the global actor list and in the actor to run list */
473 engine->add_actor_to_run_list_no_check(this);
478 ActorImplPtr ActorImpl::create(const std::string& name, const ActorCode& code, void* data, s4u::Host* host,
479 const ActorImpl* parent_actor)
481 XBT_DEBUG("Start actor %s@'%s'", name.c_str(), host->get_cname());
484 if (parent_actor != nullptr)
485 actor = parent_actor->init(xbt::string(name), host);
487 actor = self()->init(xbt::string(name), host);
489 actor->piface_.set_data(data); /* actor data */
496 void create_maestro(const std::function<void()>& code)
498 auto* engine = EngineImpl::get_instance();
499 /* Create maestro actor and initialize it */
500 auto* maestro = new ActorImpl(xbt::string(""), /*host*/ nullptr);
503 maestro->context_.reset(engine->get_context_factory()->create_context(ActorCode(), maestro));
505 maestro->context_.reset(engine->get_context_factory()->create_maestro(ActorCode(code), maestro));
508 maestro->simcall_.issuer_ = maestro;
509 engine->set_maestro(maestro);
513 } // namespace kernel
514 } // namespace simgrid
516 /* needs to be public and without simcall because it is called by exceptions and logging events */
517 const char* SIMIX_process_self_get_name() // XBT_ATTRIB_DEPRECATED_v333
519 return simgrid::s4u::Actor::is_maestro() ? "maestro" : simgrid::kernel::actor::ActorImpl::self()->get_cname();
522 int SIMIX_is_maestro() // XBT_ATTRIB_DEPRECATED_v333
524 const auto* self = simgrid::kernel::actor::ActorImpl::self();
525 return self != nullptr && self->is_maestro();