1 /* Copyright (c) 2007-2019. 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 "smx_private.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/Client.hpp"
18 #include "src/simix/smx_host_private.hpp"
19 #include "src/surf/HostImpl.hpp"
20 #include "src/surf/cpu_interface.hpp"
22 #include <boost/range/algorithm.hpp>
24 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(simix_process, simix, "Logging specific to SIMIX (process)");
26 static unsigned long simix_process_maxpid = 0;
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 smx_context_t self_context = simgrid::kernel::context::Context::self();
39 return (self_context != nullptr) ? self_context->get_actor() : nullptr;
43 * @brief Returns whether a process has pending asynchronous communications.
44 * @return true if there are asynchronous communications in this process
46 int SIMIX_process_has_pending_comms(smx_actor_t process) {
48 return process->comms.size() > 0;
55 ActorImpl::ActorImpl(simgrid::xbt::string name, s4u::Host* host) : host_(host), name_(name), piface_(this)
57 pid_ = simix_process_maxpid++;
58 simcall.issuer = this;
61 ActorImpl::~ActorImpl()
63 delete this->context_;
66 void ActorImpl::cleanup()
68 if (this == simix_global->maestro_process) /* Do not cleanup maestro */
71 XBT_DEBUG("Cleanup actor %s (%p), waiting synchro %p", get_cname(), this, waiting_synchro.get());
73 simix_global->mutex.lock();
75 simix_global->process_list.erase(pid_);
76 if (host_ && host_process_list_hook.is_linked())
77 simgrid::xbt::intrusive_erase(host_->pimpl_->process_list_, *this);
78 if (not smx_destroy_list_hook.is_linked()) {
80 xbt_dynar_push_as(simix_global->dead_actors_vector, smx_actor_t, this);
82 simix_global->actors_to_destroy.push_back(*this);
84 context_->iwannadie = false;
86 simix_global->mutex.unlock();
89 void ActorImpl::exit()
91 context_->iwannadie = true;
96 // Forcefully kill the actor if its host is turned off. Not a HostFailureException because you should not survive that
97 if (not host_->is_on())
98 this->throw_exception(std::make_exception_ptr(simgrid::kernel::context::StopRequest("host failed")));
100 /* destroy the blocking synchro if any */
101 if (waiting_synchro != nullptr) {
103 activity::ExecImplPtr exec = boost::dynamic_pointer_cast<activity::ExecImpl>(waiting_synchro);
104 activity::CommImplPtr comm = boost::dynamic_pointer_cast<activity::CommImpl>(waiting_synchro);
105 activity::SleepImplPtr sleep = boost::dynamic_pointer_cast<activity::SleepImpl>(waiting_synchro);
106 activity::RawImplPtr raw = boost::dynamic_pointer_cast<activity::RawImpl>(waiting_synchro);
107 activity::IoImplPtr io = boost::dynamic_pointer_cast<activity::IoImpl>(waiting_synchro);
109 if (exec != nullptr && exec->surf_action_) {
111 exec->surf_action_->unref();
112 exec->surf_action_ = nullptr;
113 } else if (comm != nullptr) {
114 comms.remove(waiting_synchro);
116 // Remove first occurrence of &actor->simcall:
117 auto i = boost::range::find(waiting_synchro->simcalls_, &simcall);
118 if (i != waiting_synchro->simcalls_.end())
119 waiting_synchro->simcalls_.remove(&simcall);
120 } else if (sleep != nullptr) {
121 if (sleep->surf_action_)
122 sleep->surf_action_->cancel();
124 } else if (raw != nullptr) {
126 } else if (io != nullptr) {
129 simgrid::kernel::activity::ActivityImplPtr activity = waiting_synchro;
130 xbt_die("Activity %s is of unknown type %s", activity->get_cname(),
131 simgrid::xbt::demangle(typeid(activity).name()).get());
134 waiting_synchro = nullptr;
138 void ActorImpl::kill(ActorImpl* actor)
140 if (actor->finished_) {
141 XBT_DEBUG("Ignoring request to kill actor %s@%s that is already dead", actor->get_cname(),
142 actor->host_->get_cname());
146 XBT_DEBUG("Actor '%s'@%s is killing actor '%s'@%s", get_cname(), host_ ? host_->get_cname() : "", actor->get_cname(),
147 actor->host_ ? actor->host_->get_cname() : "");
151 if (std::find(begin(simix_global->actors_to_run), end(simix_global->actors_to_run), actor) ==
152 end(simix_global->actors_to_run) &&
154 XBT_DEBUG("Inserting %s in the to_run list", actor->get_cname());
155 simix_global->actors_to_run.push_back(actor);
159 void ActorImpl::kill_all()
161 for (auto const& kv : simix_global->process_list)
162 if (kv.second != this)
163 this->kill(kv.second);
166 void ActorImpl::set_kill_time(double kill_time)
168 if (kill_time <= SIMIX_get_clock())
170 XBT_DEBUG("Set kill time %f for actor %s@%s", kill_time, get_cname(), host_->get_cname());
171 kill_timer = simix::Timer::set(kill_time, [this] {
173 kill_timer = nullptr;
177 double ActorImpl::get_kill_time()
179 return kill_timer ? kill_timer->get_date() : 0;
182 static void dying_daemon(int /*exit_status*/, void* data)
184 std::vector<ActorImpl*>* vect = &simix_global->daemons;
186 auto it = std::find(vect->begin(), vect->end(), static_cast<ActorImpl*>(data));
187 xbt_assert(it != vect->end(), "The dying daemon is not a daemon after all. Please report that bug.");
189 /* Don't move the whole content since we don't really care about the order */
190 std::swap(*it, vect->back());
194 void ActorImpl::yield()
196 XBT_DEBUG("Yield actor '%s'", get_cname());
198 /* Go into sleep and return control to maestro */
201 /* Ok, maestro returned control to us */
202 XBT_DEBUG("Control returned to me: '%s'", get_cname());
204 if (context_->iwannadie) {
206 XBT_DEBUG("Actor %s@%s is dead", get_cname(), host_->get_cname());
207 // throw simgrid::kernel::context::StopRequest(); Does not seem to properly kill the actor
213 XBT_DEBUG("Hey! I'm suspended.");
214 xbt_assert(exception_ != nullptr, "Gasp! This exception may be lost by subsequent calls.");
219 if (exception_ != nullptr) {
220 XBT_DEBUG("Wait, maestro left me an exception");
221 std::exception_ptr exception = std::move(exception_);
222 exception_ = nullptr;
223 std::rethrow_exception(std::move(exception));
226 if (SMPI_switch_data_segment && not finished_) {
227 SMPI_switch_data_segment(iface());
231 /** This actor will be terminated automatically when the last non-daemon actor finishes */
232 void ActorImpl::daemonize()
236 simix_global->daemons.push_back(this);
237 SIMIX_process_on_exit(this, dying_daemon, this);
241 s4u::Actor* ActorImpl::restart()
243 XBT_DEBUG("Restarting actor %s on %s", get_cname(), host_->get_cname());
245 // retrieve the arguments of the old actor
246 ProcessArg arg = ProcessArg(host_, this);
248 // kill the old actor
249 (this == simix_global->maestro_process) ? this->exit() : SIMIX_process_self()->kill(this);
251 // start the new actor
253 ActorImpl::create(arg.name, std::move(arg.code), arg.data, arg.host, arg.properties.get(), nullptr);
254 actor->set_kill_time(arg.kill_time);
255 actor->set_auto_restart(arg.auto_restart);
257 return actor->ciface();
260 activity::ActivityImplPtr ActorImpl::suspend(ActorImpl* issuer)
263 XBT_DEBUG("Actor '%s' is already suspended", get_cname());
269 /* If we are suspending another actor that is waiting on a sync, suspend its synchronization. */
270 if (this != issuer) {
272 waiting_synchro->suspend();
273 /* If the other actor is not waiting, its suspension is delayed to when the actor is rescheduled. */
277 return activity::ExecImplPtr(new activity::ExecImpl("suspend", "", nullptr, this->host_))->start(0.0, 1.0, 0.0);
281 void ActorImpl::resume()
283 XBT_IN("actor = %p", this);
285 if (context_->iwannadie) {
286 XBT_VERB("Ignoring request to suspend an actor that is currently dying.");
294 /* resume the synchronization that was blocking the resumed actor. */
296 waiting_synchro->resume();
301 activity::ActivityImplPtr ActorImpl::join(smx_actor_t actor, double timeout)
303 activity::ActivityImplPtr res = this->sleep(timeout);
304 intrusive_ptr_add_ref(res.get());
305 SIMIX_process_on_exit(actor,
307 auto sleep = static_cast<simgrid::kernel::activity::SleepImpl*>(arg);
308 if (sleep->surf_action_)
309 sleep->surf_action_->finish(simgrid::kernel::resource::Action::State::FINISHED);
310 intrusive_ptr_release(sleep);
316 activity::ActivityImplPtr ActorImpl::sleep(double duration)
318 if (not host_->is_on())
319 throw_exception(std::make_exception_ptr(simgrid::HostFailureException(
320 XBT_THROW_POINT, std::string("Host ") + host_->get_cname() + " failed, you cannot sleep there.")));
322 return simgrid::kernel::activity::SleepImplPtr(new simgrid::kernel::activity::SleepImpl("sleep", host_))
326 void ActorImpl::throw_exception(std::exception_ptr e)
333 /* cancel the blocking synchro if any */
334 if (waiting_synchro) {
336 activity::ExecImplPtr exec = boost::dynamic_pointer_cast<activity::ExecImpl>(waiting_synchro);
340 activity::CommImplPtr comm = boost::dynamic_pointer_cast<activity::CommImpl>(waiting_synchro);
341 if (comm != nullptr) {
346 activity::SleepImplPtr sleep = boost::dynamic_pointer_cast<activity::SleepImpl>(waiting_synchro);
347 if (sleep != nullptr) {
348 SIMIX_process_sleep_destroy(waiting_synchro);
349 if (std::find(begin(simix_global->actors_to_run), end(simix_global->actors_to_run), this) ==
350 end(simix_global->actors_to_run) &&
351 this != SIMIX_process_self()) {
352 XBT_DEBUG("Inserting [%p] %s in the to_run list", this, get_cname());
353 simix_global->actors_to_run.push_back(this);
357 activity::RawImplPtr raw = boost::dynamic_pointer_cast<activity::RawImpl>(waiting_synchro);
358 if (raw != nullptr) {
362 activity::IoImplPtr io = boost::dynamic_pointer_cast<activity::IoImpl>(waiting_synchro);
367 waiting_synchro = nullptr;
370 void ActorImpl::set_host(s4u::Host* dest)
372 simgrid::xbt::intrusive_erase(host_->pimpl_->process_list_, *this);
374 dest->pimpl_->process_list_.push_back(*this);
377 ActorImplPtr ActorImpl::create(std::string name, simix::ActorCode code, void* data, s4u::Host* host,
378 std::unordered_map<std::string, std::string>* properties, ActorImpl* parent_actor)
381 XBT_DEBUG("Start actor %s@'%s'", name.c_str(), host->get_cname());
383 if (not host->is_on()) {
384 XBT_WARN("Cannot launch actor '%s' on failed host '%s'", name.c_str(), host->get_cname());
388 ActorImpl* actor = new ActorImpl(simgrid::xbt::string(name), host);
390 xbt_assert(code && host != nullptr, "Invalid parameters");
392 actor->set_user_data(data);
395 if (parent_actor != nullptr)
396 actor->set_ppid(parent_actor->get_pid());
398 XBT_VERB("Create context %s", actor->get_cname());
399 actor->context_ = simix_global->context_factory->create_context(std::move(code), actor);
402 if (properties != nullptr)
403 for (auto const& kv : *properties)
404 actor->set_property(kv.first, kv.second);
406 /* Add the actor to its host's actor list */
407 host->pimpl_->process_list_.push_back(*actor);
409 XBT_DEBUG("Start context '%s'", actor->get_cname());
411 /* Now insert it in the global actor list and in the actor to run list */
412 simix_global->process_list[actor->get_pid()] = actor;
413 XBT_DEBUG("Inserting [%p] %s(%s) in the to_run list", actor, actor->get_cname(), host->get_cname());
414 simix_global->actors_to_run.push_back(actor);
415 intrusive_ptr_add_ref(actor);
417 /* The on_creation() signal must be delayed until there, where the pid and everything is set */
418 s4u::Actor::on_creation(actor->iface());
420 return ActorImplPtr(actor);
423 void create_maestro(simix::ActorCode code)
425 /* Create maestro actor and initialize it */
426 ActorImpl* maestro = new ActorImpl(xbt::string(""), /*host*/ nullptr);
429 maestro->context_ = simix_global->context_factory->create_context(simix::ActorCode(), maestro);
431 maestro->context_ = simix_global->context_factory->create_maestro(code, maestro);
434 maestro->simcall.issuer = maestro;
435 simix_global->maestro_process = maestro;
439 } // namespace kernel
442 smx_actor_t SIMIX_process_attach(const char* name, void* data, const char* hostname,
443 std::unordered_map<std::string, std::string>* properties, smx_actor_t parent_process)
445 // This is mostly a copy/paste from SIMIX_process_new(),
446 // it'd be nice to share some code between those two functions.
448 sg_host_t host = sg_host_by_name(hostname);
449 XBT_DEBUG("Attach process %s on host '%s'", name, hostname);
451 if (not host->is_on()) {
452 XBT_WARN("Cannot launch process '%s' on failed host '%s'", name, hostname);
456 smx_actor_t actor = new simgrid::kernel::actor::ActorImpl(simgrid::xbt::string(name), host);
458 actor->set_user_data(data);
459 actor->code = nullptr;
461 if (parent_process != nullptr)
462 actor->set_ppid(parent_process->get_pid());
464 XBT_VERB("Create context %s", actor->get_cname());
465 xbt_assert(simix_global != nullptr, "simix is not initialized, please call MSG_init first");
466 actor->context_ = simix_global->context_factory->attach(actor);
469 if (properties != nullptr)
470 for (auto const& kv : *properties)
471 actor->set_property(kv.first, kv.second);
473 /* Add the process to it's host process list */
474 host->pimpl_->process_list_.push_back(*actor);
476 /* Now insert it in the global process list and in the process to run list */
477 simix_global->process_list[actor->get_pid()] = actor;
478 XBT_DEBUG("Inserting [%p] %s(%s) in the to_run list", actor, actor->get_cname(), host->get_cname());
479 simix_global->actors_to_run.push_back(actor);
480 intrusive_ptr_add_ref(actor);
482 auto* context = dynamic_cast<simgrid::kernel::context::AttachContext*>(actor->context_);
483 xbt_assert(nullptr != context, "Not a suitable context");
484 context->attach_start();
486 /* The on_creation() signal must be delayed until there, where the pid and everything is set */
487 simgrid::s4u::ActorPtr tmp = actor->iface(); // Passing this directly to on_creation will lead to crashes
488 simgrid::s4u::Actor::on_creation(tmp);
493 void SIMIX_process_detach()
495 auto* context = dynamic_cast<simgrid::kernel::context::AttachContext*>(simgrid::kernel::context::Context::self());
496 if (context == nullptr)
497 xbt_die("Not a suitable context");
499 context->get_actor()->cleanup();
500 context->attach_stop();
504 /** @deprecated When this function gets removed, also remove the xbt_ex class, that is only there to help users to
506 void SIMIX_process_throw(smx_actor_t actor, xbt_errcat_t cat, int value, const char* msg)
508 SMX_EXCEPTION(actor, cat, value, msg);
510 if (actor->is_suspended())
513 /* cancel the blocking synchro if any */
514 if (actor->waiting_synchro) {
516 simgrid::kernel::activity::ExecImplPtr exec =
517 boost::dynamic_pointer_cast<simgrid::kernel::activity::ExecImpl>(actor->waiting_synchro);
521 simgrid::kernel::activity::CommImplPtr comm =
522 boost::dynamic_pointer_cast<simgrid::kernel::activity::CommImpl>(actor->waiting_synchro);
523 if (comm != nullptr) {
524 actor->comms.remove(comm);
528 simgrid::kernel::activity::SleepImplPtr sleep =
529 boost::dynamic_pointer_cast<simgrid::kernel::activity::SleepImpl>(actor->waiting_synchro);
530 if (sleep != nullptr) {
531 SIMIX_process_sleep_destroy(actor->waiting_synchro);
532 if (std::find(begin(simix_global->actors_to_run), end(simix_global->actors_to_run), actor) ==
533 end(simix_global->actors_to_run) &&
534 actor != SIMIX_process_self()) {
535 XBT_DEBUG("Inserting [%p] %s in the to_run list", actor, actor->get_cname());
536 simix_global->actors_to_run.push_back(actor);
540 simgrid::kernel::activity::RawImplPtr raw =
541 boost::dynamic_pointer_cast<simgrid::kernel::activity::RawImpl>(actor->waiting_synchro);
542 if (raw != nullptr) {
546 simgrid::kernel::activity::IoImplPtr io =
547 boost::dynamic_pointer_cast<simgrid::kernel::activity::IoImpl>(actor->waiting_synchro);
552 actor->waiting_synchro = nullptr;
555 void simcall_HANDLER_process_suspend(smx_simcall_t simcall, smx_actor_t actor)
557 smx_activity_t sync_suspend = actor->suspend(simcall->issuer);
559 if (actor != simcall->issuer) {
560 SIMIX_simcall_answer(simcall);
562 sync_suspend->simcalls_.push_back(simcall);
563 actor->waiting_synchro = sync_suspend;
564 actor->waiting_synchro->suspend();
566 /* If we are suspending ourselves, then just do not finish the simcall now */
569 int SIMIX_process_get_maxpid() {
570 return simix_process_maxpid;
573 int SIMIX_process_count()
575 return simix_global->process_list.size();
578 void* SIMIX_process_self_get_data()
580 smx_actor_t self = SIMIX_process_self();
582 if (self == nullptr) {
585 return self->get_user_data();
588 void SIMIX_process_self_set_data(void *data)
590 SIMIX_process_self()->set_user_data(data);
594 /* needs to be public and without simcall because it is called
595 by exceptions and logging events */
596 const char* SIMIX_process_self_get_name() {
598 smx_actor_t process = SIMIX_process_self();
599 if (process == nullptr || process == simix_global->maestro_process)
602 return process->get_cname();
605 void simcall_HANDLER_process_join(smx_simcall_t simcall, smx_actor_t process, double timeout)
607 if (process->finished_) {
608 // The joined process is already finished, just wake up the issuer process right away
609 simcall_process_sleep__set__result(simcall, SIMIX_DONE);
610 SIMIX_simcall_answer(simcall);
613 smx_activity_t sync = simcall->issuer->join(process, timeout);
614 sync->simcalls_.push_back(simcall);
615 simcall->issuer->waiting_synchro = sync;
618 void simcall_HANDLER_process_sleep(smx_simcall_t simcall, double duration)
620 if (MC_is_active() || MC_record_replay_is_active()) {
621 MC_process_clock_add(simcall->issuer, duration);
622 simcall_process_sleep__set__result(simcall, SIMIX_DONE);
623 SIMIX_simcall_answer(simcall);
626 smx_activity_t sync = simcall->issuer->sleep(duration);
627 sync->simcalls_.push_back(simcall);
628 simcall->issuer->waiting_synchro = sync;
631 void SIMIX_process_sleep_destroy(smx_activity_t synchro)
633 XBT_DEBUG("Destroy sleep synchro %p", synchro.get());
634 simgrid::kernel::activity::SleepImplPtr sleep =
635 boost::static_pointer_cast<simgrid::kernel::activity::SleepImpl>(synchro);
637 if (sleep->surf_action_) {
638 sleep->surf_action_->unref();
639 sleep->surf_action_ = nullptr;
644 * @brief Calling this function makes the process to yield.
646 * Only the current process can call this function, giving back the control to maestro.
648 * @param self the current process
651 /** @brief Returns the list of processes to run.
654 const std::vector<smx_actor_t>& simgrid::simix::process_get_runnable()
656 return simix_global->actors_to_run;
659 /** @brief Returns the process from PID. */
660 smx_actor_t SIMIX_process_from_PID(aid_t PID)
662 auto actor = simix_global->process_list.find(PID);
663 return actor == simix_global->process_list.end() ? nullptr : actor->second;
666 void SIMIX_process_on_exit(smx_actor_t actor, int_f_pvoid_pvoid_t fun, void* data)
668 SIMIX_process_on_exit(actor, [fun](int a, void* b) { fun((void*)(intptr_t)a, b); }, data);
671 void SIMIX_process_on_exit(smx_actor_t actor, std::function<void(int, void*)> fun, void* data)
673 xbt_assert(actor, "current process not found: are you in maestro context ?");
675 actor->on_exit.emplace_back(s_smx_process_exit_fun_t{fun, data});
678 /** @brief Restart a process, starting it again from the beginning. */
680 * @ingroup simix_process_management
681 * @brief Creates and runs a new SIMIX process.
683 * The structure and the corresponding thread are created and put in the list of ready processes.
685 * @param name a name for the process. It is for user-level information and can be nullptr.
686 * @param code the main function of the process
687 * @param data a pointer to any data one may want to attach to the new object. It is for user-level information and can
689 * It can be retrieved with the method ActorImpl::getUserData().
690 * @param host where the new agent is executed.
691 * @param properties the properties of the process
693 smx_actor_t simcall_process_create(std::string name, simgrid::simix::ActorCode code, void* data, sg_host_t host,
694 std::unordered_map<std::string, std::string>* properties)
696 smx_actor_t self = SIMIX_process_self();
697 return simgrid::simix::simcall([name, code, data, host, properties, self] {
698 return simgrid::kernel::actor::ActorImpl::create(std::move(name), std::move(code), data, host, properties, self)
703 void simcall_process_set_data(smx_actor_t process, void* data)
705 simgrid::simix::simcall([process, data] { process->set_user_data(data); });