1 /* Copyright (c) 2007-2020. 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/activity/CommImpl.hpp"
11 #include "src/kernel/activity/ExecImpl.hpp"
12 #include "src/kernel/activity/IoImpl.hpp"
13 #include "src/kernel/activity/SleepImpl.hpp"
14 #include "src/kernel/activity/SynchroRaw.hpp"
15 #include "src/mc/mc_replay.hpp"
16 #include "src/mc/remote/AppSide.hpp"
17 #include "src/simix/smx_private.hpp"
18 #include "src/surf/HostImpl.hpp"
19 #include "src/surf/cpu_interface.hpp"
21 #include <boost/range/algorithm.hpp>
24 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(simix_process, simix, "Logging specific to SIMIX (process)");
27 * @brief Returns the current agent.
29 * This functions returns the currently running SIMIX process.
31 * @return The SIMIX process
33 smx_actor_t SIMIX_process_self()
35 return simgrid::kernel::actor::ActorImpl::self();
42 static unsigned long maxpid = 0;
43 unsigned long get_maxpid()
48 ActorImpl* ActorImpl::self()
50 const context::Context* self_context = context::Context::self();
52 return (self_context != nullptr) ? self_context->get_actor() : nullptr;
55 ActorImpl::ActorImpl(xbt::string name, s4u::Host* host) : host_(host), name_(std::move(name)), piface_(this)
58 simcall_.issuer_ = this;
59 stacksize_ = smx_context_stack_size;
62 ActorImpl::~ActorImpl()
64 if (simix_global != nullptr && this != simix_global->maestro_)
65 s4u::Actor::on_destruction(*get_ciface());
68 /* Become an actor in the simulation
70 * Currently this can only be called by the main thread (once) and only work with some thread factories
71 * (currently ThreadContextFactory).
73 * In the future, it might be extended in order to attach other threads created by a third party library.
76 ActorImplPtr ActorImpl::attach(const std::string& name, void* data, s4u::Host* host,
77 const std::unordered_map<std::string, std::string>* properties)
79 // This is mostly a copy/paste from create(), it'd be nice to share some code between those two functions.
81 XBT_DEBUG("Attach actor %s on host '%s'", name.c_str(), host->get_cname());
83 if (not host->is_on()) {
84 XBT_WARN("Cannot attach actor '%s' on failed host '%s'", name.c_str(), host->get_cname());
85 throw HostFailureException(XBT_THROW_POINT, "Cannot attach actor on failed host.");
88 auto* actor = new ActorImpl(xbt::string(name), host);
90 actor->set_user_data(data);
91 actor->code_ = nullptr;
93 XBT_VERB("Create context %s", actor->get_cname());
94 xbt_assert(simix_global != nullptr, "simix is not initialized, please call MSG_init first");
95 actor->context_.reset(simix_global->context_factory->attach(actor));
98 if (properties != nullptr)
99 actor->set_properties(*properties);
101 /* Add the actor to it's host actor list */
102 host->pimpl_->add_actor(actor);
104 /* Now insert it in the global actor list and in the actors to run list */
105 simix_global->process_list[actor->get_pid()] = actor;
106 XBT_DEBUG("Inserting [%p] %s(%s) in the to_run list", actor, actor->get_cname(), host->get_cname());
107 simix_global->actors_to_run.push_back(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 if (context == nullptr)
129 xbt_die("Not a suitable context");
131 context->get_actor()->cleanup();
132 context->attach_stop();
135 void ActorImpl::cleanup_from_simix()
137 const std::lock_guard<std::mutex> lock(simix_global->mutex);
138 simix_global->process_list.erase(pid_);
139 if (host_ && host_actor_list_hook.is_linked())
140 host_->pimpl_->remove_actor(this);
141 if (not smx_destroy_list_hook.is_linked()) {
143 xbt_dynar_push_as(simix_global->dead_actors_vector, ActorImpl*, this);
145 simix_global->actors_to_destroy.push_back(*this);
149 void ActorImpl::cleanup()
153 if (has_to_auto_restart() && not get_host()->is_on()) {
154 XBT_DEBUG("Insert host %s to watched_hosts because it's off and %s needs to restart", get_host()->get_cname(),
156 watched_hosts.insert(get_host()->get_name());
160 // Execute the termination callbacks
161 bool failed = context_->wannadie();
162 for (auto exit_fun = on_exit->crbegin(); exit_fun != on_exit->crend(); ++exit_fun)
168 /* cancel non-blocking activities */
169 for (auto activity : activities_)
173 XBT_DEBUG("%s@%s(%ld) should not run anymore", get_cname(), get_host()->get_cname(), get_pid());
175 if (this == simix_global->maestro_) /* Do not cleanup maestro */
178 XBT_DEBUG("Cleanup actor %s (%p), waiting synchro %p", get_cname(), this, waiting_synchro_.get());
180 /* Unregister associated timers if any */
181 if (kill_timer_ != nullptr) {
182 kill_timer_->remove();
183 kill_timer_ = nullptr;
185 if (simcall_.timeout_cb_) {
186 simcall_.timeout_cb_->remove();
187 simcall_.timeout_cb_ = nullptr;
190 cleanup_from_simix();
192 context_->set_wannadie(false); // don't let the simcall's yield() do a Context::stop(), to avoid infinite loops
193 actor::simcall([this] { s4u::Actor::on_termination(*get_ciface()); });
194 context_->set_wannadie();
197 void ActorImpl::exit()
199 context_->set_wannadie();
201 exception_ = nullptr;
203 /* destroy the blocking synchro if any */
204 if (waiting_synchro_ != nullptr) {
205 waiting_synchro_->cancel();
206 waiting_synchro_->state_ = activity::State::FAILED;
208 activity::ExecImplPtr exec = boost::dynamic_pointer_cast<activity::ExecImpl>(waiting_synchro_);
209 activity::CommImplPtr comm = boost::dynamic_pointer_cast<activity::CommImpl>(waiting_synchro_);
211 if (exec != nullptr) {
212 exec->clean_action();
213 } else if (comm != nullptr) {
214 // Remove first occurrence of &actor->simcall:
215 auto i = boost::range::find(waiting_synchro_->simcalls_, &simcall_);
216 if (i != waiting_synchro_->simcalls_.end())
217 waiting_synchro_->simcalls_.remove(&simcall_);
219 activity::ActivityImplPtr(waiting_synchro_)->finish();
222 activities_.remove(waiting_synchro_);
223 waiting_synchro_ = nullptr;
226 // Forcefully kill the actor if its host is turned off. Not a HostFailureException because you should not survive that
227 this->throw_exception(std::make_exception_ptr(ForcefulKillException(host_->is_on() ? "exited" : "host failed")));
230 void ActorImpl::kill(ActorImpl* actor) const
232 xbt_assert(actor != simix_global->maestro_, "Killing maestro is a rather bad idea");
233 if (actor->finished_) {
234 XBT_DEBUG("Ignoring request to kill actor %s@%s that is already dead", actor->get_cname(),
235 actor->host_->get_cname());
239 XBT_DEBUG("Actor '%s'@%s is killing actor '%s'@%s", get_cname(), host_ ? host_->get_cname() : "", actor->get_cname(),
240 actor->host_ ? actor->host_->get_cname() : "");
245 XBT_DEBUG("Go on, this is a suicide,");
246 } else if (std::find(begin(simix_global->actors_to_run), end(simix_global->actors_to_run), actor) !=
247 end(simix_global->actors_to_run)) {
248 XBT_DEBUG("Actor %s is already in the to_run list", actor->get_cname());
250 XBT_DEBUG("Inserting %s in the to_run list", actor->get_cname());
251 simix_global->actors_to_run.push_back(actor);
255 void ActorImpl::kill_all() const
257 for (auto const& kv : simix_global->process_list)
258 if (kv.second != this)
259 this->kill(kv.second);
262 void ActorImpl::set_kill_time(double kill_time)
264 if (kill_time <= SIMIX_get_clock())
266 XBT_DEBUG("Set kill time %f for actor %s@%s", kill_time, get_cname(), host_->get_cname());
267 kill_timer_ = simix::Timer::set(kill_time, [this] {
269 kill_timer_ = nullptr;
273 double ActorImpl::get_kill_time() const
275 return kill_timer_ ? kill_timer_->get_date() : 0;
278 void ActorImpl::yield()
280 XBT_DEBUG("Yield actor '%s'", get_cname());
282 /* Go into sleep and return control to maestro */
285 /* Ok, maestro returned control to us */
286 XBT_DEBUG("Control returned to me: '%s'", get_cname());
288 if (context_->wannadie()) {
289 XBT_DEBUG("Actor %s@%s is dead", get_cname(), host_->get_cname());
295 XBT_DEBUG("Hey! I'm suspended.");
297 xbt_assert(exception_ == nullptr, "Gasp! This exception may be lost by subsequent calls.");
299 if (waiting_synchro_ != nullptr) // Not sure of when this will happen. Maybe when suspending early in the SR when a
300 waiting_synchro_->suspend(); // waiting_synchro was terminated
302 yield(); // Yield back to maestro without proceeding with my execution. I'll get rescheduled by resume()
305 if (exception_ != nullptr) {
306 XBT_DEBUG("Wait, maestro left me an exception");
307 std::exception_ptr exception = std::move(exception_);
308 exception_ = nullptr;
309 std::rethrow_exception(std::move(exception));
312 if (SMPI_switch_data_segment && not finished_) {
313 SMPI_switch_data_segment(get_iface());
317 /** This actor will be terminated automatically when the last non-daemon actor finishes */
318 void ActorImpl::daemonize()
322 simix_global->daemons.push_back(this);
326 void ActorImpl::undaemonize()
329 auto& vect = simix_global->daemons;
330 auto it = std::find(vect.begin(), vect.end(), this);
331 xbt_assert(it != vect.end(), "The dying daemon is not a daemon after all. Please report that bug.");
332 /* Don't move the whole content since we don't really care about the order */
334 std::swap(*it, vect.back());
340 s4u::Actor* ActorImpl::restart()
342 xbt_assert(this != simix_global->maestro_, "Restarting maestro is not supported");
344 XBT_DEBUG("Restarting actor %s on %s", get_cname(), host_->get_cname());
346 // retrieve the arguments of the old actor
347 ProcessArg arg = ProcessArg(host_, this);
349 // kill the old actor
350 context::Context::self()->get_actor()->kill(this);
352 // start the new actor
353 ActorImplPtr actor = ActorImpl::create(arg.name, arg.code, arg.data, arg.host, arg.properties.get(), nullptr);
354 *actor->on_exit = std::move(*arg.on_exit);
355 actor->set_kill_time(arg.kill_time);
356 actor->set_auto_restart(arg.auto_restart);
358 return actor->get_ciface();
361 void ActorImpl::suspend()
364 XBT_DEBUG("Actor '%s' is already suspended", get_cname());
370 /* If the suspended actor is waiting on a sync, suspend its synchronization.
371 * Otherwise, it will suspend itself when scheduled, ie, very soon. */
372 if (waiting_synchro_ != nullptr)
373 waiting_synchro_->suspend();
376 void ActorImpl::resume()
378 XBT_IN("actor = %p", this);
380 if (context_->wannadie()) {
381 XBT_VERB("Ignoring request to suspend an actor that is currently dying.");
389 /* resume the activity that was blocking the resumed actor. */
390 if (waiting_synchro_)
391 waiting_synchro_->resume();
392 else // Reschedule the actor if it was forcefully unscheduled in yield()
393 simix_global->actors_to_run.push_back(this);
398 activity::ActivityImplPtr ActorImpl::join(const ActorImpl* actor, double timeout)
400 activity::ActivityImplPtr sleep = this->sleep(timeout);
401 actor->on_exit->emplace_back([sleep](bool) {
402 if (sleep->surf_action_)
403 sleep->surf_action_->finish(resource::Action::State::FINISHED);
408 activity::ActivityImplPtr ActorImpl::sleep(double duration)
410 if (not host_->is_on())
411 throw_exception(std::make_exception_ptr(HostFailureException(
412 XBT_THROW_POINT, std::string("Host ") + host_->get_cname() + " failed, you cannot sleep there.")));
414 auto sleep = new activity::SleepImpl();
415 sleep->set_name("sleep").set_host(host_).set_duration(duration).start();
416 return activity::SleepImplPtr(sleep);
419 void ActorImpl::throw_exception(std::exception_ptr e)
426 /* cancel the blocking synchro if any */
427 if (waiting_synchro_) {
428 waiting_synchro_->cancel();
429 activities_.remove(waiting_synchro_);
430 waiting_synchro_ = nullptr;
434 void ActorImpl::simcall_answer()
436 if (this != simix_global->maestro_) {
437 XBT_DEBUG("Answer simcall %s (%d) issued by %s (%p)", SIMIX_simcall_name(simcall_.call_), (int)simcall_.call_,
439 xbt_assert(simcall_.call_ != simix::Simcall::NONE);
440 simcall_.call_ = simix::Simcall::NONE;
441 xbt_assert(not XBT_LOG_ISENABLED(simix_process, xbt_log_priority_debug) ||
442 std::find(begin(simix_global->actors_to_run), end(simix_global->actors_to_run), this) ==
443 end(simix_global->actors_to_run),
444 "Actor %p should not exist in actors_to_run!", this);
445 simix_global->actors_to_run.push_back(this);
449 void ActorImpl::set_host(s4u::Host* dest)
451 host_->pimpl_->remove_actor(this);
453 dest->pimpl_->add_actor(this);
456 ActorImplPtr ActorImpl::init(const std::string& name, s4u::Host* host) const
458 auto* actor = new ActorImpl(xbt::string(name), host);
459 actor->set_ppid(this->pid_);
461 intrusive_ptr_add_ref(actor);
462 /* The on_creation() signal must be delayed until there, where the pid and everything is set */
463 s4u::Actor::on_creation(*actor->get_ciface());
465 return ActorImplPtr(actor);
468 ActorImpl* ActorImpl::start(const ActorCode& code)
470 xbt_assert(code && host_ != nullptr, "Invalid parameters");
472 if (not host_->is_on()) {
473 XBT_WARN("Cannot launch actor '%s' on failed host '%s'", name_.c_str(), host_->get_cname());
474 intrusive_ptr_release(this);
475 throw HostFailureException(XBT_THROW_POINT, "Cannot start actor on failed host.");
479 XBT_VERB("Create context %s", get_cname());
480 context_.reset(simix_global->context_factory->create_context(ActorCode(code), this));
482 XBT_DEBUG("Start context '%s'", get_cname());
484 /* Add the actor to its host's actor list */
485 host_->pimpl_->add_actor(this);
486 simix_global->process_list[pid_] = this;
488 /* Now insert it in the global actor list and in the actor to run list */
489 XBT_DEBUG("Inserting [%p] %s(%s) in the to_run list", this, get_cname(), host_->get_cname());
490 simix_global->actors_to_run.push_back(this);
495 ActorImplPtr ActorImpl::create(const std::string& name, const ActorCode& code, void* data, s4u::Host* host,
496 const std::unordered_map<std::string, std::string>* properties,
497 const ActorImpl* parent_actor)
499 XBT_DEBUG("Start actor %s@'%s'", name.c_str(), host->get_cname());
502 if (parent_actor != nullptr)
503 actor = parent_actor->init(xbt::string(name), host);
505 actor = self()->init(xbt::string(name), host);
508 actor->set_user_data(data);
511 if (properties != nullptr)
512 actor->set_properties(*properties);
519 void create_maestro(const std::function<void()>& code)
521 /* Create maestro actor and initialize it */
522 auto* maestro = new ActorImpl(xbt::string(""), /*host*/ nullptr);
525 maestro->context_.reset(simix_global->context_factory->create_context(ActorCode(), maestro));
527 maestro->context_.reset(simix_global->context_factory->create_maestro(ActorCode(code), maestro));
530 maestro->simcall_.issuer_ = maestro;
531 simix_global->maestro_ = maestro;
535 } // namespace kernel
536 } // namespace simgrid
538 int SIMIX_process_count() // XBT_ATTRIB_DEPRECATED_v329
540 return simix_global->process_list.size();
543 void* SIMIX_process_self_get_data() // XBT_ATTRIB_DEPRECATED_v329
545 smx_actor_t self = simgrid::kernel::actor::ActorImpl::self();
547 if (self == nullptr) {
550 return self->get_user_data();
553 void SIMIX_process_self_set_data(void* data) // XBT_ATTRIB_DEPRECATED_v329
555 simgrid::kernel::actor::ActorImpl::self()->set_user_data(data);
558 /* needs to be public and without simcall because it is called
559 by exceptions and logging events */
560 const char* SIMIX_process_self_get_name()
562 return SIMIX_is_maestro() ? "maestro" : simgrid::kernel::actor::ActorImpl::self()->get_cname();
566 * @brief Calling this function makes the process to yield.
568 * Only the current process can call this function, giving back the control to maestro.
570 * @param self the current process
573 /** @brief Returns the process from PID. */
574 smx_actor_t SIMIX_process_from_PID(aid_t PID)
576 auto item = simix_global->process_list.find(PID);
577 if (item == simix_global->process_list.end()) {
578 for (auto& a : simix_global->actors_to_destroy)
579 if (a.get_pid() == PID)
581 return nullptr; // Not found, even in the trash
586 void SIMIX_process_on_exit(smx_actor_t actor,
587 const std::function<void(bool /*failed*/)>& fun) // XBT_ATTRIB_DEPRECATED_v329
589 xbt_assert(actor, "current process not found: are you in maestro context ?");
590 actor->on_exit->emplace_back(fun);
593 void simcall_process_set_data(smx_actor_t process, void* data) // XBT_ATTRIB_DEPRECATED_v329
595 simgrid::kernel::actor::simcall([process, data] { process->set_user_data(data); });