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)");
26 * @brief Returns the current agent.
28 * This functions returns the currently running SIMIX process.
30 * @return The SIMIX process
32 smx_actor_t SIMIX_process_self()
34 simgrid::kernel::context::Context* self_context = simgrid::kernel::context::Context::self();
36 return (self_context != nullptr) ? self_context->get_actor() : nullptr;
40 * @brief Returns whether a process has pending asynchronous communications.
41 * @return true if there are asynchronous communications in this process
44 int SIMIX_process_has_pending_comms(smx_actor_t process)
47 return process->comms.size() > 0;
54 static unsigned long maxpid = 0;
60 ActorImpl::ActorImpl(const simgrid::xbt::string& name, s4u::Host* host) : host_(host), name_(name), piface_(this)
63 simcall.issuer_ = this;
66 ActorImpl::~ActorImpl()
68 if (simix_global != nullptr && this != simix_global->maestro_process) {
69 if (context_.get() != nullptr) /* the actor was not start()ed yet. This happens if its host was initially off */
70 context_->iwannadie = false; // don't let the simcall's yield() do a Context::stop(), to avoid infinite loops
71 simgrid::kernel::actor::simcall([this] { simgrid::s4u::Actor::on_destruction(*ciface()); });
72 if (context_.get() != nullptr)
73 context_->iwannadie = true;
77 /* Become an actor in the simulation
79 * Currently this can only be called by the main thread (once) and only work with some thread factories
80 * (currently ThreadContextFactory).
82 * In the future, it might be extended in order to attach other threads created by a third party library.
85 ActorImplPtr ActorImpl::attach(const std::string& name, void* data, s4u::Host* host,
86 const std::unordered_map<std::string, std::string>* properties)
88 // This is mostly a copy/paste from create(), it'd be nice to share some code between those two functions.
90 XBT_DEBUG("Attach process %s on host '%s'", name.c_str(), host->get_cname());
92 if (not host->is_on()) {
93 XBT_WARN("Cannot launch process '%s' on failed host '%s'", name.c_str(), host->get_cname());
94 throw simgrid::HostFailureException(XBT_THROW_POINT, "Cannot attach actor on failed host.");
97 ActorImpl* actor = new ActorImpl(xbt::string(name), host);
99 actor->set_user_data(data);
100 actor->code_ = nullptr;
102 XBT_VERB("Create context %s", actor->get_cname());
103 xbt_assert(simix_global != nullptr, "simix is not initialized, please call MSG_init first");
104 actor->context_.reset(simix_global->context_factory->attach(actor));
107 if (properties != nullptr)
108 actor->set_properties(*properties);
110 /* Add the process to it's host process list */
111 host->pimpl_->process_list_.push_back(*actor);
113 /* Now insert it in the global process list and in the process to run list */
114 simix_global->process_list[actor->get_pid()] = actor;
115 XBT_DEBUG("Inserting [%p] %s(%s) in the to_run list", actor, actor->get_cname(), host->get_cname());
116 simix_global->actors_to_run.push_back(actor);
117 intrusive_ptr_add_ref(actor);
119 auto* context = dynamic_cast<simgrid::kernel::context::AttachContext*>(actor->context_.get());
120 xbt_assert(nullptr != context, "Not a suitable context");
121 context->attach_start();
123 /* The on_creation() signal must be delayed until there, where the pid and everything is set */
124 simgrid::s4u::Actor::on_creation(*actor->ciface());
126 return ActorImplPtr(actor);
128 /** @brief Detach an actor attached with `attach()`
130 * This is called when the current actor has finished its job.
131 * Used in the main thread, it waits for the simulation to finish before returning. When it returns, the other
132 * simulated actors and the maestro are destroyed.
134 void ActorImpl::detach()
136 auto* context = dynamic_cast<context::AttachContext*>(context::Context::self());
137 if (context == nullptr)
138 xbt_die("Not a suitable context");
140 context->get_actor()->cleanup();
141 context->attach_stop();
144 void ActorImpl::cleanup()
148 if (has_to_auto_restart() && not get_host()->is_on()) {
149 XBT_DEBUG("Insert host %s to watched_hosts because it's off and %s needs to restart", get_host()->get_cname(),
151 watched_hosts.insert(get_host()->get_name());
155 // Execute the termination callbacks
156 bool failed = context_->iwannadie;
157 for (auto exit_fun = on_exit->crbegin(); exit_fun != on_exit->crend(); ++exit_fun)
163 /* cancel non-blocking activities */
164 for (auto activity : comms)
165 boost::static_pointer_cast<activity::CommImpl>(activity)->cancel();
168 XBT_DEBUG("%s@%s(%ld) should not run anymore", get_cname(), get_host()->get_cname(), get_pid());
170 if (this == simix_global->maestro_process) /* Do not cleanup maestro */
173 XBT_DEBUG("Cleanup actor %s (%p), waiting synchro %p", get_cname(), this, waiting_synchro.get());
175 /* Unregister from the kill timer if any */
176 if (kill_timer != nullptr) {
177 kill_timer->remove();
178 kill_timer = nullptr;
181 simix_global->mutex.lock();
183 simix_global->process_list.erase(pid_);
184 if (host_ && host_process_list_hook.is_linked())
185 simgrid::xbt::intrusive_erase(host_->pimpl_->process_list_, *this);
186 if (not smx_destroy_list_hook.is_linked()) {
188 xbt_dynar_push_as(simix_global->dead_actors_vector, ActorImpl*, this);
190 simix_global->actors_to_destroy.push_back(*this);
193 simix_global->mutex.unlock();
195 context_->iwannadie = false; // don't let the simcall's yield() do a Context::stop(), to avoid infinite loops
196 simgrid::kernel::actor::simcall([this] { simgrid::s4u::Actor::on_termination(*ciface()); });
197 context_->iwannadie = true;
200 void ActorImpl::exit()
202 context_->iwannadie = true;
204 exception_ = nullptr;
206 /* destroy the blocking synchro if any */
207 if (waiting_synchro != nullptr) {
208 waiting_synchro->cancel();
209 waiting_synchro->state_ = SIMIX_FAILED;
211 activity::ExecImplPtr exec = boost::dynamic_pointer_cast<activity::ExecImpl>(waiting_synchro);
212 activity::CommImplPtr comm = boost::dynamic_pointer_cast<activity::CommImpl>(waiting_synchro);
214 if (exec != nullptr) {
215 exec->clean_action();
216 } else if (comm != nullptr) {
217 comms.remove(waiting_synchro);
218 // Remove first occurrence of &actor->simcall:
219 auto i = boost::range::find(waiting_synchro->simcalls_, &simcall);
220 if (i != waiting_synchro->simcalls_.end())
221 waiting_synchro->simcalls_.remove(&simcall);
223 activity::ActivityImplPtr(waiting_synchro)->finish();
226 waiting_synchro = nullptr;
229 // Forcefully kill the actor if its host is turned off. Not a HostFailureException because you should not survive that
230 this->throw_exception(std::make_exception_ptr(ForcefulKillException(host_->is_on() ? "exited" : "host failed")));
233 void ActorImpl::kill(ActorImpl* actor)
235 if (actor->finished_) {
236 XBT_DEBUG("Ignoring request to kill actor %s@%s that is already dead", actor->get_cname(),
237 actor->host_->get_cname());
241 XBT_DEBUG("Actor '%s'@%s is killing actor '%s'@%s", get_cname(), host_ ? host_->get_cname() : "", actor->get_cname(),
242 actor->host_ ? actor->host_->get_cname() : "");
246 if (std::find(begin(simix_global->actors_to_run), end(simix_global->actors_to_run), actor) ==
247 end(simix_global->actors_to_run) &&
249 XBT_DEBUG("Inserting %s in the to_run list", actor->get_cname());
250 simix_global->actors_to_run.push_back(actor);
254 void ActorImpl::kill_all()
256 for (auto const& kv : simix_global->process_list)
257 if (kv.second != this)
258 this->kill(kv.second);
261 void ActorImpl::set_kill_time(double kill_time)
263 if (kill_time <= SIMIX_get_clock())
265 XBT_DEBUG("Set kill time %f for actor %s@%s", kill_time, get_cname(), host_->get_cname());
266 kill_timer = simix::Timer::set(kill_time, [this] {
268 kill_timer = nullptr;
272 double ActorImpl::get_kill_time()
274 return kill_timer ? kill_timer->get_date() : 0;
277 void ActorImpl::yield()
279 XBT_DEBUG("Yield actor '%s'", get_cname());
281 /* Go into sleep and return control to maestro */
284 /* Ok, maestro returned control to us */
285 XBT_DEBUG("Control returned to me: '%s'", get_cname());
287 if (context_->iwannadie) {
288 XBT_DEBUG("Actor %s@%s is dead", get_cname(), host_->get_cname());
289 // throw simgrid::kernel::context::ForcefulKillException(); Does not seem to properly kill the actor
295 XBT_DEBUG("Hey! I'm suspended.");
297 xbt_assert(exception_ == nullptr, "Gasp! This exception may be lost by subsequent calls.");
302 if (exception_ != nullptr) {
303 XBT_DEBUG("Wait, maestro left me an exception");
304 std::exception_ptr exception = std::move(exception_);
305 exception_ = nullptr;
306 std::rethrow_exception(std::move(exception));
309 if (SMPI_switch_data_segment && not finished_) {
310 SMPI_switch_data_segment(iface());
314 /** This actor will be terminated automatically when the last non-daemon actor finishes */
315 void ActorImpl::daemonize()
319 simix_global->daemons.push_back(this);
323 void ActorImpl::undaemonize()
326 auto& vect = simix_global->daemons;
327 auto it = std::find(vect.begin(), vect.end(), this);
328 xbt_assert(it != vect.end(), "The dying daemon is not a daemon after all. Please report that bug.");
329 /* Don't move the whole content since we don't really care about the order */
331 std::swap(*it, vect.back());
337 s4u::Actor* ActorImpl::restart()
339 xbt_assert(this != simix_global->maestro_process, "Restarting maestro is not supported");
341 XBT_DEBUG("Restarting actor %s on %s", get_cname(), host_->get_cname());
343 // retrieve the arguments of the old actor
344 ProcessArg arg = ProcessArg(host_, this);
346 // kill the old actor
347 context::Context::self()->get_actor()->kill(this);
349 // start the new actor
351 ActorImpl::create(arg.name, std::move(arg.code), arg.data, arg.host, arg.properties.get(), nullptr);
352 *actor->on_exit = std::move(*arg.on_exit);
353 actor->set_kill_time(arg.kill_time);
354 actor->set_auto_restart(arg.auto_restart);
356 return actor->ciface();
359 void ActorImpl::suspend(ActorImpl* issuer)
362 XBT_DEBUG("Actor '%s' is already suspended", get_cname());
368 /* If the suspended actor is waiting on a sync, suspend its synchronization. */
369 if (waiting_synchro == nullptr) {
370 activity::ExecImpl* exec = new activity::ExecImpl();
371 exec->set_name("suspend").set_host(host_).set_flops_amount(0.0).start();
372 waiting_synchro = activity::ExecImplPtr(exec);
374 waiting_synchro->simcalls_.push_back(&simcall);
376 waiting_synchro->suspend();
379 void ActorImpl::resume()
381 XBT_IN("actor = %p", this);
383 if (context_->iwannadie) {
384 XBT_VERB("Ignoring request to suspend an actor that is currently dying.");
392 /* resume the synchronization that was blocking the resumed actor. */
394 waiting_synchro->resume();
399 activity::ActivityImplPtr ActorImpl::join(ActorImpl* actor, double timeout)
401 activity::ActivityImplPtr sleep = this->sleep(timeout);
402 SIMIX_process_on_exit(actor, [sleep](bool) {
403 if (sleep->surf_action_)
404 sleep->surf_action_->finish(resource::Action::State::FINISHED);
409 activity::ActivityImplPtr ActorImpl::sleep(double duration)
411 if (not host_->is_on())
412 throw_exception(std::make_exception_ptr(simgrid::HostFailureException(
413 XBT_THROW_POINT, std::string("Host ") + host_->get_cname() + " failed, you cannot sleep there.")));
415 activity::SleepImpl* sleep = new activity::SleepImpl();
416 (*sleep).set_name("sleep").set_host(host_).set_duration(duration).start();
417 return activity::SleepImplPtr(sleep);
420 void ActorImpl::throw_exception(std::exception_ptr e)
427 /* cancel the blocking synchro if any */
428 if (waiting_synchro) {
429 waiting_synchro->cancel();
431 activity::CommImplPtr comm = boost::dynamic_pointer_cast<activity::CommImpl>(waiting_synchro);
436 waiting_synchro = nullptr;
440 void ActorImpl::simcall_answer()
442 if (this != simix_global->maestro_process){
443 XBT_DEBUG("Answer simcall %s (%d) issued by %s (%p)", SIMIX_simcall_name(simcall.call_), (int)simcall.call_,
445 simcall.call_ = SIMCALL_NONE;
446 xbt_assert(not XBT_LOG_ISENABLED(simix_process, xbt_log_priority_debug) ||
447 std::find(begin(simix_global->actors_to_run), end(simix_global->actors_to_run), this) ==
448 end(simix_global->actors_to_run),
449 "Actor %p should not exist in actors_to_run!", this);
450 simix_global->actors_to_run.push_back(this);
454 void ActorImpl::set_host(s4u::Host* dest)
456 xbt::intrusive_erase(host_->pimpl_->process_list_, *this);
458 dest->pimpl_->process_list_.push_back(*this);
461 ActorImplPtr ActorImpl::init(const std::string& name, s4u::Host* host)
463 ActorImpl* actor = new ActorImpl(xbt::string(name), host);
464 actor->set_ppid(this->pid_);
466 intrusive_ptr_add_ref(actor);
467 /* The on_creation() signal must be delayed until there, where the pid and everything is set */
468 s4u::Actor::on_creation(*actor->ciface());
470 return ActorImplPtr(actor);
473 ActorImpl* ActorImpl::start(const simix::ActorCode& code)
475 xbt_assert(code && host_ != nullptr, "Invalid parameters");
477 if (not host_->is_on()) {
478 XBT_WARN("Cannot launch actor '%s' on failed host '%s'", name_.c_str(), host_->get_cname());
479 intrusive_ptr_release(this);
480 throw simgrid::HostFailureException(XBT_THROW_POINT, "Cannot start actor on failed host.");
484 XBT_VERB("Create context %s", get_cname());
485 context_.reset(simix_global->context_factory->create_context(simix::ActorCode(code), this));
487 XBT_DEBUG("Start context '%s'", get_cname());
489 /* Add the actor to its host's actor list */
490 host_->pimpl_->process_list_.push_back(*this);
491 simix_global->process_list[pid_] = this;
493 /* Now insert it in the global actor list and in the actor to run list */
494 XBT_DEBUG("Inserting [%p] %s(%s) in the to_run list", this, get_cname(), host_->get_cname());
495 simix_global->actors_to_run.push_back(this);
500 ActorImplPtr ActorImpl::create(const std::string& name, const simix::ActorCode& code, void* data, s4u::Host* host,
501 const std::unordered_map<std::string, std::string>* properties, ActorImpl* parent_actor)
503 XBT_DEBUG("Start actor %s@'%s'", name.c_str(), host->get_cname());
506 if (parent_actor != nullptr)
507 actor = parent_actor->init(xbt::string(name), host);
509 actor = SIMIX_process_self()->init(xbt::string(name), host);
512 actor->set_user_data(data);
515 if (properties != nullptr)
516 actor->set_properties(*properties);
523 void create_maestro(const std::function<void()>& code)
525 /* Create maestro actor and initialize it */
526 ActorImpl* maestro = new ActorImpl(xbt::string(""), /*host*/ nullptr);
529 maestro->context_.reset(simix_global->context_factory->create_context(simix::ActorCode(), maestro));
531 maestro->context_.reset(simix_global->context_factory->create_maestro(simix::ActorCode(code), maestro));
534 maestro->simcall.issuer_ = maestro;
535 simix_global->maestro_process = maestro;
539 } // namespace kernel
540 } // namespace simgrid
542 void SIMIX_process_detach() // deprecated v3.25
544 simgrid::kernel::actor::ActorImpl::detach();
547 smx_actor_t SIMIX_process_attach(const char* name, void* data, const char* hostname,
548 std::unordered_map<std::string, std::string>* properties,
549 smx_actor_t /*parent_process*/) // deprecated 3.25
551 return simgrid::kernel::actor::ActorImpl::attach(name, data, sg_host_by_name(hostname), properties).get();
554 int SIMIX_process_count()
556 return simix_global->process_list.size();
559 void* SIMIX_process_self_get_data() // deprecated
561 smx_actor_t self = SIMIX_process_self();
563 if (self == nullptr) {
566 return self->get_user_data();
569 void SIMIX_process_self_set_data(void* data) // deprecated
571 SIMIX_process_self()->set_user_data(data);
574 /* needs to be public and without simcall because it is called
575 by exceptions and logging events */
576 const char* SIMIX_process_self_get_name()
579 smx_actor_t process = SIMIX_process_self();
580 if (process == nullptr || process == simix_global->maestro_process)
583 return process->get_cname();
587 * @brief Calling this function makes the process to yield.
589 * Only the current process can call this function, giving back the control to maestro.
591 * @param self the current process
594 /** @brief Returns the list of processes to run.
597 const std::vector<smx_actor_t>& simgrid::simix::process_get_runnable()
599 return simix_global->actors_to_run;
602 /** @brief Returns the process from PID. */
603 smx_actor_t SIMIX_process_from_PID(aid_t PID)
605 auto item = simix_global->process_list.find(PID);
606 if (item == simix_global->process_list.end()) {
607 for (auto& a : simix_global->actors_to_destroy)
608 if (a.get_pid() == PID)
610 return nullptr; // Not found, even in the trash
615 void SIMIX_process_on_exit(smx_actor_t actor, int_f_pvoid_pvoid_t fun, void* data)
617 SIMIX_process_on_exit(actor, [fun, data](bool failed) {
618 intptr_t status = failed ? SMX_EXIT_FAILURE : SMX_EXIT_SUCCESS;
619 fun(reinterpret_cast<void*>(status), data);
623 void SIMIX_process_on_exit(smx_actor_t actor, const std::function<void(int, void*)>& fun, void* data)
625 SIMIX_process_on_exit(actor, [fun, data](bool failed) { fun(failed ? SMX_EXIT_FAILURE : SMX_EXIT_SUCCESS, data); });
628 void SIMIX_process_on_exit(smx_actor_t actor, const std::function<void(bool /*failed*/)>& fun)
630 xbt_assert(actor, "current process not found: are you in maestro context ?");
631 actor->on_exit->emplace_back(fun);
634 /** @brief Restart a process, starting it again from the beginning. */
636 * @ingroup simix_process_management
637 * @brief Creates and runs a new SIMIX process.
639 * The structure and the corresponding thread are created and put in the list of ready processes.
641 * @param name a name for the process. It is for user-level information and can be nullptr.
642 * @param code the main function of the process
643 * @param data a pointer to any data one may want to attach to the new object. It is for user-level information and can
645 * It can be retrieved with the method ActorImpl::getUserData().
646 * @param host where the new agent is executed.
647 * @param properties the properties of the process
649 smx_actor_t simcall_process_create(const std::string& name, const simgrid::simix::ActorCode& code, void* data,
650 sg_host_t host, std::unordered_map<std::string, std::string>* properties)
652 smx_actor_t self = SIMIX_process_self();
653 return simgrid::kernel::actor::simcall([&name, &code, data, host, properties, self] {
654 return simgrid::kernel::actor::ActorImpl::create(name, code, data, host, properties, self).get();
658 void simcall_process_set_data(smx_actor_t process, void* data)
660 simgrid::kernel::actor::simcall([process, data] { process->set_user_data(data); });