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/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>
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;
48 ActorImpl* ActorImpl::self()
50 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;
61 ActorImpl::~ActorImpl()
63 if (simix_global != nullptr && this != simix_global->maestro_)
64 s4u::Actor::on_destruction(*ciface());
67 /* Become an actor in the simulation
69 * Currently this can only be called by the main thread (once) and only work with some thread factories
70 * (currently ThreadContextFactory).
72 * In the future, it might be extended in order to attach other threads created by a third party library.
75 ActorImplPtr ActorImpl::attach(const std::string& name, void* data, s4u::Host* host,
76 const std::unordered_map<std::string, std::string>* properties)
78 // This is mostly a copy/paste from create(), it'd be nice to share some code between those two functions.
80 XBT_DEBUG("Attach actor %s on host '%s'", name.c_str(), host->get_cname());
82 if (not host->is_on()) {
83 XBT_WARN("Cannot attach actor '%s' on failed host '%s'", name.c_str(), host->get_cname());
84 throw HostFailureException(XBT_THROW_POINT, "Cannot attach actor on failed host.");
87 ActorImpl* actor = new ActorImpl(xbt::string(name), host);
89 actor->set_user_data(data);
90 actor->code_ = nullptr;
92 XBT_VERB("Create context %s", actor->get_cname());
93 xbt_assert(simix_global != nullptr, "simix is not initialized, please call MSG_init first");
94 actor->context_.reset(simix_global->context_factory->attach(actor));
97 if (properties != nullptr)
98 actor->set_properties(*properties);
100 /* Add the actor to it's host actor list */
101 host->pimpl_->add_actor(actor);
103 /* Now insert it in the global actor list and in the actors to run list */
104 simix_global->process_list[actor->get_pid()] = actor;
105 XBT_DEBUG("Inserting [%p] %s(%s) in the to_run list", actor, actor->get_cname(), host->get_cname());
106 simix_global->actors_to_run.push_back(actor);
107 intrusive_ptr_add_ref(actor);
109 auto* context = dynamic_cast<context::AttachContext*>(actor->context_.get());
110 xbt_assert(nullptr != context, "Not a suitable context");
111 context->attach_start();
113 /* The on_creation() signal must be delayed until there, where the pid and everything is set */
114 s4u::Actor::on_creation(*actor->ciface());
116 return ActorImplPtr(actor);
118 /** @brief Detach an actor attached with `attach()`
120 * This is called when the current actor has finished its job.
121 * Used in the main thread, it waits for the simulation to finish before returning. When it returns, the other
122 * simulated actors and the maestro are destroyed.
124 void ActorImpl::detach()
126 auto* context = dynamic_cast<context::AttachContext*>(context::Context::self());
127 if (context == nullptr)
128 xbt_die("Not a suitable context");
130 context->get_actor()->cleanup();
131 context->attach_stop();
134 void ActorImpl::cleanup_from_simix()
136 const std::lock_guard<std::mutex> lock(simix_global->mutex);
137 simix_global->process_list.erase(pid_);
138 if (host_ && host_actor_list_hook.is_linked())
139 host_->pimpl_->remove_actor(this);
140 if (not smx_destroy_list_hook.is_linked()) {
142 xbt_dynar_push_as(simix_global->dead_actors_vector, ActorImpl*, this);
144 simix_global->actors_to_destroy.push_back(*this);
148 void ActorImpl::cleanup()
152 if (has_to_auto_restart() && not get_host()->is_on()) {
153 XBT_DEBUG("Insert host %s to watched_hosts because it's off and %s needs to restart", get_host()->get_cname(),
155 watched_hosts.insert(get_host()->get_name());
159 // Execute the termination callbacks
160 bool failed = context_->wannadie();
161 for (auto exit_fun = on_exit->crbegin(); exit_fun != on_exit->crend(); ++exit_fun)
167 /* cancel non-blocking activities */
168 for (auto activity : comms)
169 boost::static_pointer_cast<activity::CommImpl>(activity)->cancel();
172 XBT_DEBUG("%s@%s(%ld) should not run anymore", get_cname(), get_host()->get_cname(), get_pid());
174 if (this == simix_global->maestro_) /* Do not cleanup maestro */
177 XBT_DEBUG("Cleanup actor %s (%p), waiting synchro %p", get_cname(), this, waiting_synchro.get());
179 /* Unregister from the kill timer if any */
180 if (kill_timer != nullptr) {
181 kill_timer->remove();
182 kill_timer = nullptr;
184 cleanup_from_simix();
186 context_->set_wannadie(false); // don't let the simcall's yield() do a Context::stop(), to avoid infinite loops
187 actor::simcall([this] { s4u::Actor::on_termination(*ciface()); });
188 context_->set_wannadie();
191 void ActorImpl::exit()
193 context_->set_wannadie();
195 exception_ = nullptr;
197 /* destroy the blocking synchro if any */
198 if (waiting_synchro != nullptr) {
199 waiting_synchro->cancel();
200 waiting_synchro->state_ = activity::State::FAILED;
202 activity::ExecImplPtr exec = boost::dynamic_pointer_cast<activity::ExecImpl>(waiting_synchro);
203 activity::CommImplPtr comm = boost::dynamic_pointer_cast<activity::CommImpl>(waiting_synchro);
205 if (exec != nullptr) {
206 exec->clean_action();
207 } else if (comm != nullptr) {
208 comms.remove(waiting_synchro);
209 // Remove first occurrence of &actor->simcall:
210 auto i = boost::range::find(waiting_synchro->simcalls_, &simcall);
211 if (i != waiting_synchro->simcalls_.end())
212 waiting_synchro->simcalls_.remove(&simcall);
214 activity::ActivityImplPtr(waiting_synchro)->finish();
217 waiting_synchro = nullptr;
220 // Forcefully kill the actor if its host is turned off. Not a HostFailureException because you should not survive that
221 this->throw_exception(std::make_exception_ptr(ForcefulKillException(host_->is_on() ? "exited" : "host failed")));
224 void ActorImpl::kill(ActorImpl* actor)
226 xbt_assert(actor != simix_global->maestro_, "Killing maestro is a rather bad idea");
227 if (actor->finished_) {
228 XBT_DEBUG("Ignoring request to kill actor %s@%s that is already dead", actor->get_cname(),
229 actor->host_->get_cname());
233 XBT_DEBUG("Actor '%s'@%s is killing actor '%s'@%s", get_cname(), host_ ? host_->get_cname() : "", actor->get_cname(),
234 actor->host_ ? actor->host_->get_cname() : "");
239 XBT_DEBUG("Go on, this is a suicide,");
240 } else if (std::find(begin(simix_global->actors_to_run), end(simix_global->actors_to_run), actor) !=
241 end(simix_global->actors_to_run)) {
242 XBT_DEBUG("Actor %s is already in the to_run list", actor->get_cname());
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_->wannadie()) {
283 XBT_DEBUG("Actor %s@%s is dead", get_cname(), host_->get_cname());
289 XBT_DEBUG("Hey! I'm suspended.");
291 xbt_assert(exception_ == nullptr, "Gasp! This exception may be lost by subsequent calls.");
296 if (exception_ != nullptr) {
297 XBT_DEBUG("Wait, maestro left me an exception");
298 std::exception_ptr exception = std::move(exception_);
299 exception_ = nullptr;
300 std::rethrow_exception(std::move(exception));
303 if (SMPI_switch_data_segment && not finished_) {
304 SMPI_switch_data_segment(iface());
308 /** This actor will be terminated automatically when the last non-daemon actor finishes */
309 void ActorImpl::daemonize()
313 simix_global->daemons.push_back(this);
317 void ActorImpl::undaemonize()
320 auto& vect = simix_global->daemons;
321 auto it = std::find(vect.begin(), vect.end(), this);
322 xbt_assert(it != vect.end(), "The dying daemon is not a daemon after all. Please report that bug.");
323 /* Don't move the whole content since we don't really care about the order */
325 std::swap(*it, vect.back());
331 s4u::Actor* ActorImpl::restart()
333 xbt_assert(this != simix_global->maestro_, "Restarting maestro is not supported");
335 XBT_DEBUG("Restarting actor %s on %s", get_cname(), host_->get_cname());
337 // retrieve the arguments of the old actor
338 ProcessArg arg = ProcessArg(host_, this);
340 // kill the old actor
341 context::Context::self()->get_actor()->kill(this);
343 // start the new actor
345 ActorImpl::create(arg.name, std::move(arg.code), arg.data, arg.host, arg.properties.get(), nullptr);
346 *actor->on_exit = std::move(*arg.on_exit);
347 actor->set_kill_time(arg.kill_time);
348 actor->set_auto_restart(arg.auto_restart);
350 return actor->ciface();
353 void ActorImpl::suspend()
356 XBT_DEBUG("Actor '%s' is already suspended", get_cname());
362 /* If the suspended actor is waiting on a sync, suspend its synchronization. */
363 if (waiting_synchro == nullptr) {
364 auto exec = new activity::ExecImpl();
365 exec->set_name("suspend").set_host(host_).set_flops_amount(0.0).start();
366 waiting_synchro = activity::ExecImplPtr(exec);
368 waiting_synchro->simcalls_.push_back(&simcall);
370 waiting_synchro->suspend();
373 void ActorImpl::resume()
375 XBT_IN("actor = %p", this);
377 if (context_->wannadie()) {
378 XBT_VERB("Ignoring request to suspend an actor that is currently dying.");
386 /* resume the synchronization that was blocking the resumed actor. */
388 waiting_synchro->resume();
393 activity::ActivityImplPtr ActorImpl::join(const ActorImpl* actor, double timeout)
395 activity::ActivityImplPtr sleep = this->sleep(timeout);
396 actor->on_exit->emplace_back([sleep](bool) {
397 if (sleep->surf_action_)
398 sleep->surf_action_->finish(resource::Action::State::FINISHED);
403 activity::ActivityImplPtr ActorImpl::sleep(double duration)
405 if (not host_->is_on())
406 throw_exception(std::make_exception_ptr(HostFailureException(
407 XBT_THROW_POINT, std::string("Host ") + host_->get_cname() + " failed, you cannot sleep there.")));
409 auto sleep = new activity::SleepImpl();
410 sleep->set_name("sleep").set_host(host_).set_duration(duration).start();
411 return activity::SleepImplPtr(sleep);
414 void ActorImpl::throw_exception(std::exception_ptr e)
421 /* cancel the blocking synchro if any */
422 if (waiting_synchro) {
423 waiting_synchro->cancel();
425 activity::CommImplPtr comm = boost::dynamic_pointer_cast<activity::CommImpl>(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 simcall.call_ = SIMCALL_NONE;
440 xbt_assert(not XBT_LOG_ISENABLED(simix_process, xbt_log_priority_debug) ||
441 std::find(begin(simix_global->actors_to_run), end(simix_global->actors_to_run), this) ==
442 end(simix_global->actors_to_run),
443 "Actor %p should not exist in actors_to_run!", this);
444 simix_global->actors_to_run.push_back(this);
448 void ActorImpl::set_host(s4u::Host* dest)
450 host_->pimpl_->remove_actor(this);
452 dest->pimpl_->add_actor(this);
455 ActorImplPtr ActorImpl::init(const std::string& name, s4u::Host* host)
457 ActorImpl* actor = new ActorImpl(xbt::string(name), host);
458 actor->set_ppid(this->pid_);
460 intrusive_ptr_add_ref(actor);
461 /* The on_creation() signal must be delayed until there, where the pid and everything is set */
462 s4u::Actor::on_creation(*actor->ciface());
464 return ActorImplPtr(actor);
467 ActorImpl* ActorImpl::start(const ActorCode& code)
469 xbt_assert(code && host_ != nullptr, "Invalid parameters");
471 if (not host_->is_on()) {
472 XBT_WARN("Cannot launch actor '%s' on failed host '%s'", name_.c_str(), host_->get_cname());
473 intrusive_ptr_release(this);
474 throw HostFailureException(XBT_THROW_POINT, "Cannot start actor on failed host.");
478 XBT_VERB("Create context %s", get_cname());
479 context_.reset(simix_global->context_factory->create_context(ActorCode(code), this));
481 XBT_DEBUG("Start context '%s'", get_cname());
483 /* Add the actor to its host's actor list */
484 host_->pimpl_->add_actor(this);
485 simix_global->process_list[pid_] = this;
487 /* Now insert it in the global actor list and in the actor to run list */
488 XBT_DEBUG("Inserting [%p] %s(%s) in the to_run list", this, get_cname(), host_->get_cname());
489 simix_global->actors_to_run.push_back(this);
494 ActorImplPtr ActorImpl::create(const std::string& name, const ActorCode& code, void* data, s4u::Host* host,
495 const std::unordered_map<std::string, std::string>* properties, ActorImpl* parent_actor)
497 XBT_DEBUG("Start actor %s@'%s'", name.c_str(), host->get_cname());
500 if (parent_actor != nullptr)
501 actor = parent_actor->init(xbt::string(name), host);
503 actor = self()->init(xbt::string(name), host);
506 actor->set_user_data(data);
509 if (properties != nullptr)
510 actor->set_properties(*properties);
517 void create_maestro(const std::function<void()>& code)
519 /* Create maestro actor and initialize it */
520 ActorImpl* maestro = new ActorImpl(xbt::string(""), /*host*/ nullptr);
523 maestro->context_.reset(simix_global->context_factory->create_context(ActorCode(), maestro));
525 maestro->context_.reset(simix_global->context_factory->create_maestro(ActorCode(code), maestro));
528 maestro->simcall.issuer_ = maestro;
529 simix_global->maestro_ = maestro;
533 } // namespace kernel
534 } // namespace simgrid
536 int SIMIX_process_count() // XBT_ATTRIB_DEPRECATED_v329
538 return simix_global->process_list.size();
541 // XBT_DEPRECATED_v329
542 void* SIMIX_process_self_get_data()
544 smx_actor_t self = simgrid::kernel::actor::ActorImpl::self();
546 if (self == nullptr) {
549 return self->get_user_data();
552 // XBT_DEPRECATED_v329
553 void SIMIX_process_self_set_data(void* data)
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 /** @brief Restart a process, starting it again from the beginning. */
595 * @ingroup simix_process_management
596 * @brief Creates and runs a new SIMIX process.
598 * The structure and the corresponding thread are created and put in the list of ready processes.
600 * @param name a name for the process. It is for user-level information and can be nullptr.
601 * @param code the main function of the process
602 * @param data a pointer to any data one may want to attach to the new object. It is for user-level information and can
604 * It can be retrieved with the method ActorImpl::getUserData().
605 * @param host where the new agent is executed.
606 * @param properties the properties of the process
608 smx_actor_t simcall_process_create(const std::string& name, const simgrid::kernel::actor::ActorCode& code, void* data,
609 sg_host_t host, std::unordered_map<std::string, std::string>* properties)
611 smx_actor_t self = simgrid::kernel::actor::ActorImpl::self();
612 return simgrid::kernel::actor::simcall([&name, &code, data, host, properties, self] {
613 return simgrid::kernel::actor::ActorImpl::create(name, code, data, host, properties, self).get();
617 void simcall_process_set_data(smx_actor_t process, void* data) // XBT_ATTRIB_DEPRECATED_v329
619 simgrid::kernel::actor::simcall([process, data] { process->set_user_data(data); });