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>
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 if (context_.get() != nullptr) /* the actor was not start()ed yet. This happens if its host was initially off */
65 context_->iwannadie = false; // don't let the simcall's yield() do a Context::stop(), to avoid infinite loops
66 actor::simcall([this] { s4u::Actor::on_destruction(*ciface()); });
67 if (context_.get() != nullptr)
68 context_->iwannadie = true;
72 /* Become an actor in the simulation
74 * Currently this can only be called by the main thread (once) and only work with some thread factories
75 * (currently ThreadContextFactory).
77 * In the future, it might be extended in order to attach other threads created by a third party library.
80 ActorImplPtr ActorImpl::attach(const std::string& name, void* data, s4u::Host* host,
81 const std::unordered_map<std::string, std::string>* properties)
83 // This is mostly a copy/paste from create(), it'd be nice to share some code between those two functions.
85 XBT_DEBUG("Attach actor %s on host '%s'", name.c_str(), host->get_cname());
87 if (not host->is_on()) {
88 XBT_WARN("Cannot attach actor '%s' on failed host '%s'", name.c_str(), host->get_cname());
89 throw HostFailureException(XBT_THROW_POINT, "Cannot attach actor on failed host.");
92 ActorImpl* actor = new ActorImpl(xbt::string(name), host);
94 actor->set_user_data(data);
95 actor->code_ = nullptr;
97 XBT_VERB("Create context %s", actor->get_cname());
98 xbt_assert(simix_global != nullptr, "simix is not initialized, please call MSG_init first");
99 actor->context_.reset(simix_global->context_factory->attach(actor));
102 if (properties != nullptr)
103 actor->set_properties(*properties);
105 /* Add the actor to it's host actor list */
106 host->pimpl_->add_actor(actor);
108 /* Now insert it in the global actor list and in the actors to run list */
109 simix_global->process_list[actor->get_pid()] = actor;
110 XBT_DEBUG("Inserting [%p] %s(%s) in the to_run list", actor, actor->get_cname(), host->get_cname());
111 simix_global->actors_to_run.push_back(actor);
112 intrusive_ptr_add_ref(actor);
114 auto* context = dynamic_cast<context::AttachContext*>(actor->context_.get());
115 xbt_assert(nullptr != context, "Not a suitable context");
116 context->attach_start();
118 /* The on_creation() signal must be delayed until there, where the pid and everything is set */
119 s4u::Actor::on_creation(*actor->ciface());
121 return ActorImplPtr(actor);
123 /** @brief Detach an actor attached with `attach()`
125 * This is called when the current actor has finished its job.
126 * Used in the main thread, it waits for the simulation to finish before returning. When it returns, the other
127 * simulated actors and the maestro are destroyed.
129 void ActorImpl::detach()
131 auto* context = dynamic_cast<context::AttachContext*>(context::Context::self());
132 if (context == nullptr)
133 xbt_die("Not a suitable context");
135 context->get_actor()->cleanup();
136 context->attach_stop();
139 void ActorImpl::cleanup()
143 if (has_to_auto_restart() && not get_host()->is_on()) {
144 XBT_DEBUG("Insert host %s to watched_hosts because it's off and %s needs to restart", get_host()->get_cname(),
146 watched_hosts.insert(get_host()->get_name());
150 // Execute the termination callbacks
151 bool failed = context_->iwannadie;
152 for (auto exit_fun = on_exit->crbegin(); exit_fun != on_exit->crend(); ++exit_fun)
158 /* cancel non-blocking activities */
159 for (auto activity : comms)
160 boost::static_pointer_cast<activity::CommImpl>(activity)->cancel();
163 XBT_DEBUG("%s@%s(%ld) should not run anymore", get_cname(), get_host()->get_cname(), get_pid());
165 if (this == simix_global->maestro_) /* Do not cleanup maestro */
168 XBT_DEBUG("Cleanup actor %s (%p), waiting synchro %p", get_cname(), this, waiting_synchro.get());
170 /* Unregister from the kill timer if any */
171 if (kill_timer != nullptr) {
172 kill_timer->remove();
173 kill_timer = nullptr;
176 simix_global->mutex.lock();
178 simix_global->process_list.erase(pid_);
179 if (host_ && host_actor_list_hook.is_linked())
180 host_->pimpl_->remove_actor(this);
181 if (not smx_destroy_list_hook.is_linked()) {
183 xbt_dynar_push_as(simix_global->dead_actors_vector, ActorImpl*, this);
185 simix_global->actors_to_destroy.push_back(*this);
188 simix_global->mutex.unlock();
190 context_->iwannadie = false; // don't let the simcall's yield() do a Context::stop(), to avoid infinite loops
191 actor::simcall([this] { s4u::Actor::on_termination(*ciface()); });
192 context_->iwannadie = true;
195 void ActorImpl::exit()
197 context_->iwannadie = true;
199 exception_ = nullptr;
201 /* destroy the blocking synchro if any */
202 if (waiting_synchro != nullptr) {
203 waiting_synchro->cancel();
204 waiting_synchro->state_ = activity::State::FAILED;
206 activity::ExecImplPtr exec = boost::dynamic_pointer_cast<activity::ExecImpl>(waiting_synchro);
207 activity::CommImplPtr comm = boost::dynamic_pointer_cast<activity::CommImpl>(waiting_synchro);
209 if (exec != nullptr) {
210 exec->clean_action();
211 } else if (comm != nullptr) {
212 comms.remove(waiting_synchro);
213 // Remove first occurrence of &actor->simcall:
214 auto i = boost::range::find(waiting_synchro->simcalls_, &simcall);
215 if (i != waiting_synchro->simcalls_.end())
216 waiting_synchro->simcalls_.remove(&simcall);
218 activity::ActivityImplPtr(waiting_synchro)->finish();
221 waiting_synchro = nullptr;
224 // Forcefully kill the actor if its host is turned off. Not a HostFailureException because you should not survive that
225 this->throw_exception(std::make_exception_ptr(ForcefulKillException(host_->is_on() ? "exited" : "host failed")));
228 void ActorImpl::kill(ActorImpl* actor)
230 xbt_assert(actor != simix_global->maestro_, "Killing maestro is a rather bad idea");
231 if (actor->finished_) {
232 XBT_DEBUG("Ignoring request to kill actor %s@%s that is already dead", actor->get_cname(),
233 actor->host_->get_cname());
237 XBT_DEBUG("Actor '%s'@%s is killing actor '%s'@%s", get_cname(), host_ ? host_->get_cname() : "", actor->get_cname(),
238 actor->host_ ? actor->host_->get_cname() : "");
242 if (std::find(begin(simix_global->actors_to_run), end(simix_global->actors_to_run), actor) ==
243 end(simix_global->actors_to_run) &&
245 XBT_DEBUG("Inserting %s in the to_run list", actor->get_cname());
246 simix_global->actors_to_run.push_back(actor);
250 void ActorImpl::kill_all()
252 for (auto const& kv : simix_global->process_list)
253 if (kv.second != this)
254 this->kill(kv.second);
257 void ActorImpl::set_kill_time(double kill_time)
259 if (kill_time <= SIMIX_get_clock())
261 XBT_DEBUG("Set kill time %f for actor %s@%s", kill_time, get_cname(), host_->get_cname());
262 kill_timer = simix::Timer::set(kill_time, [this] {
264 kill_timer = nullptr;
268 double ActorImpl::get_kill_time()
270 return kill_timer ? kill_timer->get_date() : 0;
273 void ActorImpl::yield()
275 XBT_DEBUG("Yield actor '%s'", get_cname());
277 /* Go into sleep and return control to maestro */
280 /* Ok, maestro returned control to us */
281 XBT_DEBUG("Control returned to me: '%s'", get_cname());
283 if (context_->iwannadie) {
284 XBT_DEBUG("Actor %s@%s is dead", get_cname(), host_->get_cname());
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_, "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 void ActorImpl::suspend()
357 XBT_DEBUG("Actor '%s' is already suspended", get_cname());
363 /* If the suspended actor is waiting on a sync, suspend its synchronization. */
364 if (waiting_synchro == nullptr) {
365 auto exec = new activity::ExecImpl();
366 exec->set_name("suspend").set_host(host_).set_flops_amount(0.0).start();
367 waiting_synchro = activity::ExecImplPtr(exec);
369 waiting_synchro->simcalls_.push_back(&simcall);
371 waiting_synchro->suspend();
374 void ActorImpl::resume()
376 XBT_IN("actor = %p", this);
378 if (context_->iwannadie) {
379 XBT_VERB("Ignoring request to suspend an actor that is currently dying.");
387 /* resume the synchronization that was blocking the resumed actor. */
389 waiting_synchro->resume();
394 activity::ActivityImplPtr ActorImpl::join(ActorImpl* actor, double timeout)
396 activity::ActivityImplPtr sleep = this->sleep(timeout);
397 actor->on_exit->emplace_back([sleep](bool) {
398 if (sleep->surf_action_)
399 sleep->surf_action_->finish(resource::Action::State::FINISHED);
404 activity::ActivityImplPtr ActorImpl::sleep(double duration)
406 if (not host_->is_on())
407 throw_exception(std::make_exception_ptr(HostFailureException(
408 XBT_THROW_POINT, std::string("Host ") + host_->get_cname() + " failed, you cannot sleep there.")));
410 auto sleep = new activity::SleepImpl();
411 sleep->set_name("sleep").set_host(host_).set_duration(duration).start();
412 return activity::SleepImplPtr(sleep);
415 void ActorImpl::throw_exception(std::exception_ptr e)
422 /* cancel the blocking synchro if any */
423 if (waiting_synchro) {
424 waiting_synchro->cancel();
426 activity::CommImplPtr comm = boost::dynamic_pointer_cast<activity::CommImpl>(waiting_synchro);
431 waiting_synchro = nullptr;
435 void ActorImpl::simcall_answer()
437 if (this != simix_global->maestro_) {
438 XBT_DEBUG("Answer simcall %s (%d) issued by %s (%p)", SIMIX_simcall_name(simcall.call_), (int)simcall.call_,
440 simcall.call_ = SIMCALL_NONE;
441 xbt_assert(not XBT_LOG_ISENABLED(simix_process, xbt_log_priority_debug) ||
442 std::find(begin(simix_global->actors_to_run), end(simix_global->actors_to_run), this) ==
443 end(simix_global->actors_to_run),
444 "Actor %p should not exist in actors_to_run!", this);
445 simix_global->actors_to_run.push_back(this);
449 void ActorImpl::set_host(s4u::Host* dest)
451 host_->pimpl_->remove_actor(this);
453 dest->pimpl_->add_actor(this);
456 ActorImplPtr ActorImpl::init(const std::string& name, s4u::Host* host)
458 ActorImpl* actor = new ActorImpl(xbt::string(name), host);
459 actor->set_ppid(this->pid_);
461 intrusive_ptr_add_ref(actor);
462 /* The on_creation() signal must be delayed until there, where the pid and everything is set */
463 s4u::Actor::on_creation(*actor->ciface());
465 return ActorImplPtr(actor);
468 ActorImpl* ActorImpl::start(const simix::ActorCode& code)
470 xbt_assert(code && host_ != nullptr, "Invalid parameters");
472 if (not host_->is_on()) {
473 XBT_WARN("Cannot launch actor '%s' on failed host '%s'", name_.c_str(), host_->get_cname());
474 intrusive_ptr_release(this);
475 throw HostFailureException(XBT_THROW_POINT, "Cannot start actor on failed host.");
479 XBT_VERB("Create context %s", get_cname());
480 context_.reset(simix_global->context_factory->create_context(simix::ActorCode(code), this));
482 XBT_DEBUG("Start context '%s'", get_cname());
484 /* Add the actor to its host's actor list */
485 host_->pimpl_->add_actor(this);
486 simix_global->process_list[pid_] = this;
488 /* Now insert it in the global actor list and in the actor to run list */
489 XBT_DEBUG("Inserting [%p] %s(%s) in the to_run list", this, get_cname(), host_->get_cname());
490 simix_global->actors_to_run.push_back(this);
495 ActorImplPtr ActorImpl::create(const std::string& name, const simix::ActorCode& code, void* data, s4u::Host* host,
496 const std::unordered_map<std::string, std::string>* properties, ActorImpl* parent_actor)
498 XBT_DEBUG("Start actor %s@'%s'", name.c_str(), host->get_cname());
501 if (parent_actor != nullptr)
502 actor = parent_actor->init(xbt::string(name), host);
504 actor = self()->init(xbt::string(name), host);
507 actor->set_user_data(data);
510 if (properties != nullptr)
511 actor->set_properties(*properties);
518 void create_maestro(const std::function<void()>& code)
520 /* Create maestro actor and initialize it */
521 ActorImpl* maestro = new ActorImpl(xbt::string(""), /*host*/ nullptr);
524 maestro->context_.reset(simix_global->context_factory->create_context(simix::ActorCode(), maestro));
526 maestro->context_.reset(simix_global->context_factory->create_maestro(simix::ActorCode(code), maestro));
529 maestro->simcall.issuer_ = maestro;
530 simix_global->maestro_ = maestro;
534 } // namespace kernel
535 } // namespace simgrid
537 int SIMIX_process_count() // XBT_ATTRIB_DEPRECATED_v329
539 return simix_global->process_list.size();
542 // XBT_DEPRECATED_v329
543 void* SIMIX_process_self_get_data()
545 smx_actor_t self = simgrid::kernel::actor::ActorImpl::self();
547 if (self == nullptr) {
550 return self->get_user_data();
553 // XBT_DEPRECATED_v329
554 void SIMIX_process_self_set_data(void* data)
556 simgrid::kernel::actor::ActorImpl::self()->set_user_data(data);
559 /* needs to be public and without simcall because it is called
560 by exceptions and logging events */
561 const char* SIMIX_process_self_get_name()
563 return SIMIX_is_maestro() ? "maestro" : simgrid::kernel::actor::ActorImpl::self()->get_cname();
567 * @brief Calling this function makes the process to yield.
569 * Only the current process can call this function, giving back the control to maestro.
571 * @param self the current process
574 /** @brief Returns the process from PID. */
575 smx_actor_t SIMIX_process_from_PID(aid_t PID)
577 auto item = simix_global->process_list.find(PID);
578 if (item == simix_global->process_list.end()) {
579 for (auto& a : simix_global->actors_to_destroy)
580 if (a.get_pid() == PID)
582 return nullptr; // Not found, even in the trash
587 void SIMIX_process_on_exit(smx_actor_t actor,
588 const std::function<void(bool /*failed*/)>& fun) // XBT_ATTRIB_DEPRECATED_v329
590 xbt_assert(actor, "current process not found: are you in maestro context ?");
591 actor->on_exit->emplace_back(fun);
594 /** @brief Restart a process, starting it again from the beginning. */
596 * @ingroup simix_process_management
597 * @brief Creates and runs a new SIMIX process.
599 * The structure and the corresponding thread are created and put in the list of ready processes.
601 * @param name a name for the process. It is for user-level information and can be nullptr.
602 * @param code the main function of the process
603 * @param data a pointer to any data one may want to attach to the new object. It is for user-level information and can
605 * It can be retrieved with the method ActorImpl::getUserData().
606 * @param host where the new agent is executed.
607 * @param properties the properties of the process
609 smx_actor_t simcall_process_create(const std::string& name, const simgrid::simix::ActorCode& code, void* data,
610 sg_host_t host, std::unordered_map<std::string, std::string>* properties)
612 smx_actor_t self = simgrid::kernel::actor::ActorImpl::self();
613 return simgrid::kernel::actor::simcall([&name, &code, data, host, properties, self] {
614 return simgrid::kernel::actor::ActorImpl::create(name, code, data, host, properties, self).get();
618 void simcall_process_set_data(smx_actor_t process, void* data)
620 simgrid::kernel::actor::simcall([process, data] { process->set_user_data(data); });