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/simix/smx_io_private.hpp"
20 #include "src/simix/smx_synchro_private.hpp"
21 #include "src/surf/HostImpl.hpp"
22 #include "src/surf/cpu_interface.hpp"
24 #include <boost/range/algorithm.hpp>
26 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(simix_process, simix, "Logging specific to SIMIX (process)");
28 static unsigned long simix_process_maxpid = 0;
31 * @brief Returns the current agent.
33 * This functions returns the currently running SIMIX process.
35 * @return The SIMIX process
37 smx_actor_t SIMIX_process_self()
39 smx_context_t self_context = simgrid::kernel::context::Context::self();
41 return (self_context != nullptr) ? self_context->get_actor() : nullptr;
45 * @brief Returns whether a process has pending asynchronous communications.
46 * @return true if there are asynchronous communications in this process
48 int SIMIX_process_has_pending_comms(smx_actor_t process) {
50 return process->comms.size() > 0;
54 * @brief Moves a process to the list of processes to destroy.
56 void SIMIX_process_cleanup(smx_actor_t process)
58 XBT_DEBUG("Cleanup process %s (%p), waiting synchro %p", process->get_cname(), process,
59 process->waiting_synchro.get());
61 simix_global->mutex.lock();
63 simix_global->process_list.erase(process->get_pid());
64 if (process->get_host() && process->host_process_list_hook.is_linked())
65 simgrid::xbt::intrusive_erase(process->get_host()->pimpl_->process_list_, *process);
66 if (not process->smx_destroy_list_hook.is_linked()) {
68 xbt_dynar_push_as(simix_global->dead_actors_vector, smx_actor_t, process);
70 simix_global->actors_to_destroy.push_back(*process);
72 process->context_->iwannadie = false;
74 simix_global->mutex.unlock();
81 ActorImpl::ActorImpl(simgrid::xbt::string name, s4u::Host* host) : host_(host), name_(name), piface_(this)
83 pid_ = simix_process_maxpid++;
84 simcall.issuer = this;
87 ActorImpl::~ActorImpl()
89 delete this->context_;
92 void ActorImpl::exit()
94 context_->iwannadie = true;
99 // Forcefully kill the actor if its host is turned off. Not a HostFailureException because you should not survive that
100 if (not host_->is_on())
101 this->throw_exception(std::make_exception_ptr(simgrid::kernel::context::StopRequest("host failed")));
103 /* destroy the blocking synchro if any */
104 if (waiting_synchro != nullptr) {
106 activity::ExecImplPtr exec = boost::dynamic_pointer_cast<activity::ExecImpl>(waiting_synchro);
107 activity::CommImplPtr comm = boost::dynamic_pointer_cast<activity::CommImpl>(waiting_synchro);
108 activity::SleepImplPtr sleep = boost::dynamic_pointer_cast<activity::SleepImpl>(waiting_synchro);
109 activity::RawImplPtr raw = boost::dynamic_pointer_cast<activity::RawImpl>(waiting_synchro);
110 activity::IoImplPtr io = boost::dynamic_pointer_cast<activity::IoImpl>(waiting_synchro);
112 if (exec != nullptr && exec->surf_action_) {
114 exec->surf_action_->unref();
115 exec->surf_action_ = nullptr;
116 } else if (comm != nullptr) {
117 comms.remove(waiting_synchro);
119 // Remove first occurrence of &actor->simcall:
120 auto i = boost::range::find(waiting_synchro->simcalls_, &simcall);
121 if (i != waiting_synchro->simcalls_.end())
122 waiting_synchro->simcalls_.remove(&simcall);
123 } else if (sleep != nullptr) {
124 if (sleep->surf_action_)
125 sleep->surf_action_->cancel();
127 } else if (raw != nullptr) {
128 SIMIX_synchro_stop_waiting(this, &simcall);
129 } else if (io != nullptr) {
132 simgrid::kernel::activity::ActivityImplPtr activity = waiting_synchro;
133 xbt_die("Activity %s is of unknown type %s", activity->get_cname(),
134 simgrid::xbt::demangle(typeid(activity).name()).get());
137 waiting_synchro = nullptr;
141 void ActorImpl::kill(ActorImpl* actor)
143 if (actor->finished_) {
144 XBT_DEBUG("Ignoring request to kill actor %s@%s that is already dead", actor->get_cname(),
145 actor->host_->get_cname());
149 XBT_DEBUG("Actor '%s'@%s is killing actor '%s'@%s", get_cname(), host_->get_cname(), actor->get_cname(),
150 actor->host_->get_cname());
154 if (std::find(begin(simix_global->actors_to_run), end(simix_global->actors_to_run), actor) ==
155 end(simix_global->actors_to_run) &&
157 XBT_DEBUG("Inserting %s in the to_run list", actor->get_cname());
158 simix_global->actors_to_run.push_back(actor);
162 void ActorImpl::kill_all()
164 for (auto const& kv : simix_global->process_list)
165 if (kv.second != this)
166 this->kill(kv.second);
169 void ActorImpl::set_kill_time(double kill_time)
171 if (kill_time <= SIMIX_get_clock())
173 XBT_DEBUG("Set kill time %f for actor %s@%s", kill_time, get_cname(), host_->get_cname());
174 kill_timer = SIMIX_timer_set(kill_time, [this] {
176 kill_timer = nullptr;
180 double ActorImpl::get_kill_time()
182 return SIMIX_timer_get_date(kill_timer);
185 static void dying_daemon(int /*exit_status*/, void* data)
187 std::vector<ActorImpl*>* vect = &simix_global->daemons;
189 auto it = std::find(vect->begin(), vect->end(), static_cast<ActorImpl*>(data));
190 xbt_assert(it != vect->end(), "The dying daemon is not a daemon after all. Please report that bug.");
192 /* Don't move the whole content since we don't really care about the order */
193 std::swap(*it, vect->back());
197 void ActorImpl::yield()
199 XBT_DEBUG("Yield actor '%s'", get_cname());
201 /* Go into sleep and return control to maestro */
204 /* Ok, maestro returned control to us */
205 XBT_DEBUG("Control returned to me: '%s'", get_cname());
207 if (context_->iwannadie) {
209 XBT_DEBUG("Actor %s@%s is dead", get_cname(), host_->get_cname());
210 // throw simgrid::kernel::context::StopRequest(); Does not seem to properly kill the actor
216 XBT_DEBUG("Hey! I'm suspended.");
217 xbt_assert(exception_ != nullptr, "Gasp! This exception may be lost by subsequent calls.");
222 if (exception_ != nullptr) {
223 XBT_DEBUG("Wait, maestro left me an exception");
224 std::exception_ptr exception = std::move(exception_);
225 exception_ = nullptr;
226 std::rethrow_exception(std::move(exception));
229 if (SMPI_switch_data_segment && not finished_) {
230 SMPI_switch_data_segment(iface());
234 /** This actor will be terminated automatically when the last non-daemon actor finishes */
235 void ActorImpl::daemonize()
239 simix_global->daemons.push_back(this);
240 SIMIX_process_on_exit(this, dying_daemon, this);
244 s4u::Actor* ActorImpl::restart()
246 XBT_DEBUG("Restarting actor %s on %s", get_cname(), host_->get_cname());
248 // retrieve the arguments of the old actor
249 ProcessArg arg = ProcessArg(host_, this);
251 // kill the old actor
252 (this == simix_global->maestro_process) ? this->exit() : SIMIX_process_self()->kill(this);
254 // start the new actor
256 ActorImpl::create(arg.name, std::move(arg.code), arg.data, arg.host, arg.properties.get(), nullptr);
257 actor->set_kill_time(arg.kill_time);
258 actor->set_auto_restart(arg.auto_restart);
260 return actor->ciface();
263 activity::ActivityImplPtr ActorImpl::suspend(ActorImpl* issuer)
266 XBT_DEBUG("Actor '%s' is already suspended", get_cname());
272 /* If we are suspending another actor that is waiting on a sync, suspend its synchronization. */
273 if (this != issuer) {
275 waiting_synchro->suspend();
276 /* If the other actor is not waiting, its suspension is delayed to when the actor is rescheduled. */
280 return activity::ExecImplPtr(new activity::ExecImpl("suspend", "", nullptr, this->host_))->start(0.0, 1.0, 0.0);
284 void ActorImpl::resume()
286 XBT_IN("actor = %p", this);
288 if (context_->iwannadie) {
289 XBT_VERB("Ignoring request to suspend an actor that is currently dying.");
297 /* resume the synchronization that was blocking the resumed actor. */
299 waiting_synchro->resume();
304 activity::ActivityImplPtr ActorImpl::join(smx_actor_t actor, double timeout)
306 activity::ActivityImplPtr res = this->sleep(timeout);
307 intrusive_ptr_add_ref(res.get());
308 SIMIX_process_on_exit(actor,
310 auto sleep = static_cast<simgrid::kernel::activity::SleepImpl*>(arg);
311 if (sleep->surf_action_)
312 sleep->surf_action_->finish(simgrid::kernel::resource::Action::State::FINISHED);
313 intrusive_ptr_release(sleep);
319 activity::ActivityImplPtr ActorImpl::sleep(double duration)
321 if (not host_->is_on())
322 throw_exception(std::make_exception_ptr(simgrid::HostFailureException(
323 XBT_THROW_POINT, std::string("Host ") + host_->get_cname() + " failed, you cannot sleep there.")));
325 return simgrid::kernel::activity::SleepImplPtr(new simgrid::kernel::activity::SleepImpl("sleep", host_))
329 void ActorImpl::throw_exception(std::exception_ptr e)
336 /* cancel the blocking synchro if any */
337 if (waiting_synchro) {
339 activity::ExecImplPtr exec = boost::dynamic_pointer_cast<activity::ExecImpl>(waiting_synchro);
343 activity::CommImplPtr comm = boost::dynamic_pointer_cast<activity::CommImpl>(waiting_synchro);
344 if (comm != nullptr) {
349 activity::SleepImplPtr sleep = boost::dynamic_pointer_cast<activity::SleepImpl>(waiting_synchro);
350 if (sleep != nullptr) {
351 SIMIX_process_sleep_destroy(waiting_synchro);
352 if (std::find(begin(simix_global->actors_to_run), end(simix_global->actors_to_run), this) ==
353 end(simix_global->actors_to_run) &&
354 this != SIMIX_process_self()) {
355 XBT_DEBUG("Inserting [%p] %s in the to_run list", this, get_cname());
356 simix_global->actors_to_run.push_back(this);
360 activity::RawImplPtr raw = boost::dynamic_pointer_cast<activity::RawImpl>(waiting_synchro);
361 if (raw != nullptr) {
362 SIMIX_synchro_stop_waiting(this, &simcall);
365 activity::IoImplPtr io = boost::dynamic_pointer_cast<activity::IoImpl>(waiting_synchro);
370 waiting_synchro = nullptr;
373 void ActorImpl::set_host(s4u::Host* dest)
375 simgrid::xbt::intrusive_erase(host_->pimpl_->process_list_, *this);
377 dest->pimpl_->process_list_.push_back(*this);
380 ActorImplPtr ActorImpl::create(std::string name, simix::ActorCode code, void* data, s4u::Host* host,
381 std::unordered_map<std::string, std::string>* properties, ActorImpl* parent_actor)
384 XBT_DEBUG("Start actor %s@'%s'", name.c_str(), host->get_cname());
386 if (not host->is_on()) {
387 XBT_WARN("Cannot launch actor '%s' on failed host '%s'", name.c_str(), host->get_cname());
391 ActorImpl* actor = new ActorImpl(simgrid::xbt::string(name), host);
393 xbt_assert(code && host != nullptr, "Invalid parameters");
395 actor->set_user_data(data);
398 if (parent_actor != nullptr)
399 actor->set_ppid(parent_actor->get_pid());
401 XBT_VERB("Create context %s", actor->get_cname());
402 actor->context_ = SIMIX_context_new(std::move(code), &SIMIX_process_cleanup, actor);
405 if (properties != nullptr)
406 for (auto const& kv : *properties)
407 actor->set_property(kv.first, kv.second);
409 /* Add the actor to its host's actor list */
410 host->pimpl_->process_list_.push_back(*actor);
412 XBT_DEBUG("Start context '%s'", actor->get_cname());
414 /* Now insert it in the global actor list and in the actor to run list */
415 simix_global->process_list[actor->get_pid()] = actor;
416 XBT_DEBUG("Inserting [%p] %s(%s) in the to_run list", actor, actor->get_cname(), host->get_cname());
417 simix_global->actors_to_run.push_back(actor);
418 intrusive_ptr_add_ref(actor);
420 /* The on_creation() signal must be delayed until there, where the pid and everything is set */
421 s4u::Actor::on_creation(actor->iface());
423 return ActorImplPtr(actor);
426 void create_maestro(simix::ActorCode code)
428 /* Create maestro actor and initialize it */
429 ActorImpl* maestro = new ActorImpl(xbt::string(""), /*host*/ nullptr);
432 maestro->context_ = SIMIX_context_new(simix::ActorCode(), nullptr, maestro);
434 maestro->context_ = simix_global->context_factory->create_maestro(code, maestro);
437 maestro->simcall.issuer = maestro;
438 simix_global->maestro_process = maestro;
442 } // namespace kernel
445 smx_actor_t SIMIX_process_attach(const char* name, void* data, const char* hostname,
446 std::unordered_map<std::string, std::string>* properties, smx_actor_t parent_process)
448 // This is mostly a copy/paste from SIMIX_process_new(),
449 // it'd be nice to share some code between those two functions.
451 sg_host_t host = sg_host_by_name(hostname);
452 XBT_DEBUG("Attach process %s on host '%s'", name, hostname);
454 if (not host->is_on()) {
455 XBT_WARN("Cannot launch process '%s' on failed host '%s'", name, hostname);
459 smx_actor_t actor = new simgrid::kernel::actor::ActorImpl(simgrid::xbt::string(name), host);
461 actor->set_user_data(data);
462 actor->code = nullptr;
464 if (parent_process != nullptr)
465 actor->set_ppid(parent_process->get_pid());
467 XBT_VERB("Create context %s", actor->get_cname());
468 xbt_assert(simix_global != nullptr, "simix is not initialized, please call MSG_init first");
469 actor->context_ = simix_global->context_factory->attach(&SIMIX_process_cleanup, actor);
472 if (properties != nullptr)
473 for (auto const& kv : *properties)
474 actor->set_property(kv.first, kv.second);
476 /* Add the process to it's host process list */
477 host->pimpl_->process_list_.push_back(*actor);
479 /* Now insert it in the global process list and in the process to run list */
480 simix_global->process_list[actor->get_pid()] = actor;
481 XBT_DEBUG("Inserting [%p] %s(%s) in the to_run list", actor, actor->get_cname(), host->get_cname());
482 simix_global->actors_to_run.push_back(actor);
483 intrusive_ptr_add_ref(actor);
485 auto* context = dynamic_cast<simgrid::kernel::context::AttachContext*>(actor->context_);
486 xbt_assert(nullptr != context, "Not a suitable context");
487 context->attach_start();
489 /* The on_creation() signal must be delayed until there, where the pid and everything is set */
490 simgrid::s4u::ActorPtr tmp = actor->iface(); // Passing this directly to on_creation will lead to crashes
491 simgrid::s4u::Actor::on_creation(tmp);
496 void SIMIX_process_detach()
498 auto* context = dynamic_cast<simgrid::kernel::context::AttachContext*>(simgrid::kernel::context::Context::self());
499 if (context == nullptr)
500 xbt_die("Not a suitable context");
502 SIMIX_process_cleanup(context->get_actor());
503 context->attach_stop();
507 /** @deprecated When this function gets removed, also remove the xbt_ex class, that is only there to help users to
509 void SIMIX_process_throw(smx_actor_t actor, xbt_errcat_t cat, int value, const char* msg)
511 SMX_EXCEPTION(actor, cat, value, msg);
513 if (actor->is_suspended())
516 /* cancel the blocking synchro if any */
517 if (actor->waiting_synchro) {
519 simgrid::kernel::activity::ExecImplPtr exec =
520 boost::dynamic_pointer_cast<simgrid::kernel::activity::ExecImpl>(actor->waiting_synchro);
524 simgrid::kernel::activity::CommImplPtr comm =
525 boost::dynamic_pointer_cast<simgrid::kernel::activity::CommImpl>(actor->waiting_synchro);
526 if (comm != nullptr) {
527 actor->comms.remove(comm);
531 simgrid::kernel::activity::SleepImplPtr sleep =
532 boost::dynamic_pointer_cast<simgrid::kernel::activity::SleepImpl>(actor->waiting_synchro);
533 if (sleep != nullptr) {
534 SIMIX_process_sleep_destroy(actor->waiting_synchro);
535 if (std::find(begin(simix_global->actors_to_run), end(simix_global->actors_to_run), actor) ==
536 end(simix_global->actors_to_run) &&
537 actor != SIMIX_process_self()) {
538 XBT_DEBUG("Inserting [%p] %s in the to_run list", actor, actor->get_cname());
539 simix_global->actors_to_run.push_back(actor);
543 simgrid::kernel::activity::RawImplPtr raw =
544 boost::dynamic_pointer_cast<simgrid::kernel::activity::RawImpl>(actor->waiting_synchro);
545 if (raw != nullptr) {
546 SIMIX_synchro_stop_waiting(actor, &actor->simcall);
549 simgrid::kernel::activity::IoImplPtr io =
550 boost::dynamic_pointer_cast<simgrid::kernel::activity::IoImpl>(actor->waiting_synchro);
555 actor->waiting_synchro = nullptr;
558 void simcall_HANDLER_process_suspend(smx_simcall_t simcall, smx_actor_t actor)
560 smx_activity_t sync_suspend = actor->suspend(simcall->issuer);
562 if (actor != simcall->issuer) {
563 SIMIX_simcall_answer(simcall);
565 sync_suspend->simcalls_.push_back(simcall);
566 actor->waiting_synchro = sync_suspend;
567 actor->waiting_synchro->suspend();
569 /* If we are suspending ourselves, then just do not finish the simcall now */
572 int SIMIX_process_get_maxpid() {
573 return simix_process_maxpid;
576 int SIMIX_process_count()
578 return simix_global->process_list.size();
581 void* SIMIX_process_self_get_data()
583 smx_actor_t self = SIMIX_process_self();
585 if (self == nullptr) {
588 return self->get_user_data();
591 void SIMIX_process_self_set_data(void *data)
593 SIMIX_process_self()->set_user_data(data);
597 /* needs to be public and without simcall because it is called
598 by exceptions and logging events */
599 const char* SIMIX_process_self_get_name() {
601 smx_actor_t process = SIMIX_process_self();
602 if (process == nullptr || process == simix_global->maestro_process)
605 return process->get_cname();
608 void simcall_HANDLER_process_join(smx_simcall_t simcall, smx_actor_t process, double timeout)
610 if (process->finished_) {
611 // The joined process is already finished, just wake up the issuer process right away
612 simcall_process_sleep__set__result(simcall, SIMIX_DONE);
613 SIMIX_simcall_answer(simcall);
616 smx_activity_t sync = simcall->issuer->join(process, timeout);
617 sync->simcalls_.push_back(simcall);
618 simcall->issuer->waiting_synchro = sync;
621 void simcall_HANDLER_process_sleep(smx_simcall_t simcall, double duration)
623 if (MC_is_active() || MC_record_replay_is_active()) {
624 MC_process_clock_add(simcall->issuer, duration);
625 simcall_process_sleep__set__result(simcall, SIMIX_DONE);
626 SIMIX_simcall_answer(simcall);
629 smx_activity_t sync = simcall->issuer->sleep(duration);
630 sync->simcalls_.push_back(simcall);
631 simcall->issuer->waiting_synchro = sync;
634 void SIMIX_process_sleep_destroy(smx_activity_t synchro)
636 XBT_DEBUG("Destroy sleep synchro %p", synchro.get());
637 simgrid::kernel::activity::SleepImplPtr sleep =
638 boost::static_pointer_cast<simgrid::kernel::activity::SleepImpl>(synchro);
640 if (sleep->surf_action_) {
641 sleep->surf_action_->unref();
642 sleep->surf_action_ = nullptr;
647 * @brief Calling this function makes the process to yield.
649 * Only the current process can call this function, giving back the control to maestro.
651 * @param self the current process
654 /** @brief Returns the list of processes to run.
657 const std::vector<smx_actor_t>& simgrid::simix::process_get_runnable()
659 return simix_global->actors_to_run;
662 /** @brief Returns the process from PID. */
663 smx_actor_t SIMIX_process_from_PID(aid_t PID)
665 auto actor = simix_global->process_list.find(PID);
666 return actor == simix_global->process_list.end() ? nullptr : actor->second;
669 void SIMIX_process_on_exit(smx_actor_t actor, int_f_pvoid_pvoid_t fun, void* data)
671 SIMIX_process_on_exit(actor, [fun](int a, void* b) { fun((void*)(intptr_t)a, b); }, data);
674 void SIMIX_process_on_exit(smx_actor_t actor, std::function<void(int, void*)> fun, void* data)
676 xbt_assert(actor, "current process not found: are you in maestro context ?");
678 actor->on_exit.emplace_back(s_smx_process_exit_fun_t{fun, data});
681 /** @brief Restart a process, starting it again from the beginning. */
683 * @ingroup simix_process_management
684 * @brief Creates and runs a new SIMIX process.
686 * The structure and the corresponding thread are created and put in the list of ready processes.
688 * @param name a name for the process. It is for user-level information and can be nullptr.
689 * @param code the main function of the process
690 * @param data a pointer to any data one may want to attach to the new object. It is for user-level information and can
692 * It can be retrieved with the method ActorImpl::getUserData().
693 * @param host where the new agent is executed.
694 * @param properties the properties of the process
696 smx_actor_t simcall_process_create(std::string name, simgrid::simix::ActorCode code, void* data, sg_host_t host,
697 std::unordered_map<std::string, std::string>* properties)
699 smx_actor_t self = SIMIX_process_self();
700 return simgrid::simix::simcall([name, code, data, host, properties, self] {
701 return simgrid::kernel::actor::ActorImpl::create(std::move(name), std::move(code), data, host, properties, self)
706 void simcall_process_set_data(smx_actor_t process, void* data)
708 simgrid::simix::simcall([process, data] { process->set_user_data(data); });