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 "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/Client.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>
23 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(simix_process, simix, "Logging specific to SIMIX (process)");
25 static unsigned long simix_process_maxpid = 0;
28 * @brief Returns the current agent.
30 * This functions returns the currently running SIMIX process.
32 * @return The SIMIX process
34 smx_actor_t SIMIX_process_self()
36 simgrid::kernel::context::Context* self_context = simgrid::kernel::context::Context::self();
38 return (self_context != nullptr) ? self_context->get_actor() : nullptr;
42 * @brief Returns whether a process has pending asynchronous communications.
43 * @return true if there are asynchronous communications in this process
46 int SIMIX_process_has_pending_comms(smx_actor_t process)
49 return process->comms.size() > 0;
56 ActorImpl::ActorImpl(const simgrid::xbt::string& name, s4u::Host* host) : host_(host), name_(name), piface_(this)
58 pid_ = simix_process_maxpid++;
59 simcall.issuer = this;
62 ActorImpl::~ActorImpl()
64 if (this != simix_global->maestro_process) {
65 context_->iwannadie = false; // don't let the simcall's yield() do a Context::stop(), to avoid infinite loops
66 simgrid::simix::simcall([this] { simgrid::s4u::Actor::on_destruction(*ciface()); });
67 context_->iwannadie = true;
71 /* Become an actor in the simulation
73 * Currently this can only be called by the main thread (once) and only work with some thread factories
74 * (currently ThreadContextFactory).
76 * In the future, it might be extended in order to attach other threads created by a third party library.
79 ActorImplPtr ActorImpl::attach(const std::string& name, void* data, s4u::Host* host,
80 const std::unordered_map<std::string, std::string>* properties)
82 // This is mostly a copy/paste from create(), it'd be nice to share some code between those two functions.
84 XBT_DEBUG("Attach process %s on host '%s'", name.c_str(), host->get_cname());
86 if (not host->is_on()) {
87 XBT_WARN("Cannot launch process '%s' on failed host '%s'", name.c_str(), host->get_cname());
88 throw simgrid::HostFailureException(XBT_THROW_POINT, "Cannot attach actor on failed host.");
91 ActorImpl* actor = new ActorImpl(xbt::string(name), host);
93 actor->set_user_data(data);
94 actor->code_ = nullptr;
96 XBT_VERB("Create context %s", actor->get_cname());
97 xbt_assert(simix_global != nullptr, "simix is not initialized, please call MSG_init first");
98 actor->context_.reset(simix_global->context_factory->attach(actor));
101 if (properties != nullptr)
102 actor->set_properties(*properties);
104 /* Add the process to it's host process list */
105 host->pimpl_->process_list_.push_back(*actor);
107 /* Now insert it in the global process list and in the process to run list */
108 simix_global->process_list[actor->get_pid()] = actor;
109 XBT_DEBUG("Inserting [%p] %s(%s) in the to_run list", actor, actor->get_cname(), host->get_cname());
110 simix_global->actors_to_run.push_back(actor);
111 intrusive_ptr_add_ref(actor);
113 auto* context = dynamic_cast<simgrid::kernel::context::AttachContext*>(actor->context_.get());
114 xbt_assert(nullptr != context, "Not a suitable context");
115 context->attach_start();
117 /* The on_creation() signal must be delayed until there, where the pid and everything is set */
118 simgrid::s4u::Actor::on_creation(*actor->ciface());
120 return ActorImplPtr(actor);
122 /** @brief Detach an actor attached with `attach()`
124 * This is called when the current actor has finished its job.
125 * Used in the main thread, it waits for the simulation to finish before returning. When it returns, the other
126 * simulated actors and the maestro are destroyed.
128 void ActorImpl::detach()
130 auto* context = dynamic_cast<context::AttachContext*>(context::Context::self());
131 if (context == nullptr)
132 xbt_die("Not a suitable context");
134 context->get_actor()->cleanup();
135 context->attach_stop();
138 void ActorImpl::cleanup()
142 if (has_to_auto_restart() && not get_host()->is_on()) {
143 XBT_DEBUG("Insert host %s to watched_hosts because it's off and %s needs to restart", get_host()->get_cname(),
145 watched_hosts.insert(get_host()->get_name());
149 // Execute the termination callbacks
150 bool failed = context_->iwannadie;
151 for (auto exit_fun = on_exit->crbegin(); exit_fun != on_exit->crend(); ++exit_fun)
157 /* cancel non-blocking activities */
158 for (auto activity : comms)
159 boost::static_pointer_cast<activity::CommImpl>(activity)->cancel();
162 XBT_DEBUG("%s@%s(%ld) should not run anymore", get_cname(), get_host()->get_cname(), get_pid());
164 if (this == simix_global->maestro_process) /* Do not cleanup maestro */
167 XBT_DEBUG("Cleanup actor %s (%p), waiting synchro %p", get_cname(), this, waiting_synchro.get());
169 /* Unregister from the kill timer if any */
170 if (kill_timer != nullptr) {
171 kill_timer->remove();
172 kill_timer = nullptr;
175 simix_global->mutex.lock();
177 simix_global->process_list.erase(pid_);
178 if (host_ && host_process_list_hook.is_linked())
179 simgrid::xbt::intrusive_erase(host_->pimpl_->process_list_, *this);
180 if (not smx_destroy_list_hook.is_linked()) {
182 xbt_dynar_push_as(simix_global->dead_actors_vector, ActorImpl*, this);
184 simix_global->actors_to_destroy.push_back(*this);
187 simix_global->mutex.unlock();
189 context_->iwannadie = false; // don't let the simcall's yield() do a Context::stop(), to avoid infinite loops
190 simgrid::simix::simcall([this] { simgrid::s4u::Actor::on_termination(*ciface()); });
191 context_->iwannadie = true;
194 void ActorImpl::exit()
196 context_->iwannadie = true;
198 exception_ = nullptr;
200 // Forcefully kill the actor if its host is turned off. Not a HostFailureException because you should not survive that
201 if (not host_->is_on())
202 this->throw_exception(std::make_exception_ptr(ForcefulKillException("host failed")));
204 /* destroy the blocking synchro if any */
205 if (waiting_synchro != nullptr) {
206 waiting_synchro->cancel();
207 waiting_synchro->state_ = SIMIX_FAILED;
209 activity::ExecImplPtr exec = boost::dynamic_pointer_cast<activity::ExecImpl>(waiting_synchro);
210 activity::CommImplPtr comm = boost::dynamic_pointer_cast<activity::CommImpl>(waiting_synchro);
212 if (exec != nullptr) {
213 exec->clean_action();
214 } else if (comm != nullptr) {
215 comms.remove(waiting_synchro);
216 // Remove first occurrence of &actor->simcall:
217 auto i = boost::range::find(waiting_synchro->simcalls_, &simcall);
218 if (i != waiting_synchro->simcalls_.end())
219 waiting_synchro->simcalls_.remove(&simcall);
221 activity::ActivityImplPtr(waiting_synchro)->finish();
224 waiting_synchro = nullptr;
228 void ActorImpl::kill(ActorImpl* actor)
230 if (actor->finished_) {
231 XBT_DEBUG("Ignoring request to kill actor %s@%s that is already dead", actor->get_cname(),
232 actor->host_->get_cname());
236 XBT_DEBUG("Actor '%s'@%s is killing actor '%s'@%s", get_cname(), host_ ? host_->get_cname() : "", actor->get_cname(),
237 actor->host_ ? actor->host_->get_cname() : "");
241 if (std::find(begin(simix_global->actors_to_run), end(simix_global->actors_to_run), actor) ==
242 end(simix_global->actors_to_run) &&
244 XBT_DEBUG("Inserting %s in the to_run list", actor->get_cname());
245 simix_global->actors_to_run.push_back(actor);
249 void ActorImpl::kill_all()
251 for (auto const& kv : simix_global->process_list)
252 if (kv.second != this)
253 this->kill(kv.second);
256 void ActorImpl::set_kill_time(double kill_time)
258 if (kill_time <= SIMIX_get_clock())
260 XBT_DEBUG("Set kill time %f for actor %s@%s", kill_time, get_cname(), host_->get_cname());
261 kill_timer = simix::Timer::set(kill_time, [this] {
263 kill_timer = nullptr;
267 double ActorImpl::get_kill_time()
269 return kill_timer ? kill_timer->get_date() : 0;
272 void ActorImpl::yield()
274 XBT_DEBUG("Yield actor '%s'", get_cname());
276 /* Go into sleep and return control to maestro */
279 /* Ok, maestro returned control to us */
280 XBT_DEBUG("Control returned to me: '%s'", get_cname());
282 if (context_->iwannadie) {
283 XBT_DEBUG("Actor %s@%s is dead", get_cname(), host_->get_cname());
284 // throw simgrid::kernel::context::ForcefulKillException(); Does not seem to properly kill the actor
290 XBT_DEBUG("Hey! I'm suspended.");
292 xbt_assert(exception_ == nullptr, "Gasp! This exception may be lost by subsequent calls.");
297 if (exception_ != nullptr) {
298 XBT_DEBUG("Wait, maestro left me an exception");
299 std::exception_ptr exception = std::move(exception_);
300 exception_ = nullptr;
301 std::rethrow_exception(std::move(exception));
304 if (SMPI_switch_data_segment && not finished_) {
305 SMPI_switch_data_segment(iface());
309 /** This actor will be terminated automatically when the last non-daemon actor finishes */
310 void ActorImpl::daemonize()
314 simix_global->daemons.push_back(this);
318 void ActorImpl::undaemonize()
321 auto& vect = simix_global->daemons;
322 auto it = std::find(vect.begin(), vect.end(), this);
323 xbt_assert(it != vect.end(), "The dying daemon is not a daemon after all. Please report that bug.");
324 /* Don't move the whole content since we don't really care about the order */
326 std::swap(*it, vect.back());
332 s4u::Actor* ActorImpl::restart()
334 xbt_assert(this != simix_global->maestro_process, "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 = ProcessArg(host_, this);
341 // kill the old actor
342 context::Context::self()->get_actor()->kill(this);
344 // start the new actor
346 ActorImpl::create(arg.name, std::move(arg.code), arg.data, arg.host, arg.properties.get(), nullptr);
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->ciface();
354 activity::ActivityImplPtr ActorImpl::suspend(ActorImpl* issuer)
357 XBT_DEBUG("Actor '%s' is already suspended", get_cname());
363 /* If we are suspending another actor that is waiting on a sync, suspend its synchronization. */
364 if (this != issuer) {
366 waiting_synchro->suspend();
367 /* If the other actor is not waiting, its suspension is delayed to when the actor is rescheduled. */
371 activity::ExecImpl* exec = new activity::ExecImpl();
372 (*exec).set_name("suspend").set_host(host_).set_flops_amount(0.0).start();
373 return activity::ExecImplPtr(exec);
377 void ActorImpl::resume()
379 XBT_IN("actor = %p", this);
381 if (context_->iwannadie) {
382 XBT_VERB("Ignoring request to suspend an actor that is currently dying.");
390 /* resume the synchronization that was blocking the resumed actor. */
392 waiting_synchro->resume();
397 activity::ActivityImplPtr ActorImpl::join(ActorImpl* actor, double timeout)
399 activity::ActivityImplPtr sleep = this->sleep(timeout);
400 SIMIX_process_on_exit(actor, [sleep](bool) {
401 if (sleep->surf_action_)
402 sleep->surf_action_->finish(resource::Action::State::FINISHED);
407 activity::ActivityImplPtr ActorImpl::sleep(double duration)
409 if (not host_->is_on())
410 throw_exception(std::make_exception_ptr(simgrid::HostFailureException(
411 XBT_THROW_POINT, std::string("Host ") + host_->get_cname() + " failed, you cannot sleep there.")));
413 activity::SleepImpl* sleep = new activity::SleepImpl();
414 (*sleep).set_name("sleep").set_host(host_).set_duration(duration).start();
415 return activity::SleepImplPtr(sleep);
418 void ActorImpl::throw_exception(std::exception_ptr e)
425 /* cancel the blocking synchro if any */
426 if (waiting_synchro) {
427 waiting_synchro->cancel();
429 activity::CommImplPtr comm = boost::dynamic_pointer_cast<activity::CommImpl>(waiting_synchro);
434 waiting_synchro = nullptr;
438 void ActorImpl::set_host(s4u::Host* dest)
440 xbt::intrusive_erase(host_->pimpl_->process_list_, *this);
442 dest->pimpl_->process_list_.push_back(*this);
445 ActorImplPtr ActorImpl::init(const std::string& name, s4u::Host* host)
447 ActorImpl* actor = new ActorImpl(xbt::string(name), host);
448 actor->set_ppid(this->pid_);
450 intrusive_ptr_add_ref(actor);
451 /* The on_creation() signal must be delayed until there, where the pid and everything is set */
452 s4u::Actor::on_creation(*actor->ciface());
454 return ActorImplPtr(actor);
457 ActorImpl* ActorImpl::start(const simix::ActorCode& code)
459 xbt_assert(code && host_ != nullptr, "Invalid parameters");
461 if (not host_->is_on()) {
462 XBT_WARN("Cannot launch actor '%s' on failed host '%s'", name_.c_str(), host_->get_cname());
463 intrusive_ptr_release(this);
464 throw simgrid::HostFailureException(XBT_THROW_POINT, "Cannot start actor on failed host.");
468 XBT_VERB("Create context %s", get_cname());
469 context_.reset(simix_global->context_factory->create_context(simix::ActorCode(code), this));
471 XBT_DEBUG("Start context '%s'", get_cname());
473 /* Add the actor to its host's actor list */
474 host_->pimpl_->process_list_.push_back(*this);
475 simix_global->process_list[pid_] = this;
477 /* Now insert it in the global actor list and in the actor to run list */
478 XBT_DEBUG("Inserting [%p] %s(%s) in the to_run list", this, get_cname(), host_->get_cname());
479 simix_global->actors_to_run.push_back(this);
484 ActorImplPtr ActorImpl::create(const std::string& name, const simix::ActorCode& code, void* data, s4u::Host* host,
485 const std::unordered_map<std::string, std::string>* properties, ActorImpl* parent_actor)
487 XBT_DEBUG("Start actor %s@'%s'", name.c_str(), host->get_cname());
490 if (parent_actor != nullptr)
491 actor = parent_actor->init(xbt::string(name), host);
493 actor = SIMIX_process_self()->init(xbt::string(name), host);
496 actor->set_user_data(data);
499 if (properties != nullptr)
500 actor->set_properties(*properties);
507 void create_maestro(const std::function<void()>& code)
509 /* Create maestro actor and initialize it */
510 ActorImpl* maestro = new ActorImpl(xbt::string(""), /*host*/ nullptr);
513 maestro->context_.reset(simix_global->context_factory->create_context(simix::ActorCode(), maestro));
515 maestro->context_.reset(simix_global->context_factory->create_maestro(simix::ActorCode(code), maestro));
518 maestro->simcall.issuer = maestro;
519 simix_global->maestro_process = maestro;
523 } // namespace kernel
524 } // namespace simgrid
526 void SIMIX_process_detach()
528 simgrid::kernel::actor::ActorImpl::detach();
531 smx_actor_t SIMIX_process_attach(const char* name, void* data, const char* hostname,
532 std::unordered_map<std::string, std::string>* properties,
533 smx_actor_t /*parent_process*/)
535 return simgrid::kernel::actor::ActorImpl::attach(name, data, sg_host_by_name(hostname), properties).get();
538 void simcall_HANDLER_process_suspend(smx_simcall_t simcall, smx_actor_t actor)
540 smx_activity_t sync_suspend = actor->suspend(simcall->issuer);
542 if (actor != simcall->issuer) {
543 SIMIX_simcall_answer(simcall);
545 sync_suspend->simcalls_.push_back(simcall);
546 actor->waiting_synchro = sync_suspend;
547 actor->waiting_synchro->suspend();
549 /* If we are suspending ourselves, then just do not finish the simcall now */
552 int SIMIX_process_get_maxpid()
554 return simix_process_maxpid;
557 int SIMIX_process_count()
559 return simix_global->process_list.size();
562 void* SIMIX_process_self_get_data() // deprecated
564 smx_actor_t self = SIMIX_process_self();
566 if (self == nullptr) {
569 return self->get_user_data();
572 void SIMIX_process_self_set_data(void* data) // deprecated
574 SIMIX_process_self()->set_user_data(data);
577 /* needs to be public and without simcall because it is called
578 by exceptions and logging events */
579 const char* SIMIX_process_self_get_name()
582 smx_actor_t process = SIMIX_process_self();
583 if (process == nullptr || process == simix_global->maestro_process)
586 return process->get_cname();
589 void simcall_HANDLER_process_join(smx_simcall_t simcall, smx_actor_t process, double timeout)
591 if (process->finished_) {
592 // The joined process is already finished, just wake up the issuer process right away
593 simcall_process_sleep__set__result(simcall, SIMIX_DONE);
594 SIMIX_simcall_answer(simcall);
597 smx_activity_t sync = simcall->issuer->join(process, timeout);
598 sync->simcalls_.push_back(simcall);
599 simcall->issuer->waiting_synchro = sync;
602 void simcall_HANDLER_process_sleep(smx_simcall_t simcall, double duration)
604 if (MC_is_active() || MC_record_replay_is_active()) {
605 MC_process_clock_add(simcall->issuer, duration);
606 simcall_process_sleep__set__result(simcall, SIMIX_DONE);
607 SIMIX_simcall_answer(simcall);
610 smx_activity_t sync = simcall->issuer->sleep(duration);
611 sync->simcalls_.push_back(simcall);
612 simcall->issuer->waiting_synchro = sync;
616 * @brief Calling this function makes the process to yield.
618 * Only the current process can call this function, giving back the control to maestro.
620 * @param self the current process
623 /** @brief Returns the list of processes to run.
626 const std::vector<smx_actor_t>& simgrid::simix::process_get_runnable()
628 return simix_global->actors_to_run;
631 /** @brief Returns the process from PID. */
632 smx_actor_t SIMIX_process_from_PID(aid_t PID)
634 auto item = simix_global->process_list.find(PID);
635 if (item == simix_global->process_list.end()) {
636 for (auto& a : simix_global->actors_to_destroy)
637 if (a.get_pid() == PID)
639 return nullptr; // Not found, even in the trash
644 void SIMIX_process_on_exit(smx_actor_t actor, int_f_pvoid_pvoid_t fun, void* data)
646 SIMIX_process_on_exit(actor, [fun, data](bool failed) {
647 intptr_t status = failed ? SMX_EXIT_FAILURE : SMX_EXIT_SUCCESS;
648 fun(reinterpret_cast<void*>(status), data);
652 void SIMIX_process_on_exit(smx_actor_t actor, const std::function<void(int, void*)>& fun, void* data)
654 SIMIX_process_on_exit(actor, [fun, data](bool failed) { fun(failed ? SMX_EXIT_FAILURE : SMX_EXIT_SUCCESS, data); });
657 void SIMIX_process_on_exit(smx_actor_t actor, const std::function<void(bool /*failed*/)>& fun)
659 xbt_assert(actor, "current process not found: are you in maestro context ?");
660 actor->on_exit->emplace_back(fun);
663 /** @brief Restart a process, starting it again from the beginning. */
665 * @ingroup simix_process_management
666 * @brief Creates and runs a new SIMIX process.
668 * The structure and the corresponding thread are created and put in the list of ready processes.
670 * @param name a name for the process. It is for user-level information and can be nullptr.
671 * @param code the main function of the process
672 * @param data a pointer to any data one may want to attach to the new object. It is for user-level information and can
674 * It can be retrieved with the method ActorImpl::getUserData().
675 * @param host where the new agent is executed.
676 * @param properties the properties of the process
678 smx_actor_t simcall_process_create(const std::string& name, const simgrid::simix::ActorCode& code, void* data,
679 sg_host_t host, std::unordered_map<std::string, std::string>* properties)
681 smx_actor_t self = SIMIX_process_self();
682 return simgrid::simix::simcall([&name, &code, data, host, properties, self] {
683 return simgrid::kernel::actor::ActorImpl::create(name, code, data, host, properties, self).get();
687 void simcall_process_set_data(smx_actor_t process, void* data)
689 simgrid::simix::simcall([process, data] { process->set_user_data(data); });