1 /* Copyright (c) 2007-2021. 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/AppSide.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;
43 unsigned long get_maxpid()
47 ActorImpl* ActorImpl::by_PID(aid_t PID)
49 auto item = simix_global->process_list.find(PID);
50 if (item != simix_global->process_list.end())
54 for (auto& a : simix_global->actors_to_destroy)
55 if (a.get_pid() == PID)
57 return nullptr; // Not found, even in the trash
60 ActorImpl* ActorImpl::self()
62 const context::Context* self_context = context::Context::self();
64 return (self_context != nullptr) ? self_context->get_actor() : nullptr;
67 ActorImpl::ActorImpl(xbt::string name, s4u::Host* host) : host_(host), name_(std::move(name)), piface_(this)
70 simcall_.issuer_ = this;
71 stacksize_ = smx_context_stack_size;
74 ActorImpl::~ActorImpl()
76 if (simix_global != nullptr && this != simix_global->maestro_)
77 s4u::Actor::on_destruction(*get_ciface());
80 /* Become an actor in the simulation
82 * Currently this can only be called by the main thread (once) and only work with some thread factories
83 * (currently ThreadContextFactory).
85 * In the future, it might be extended in order to attach other threads created by a third party library.
88 ActorImplPtr ActorImpl::attach(const std::string& name, void* data, s4u::Host* host,
89 const std::unordered_map<std::string, std::string>* properties)
91 // This is mostly a copy/paste from create(), it'd be nice to share some code between those two functions.
93 XBT_DEBUG("Attach actor %s on host '%s'", name.c_str(), host->get_cname());
95 if (not host->is_on()) {
96 XBT_WARN("Cannot attach actor '%s' on failed host '%s'", name.c_str(), host->get_cname());
97 throw HostFailureException(XBT_THROW_POINT, "Cannot attach actor on failed host.");
100 auto* actor = new ActorImpl(xbt::string(name), host);
102 actor->set_user_data(data);
103 actor->code_ = nullptr;
105 XBT_VERB("Create context %s", actor->get_cname());
106 xbt_assert(simix_global != nullptr, "simix is not initialized, please call MSG_init first");
107 actor->context_.reset(simix_global->context_factory->attach(actor));
110 if (properties != nullptr)
111 actor->set_properties(*properties);
113 /* Add the actor to it's host actor list */
114 host->pimpl_->add_actor(actor);
116 /* Now insert it in the global actor list and in the actors to run list */
117 simix_global->process_list[actor->get_pid()] = actor;
118 XBT_DEBUG("Inserting [%p] %s(%s) in the to_run list", actor, actor->get_cname(), host->get_cname());
119 simix_global->actors_to_run.push_back(actor);
120 intrusive_ptr_add_ref(actor);
122 auto* context = dynamic_cast<context::AttachContext*>(actor->context_.get());
123 xbt_assert(nullptr != context, "Not a suitable context");
124 context->attach_start();
126 /* The on_creation() signal must be delayed until there, where the pid and everything is set */
127 s4u::Actor::on_creation(*actor->get_ciface());
129 return ActorImplPtr(actor);
131 /** @brief Detach an actor attached with `attach()`
133 * This is called when the current actor has finished its job.
134 * Used in the main thread, it waits for the simulation to finish before returning. When it returns, the other
135 * simulated actors and the maestro are destroyed.
137 void ActorImpl::detach()
139 auto* context = dynamic_cast<context::AttachContext*>(context::Context::self());
140 if (context == nullptr)
141 xbt_die("Not a suitable context");
143 context->get_actor()->cleanup();
144 context->attach_stop();
147 void ActorImpl::cleanup_from_simix()
149 const std::lock_guard<std::mutex> lock(simix_global->mutex);
150 simix_global->process_list.erase(pid_);
151 if (host_ && host_actor_list_hook.is_linked())
152 host_->pimpl_->remove_actor(this);
153 if (not smx_destroy_list_hook.is_linked()) {
155 xbt_dynar_push_as(simix_global->dead_actors_vector, ActorImpl*, this);
157 simix_global->actors_to_destroy.push_back(*this);
161 void ActorImpl::cleanup()
165 if (has_to_auto_restart() && not get_host()->is_on()) {
166 XBT_DEBUG("Insert host %s to watched_hosts because it's off and %s needs to restart", get_host()->get_cname(),
168 watched_hosts().insert(get_host()->get_name());
172 // Execute the termination callbacks
173 bool failed = context_->wannadie();
174 for (auto exit_fun = on_exit->crbegin(); exit_fun != on_exit->crend(); ++exit_fun)
180 /* cancel non-blocking activities */
181 for (auto activity : activities_)
185 XBT_DEBUG("%s@%s(%ld) should not run anymore", get_cname(), get_host()->get_cname(), get_pid());
187 if (this == simix_global->maestro_) /* Do not cleanup maestro */
190 XBT_DEBUG("Cleanup actor %s (%p), waiting synchro %p", get_cname(), this, waiting_synchro_.get());
192 /* Unregister associated timers if any */
193 if (kill_timer_ != nullptr) {
194 kill_timer_->remove();
195 kill_timer_ = nullptr;
197 if (simcall_.timeout_cb_) {
198 simcall_.timeout_cb_->remove();
199 simcall_.timeout_cb_ = nullptr;
202 cleanup_from_simix();
204 context_->set_wannadie(false); // don't let the simcall's yield() do a Context::stop(), to avoid infinite loops
205 actor::simcall([this] { s4u::Actor::on_termination(*get_ciface()); });
206 context_->set_wannadie();
209 void ActorImpl::exit()
211 context_->set_wannadie();
213 exception_ = nullptr;
215 /* destroy the blocking synchro if any */
216 if (waiting_synchro_ != nullptr) {
217 waiting_synchro_->cancel();
218 waiting_synchro_->state_ = activity::State::FAILED;
220 activity::ExecImplPtr exec = boost::dynamic_pointer_cast<activity::ExecImpl>(waiting_synchro_);
221 activity::CommImplPtr comm = boost::dynamic_pointer_cast<activity::CommImpl>(waiting_synchro_);
223 if (exec != nullptr) {
224 exec->clean_action();
225 } else if (comm != nullptr) {
226 // Remove first occurrence of &actor->simcall:
227 auto i = boost::range::find(waiting_synchro_->simcalls_, &simcall_);
228 if (i != waiting_synchro_->simcalls_.end())
229 waiting_synchro_->simcalls_.remove(&simcall_);
231 activity::ActivityImplPtr(waiting_synchro_)->finish();
234 activities_.remove(waiting_synchro_);
235 waiting_synchro_ = nullptr;
238 // Forcefully kill the actor if its host is turned off. Not a HostFailureException because you should not survive that
239 this->throw_exception(std::make_exception_ptr(ForcefulKillException(host_->is_on() ? "exited" : "host failed")));
242 void ActorImpl::kill(ActorImpl* actor) const
244 xbt_assert(actor != simix_global->maestro_, "Killing maestro is a rather bad idea");
245 if (actor->finished_) {
246 XBT_DEBUG("Ignoring request to kill actor %s@%s that is already dead", actor->get_cname(),
247 actor->host_->get_cname());
251 XBT_DEBUG("Actor '%s'@%s is killing actor '%s'@%s", get_cname(), host_ ? host_->get_cname() : "", actor->get_cname(),
252 actor->host_ ? actor->host_->get_cname() : "");
257 XBT_DEBUG("Go on, this is a suicide,");
258 } else if (std::find(begin(simix_global->actors_to_run), end(simix_global->actors_to_run), actor) !=
259 end(simix_global->actors_to_run)) {
260 XBT_DEBUG("Actor %s is already in the to_run list", actor->get_cname());
262 XBT_DEBUG("Inserting %s in the to_run list", actor->get_cname());
263 simix_global->actors_to_run.push_back(actor);
267 void ActorImpl::kill_all() const
269 for (auto const& kv : simix_global->process_list)
270 if (kv.second != this)
271 this->kill(kv.second);
274 void ActorImpl::set_kill_time(double kill_time)
276 if (kill_time <= SIMIX_get_clock())
278 XBT_DEBUG("Set kill time %f for actor %s@%s", kill_time, get_cname(), host_->get_cname());
279 kill_timer_ = simix::Timer::set(kill_time, [this] {
281 kill_timer_ = nullptr;
285 double ActorImpl::get_kill_time() const
287 return kill_timer_ ? kill_timer_->get_date() : 0;
290 void ActorImpl::yield()
292 XBT_DEBUG("Yield actor '%s'", get_cname());
294 /* Go into sleep and return control to maestro */
297 /* Ok, maestro returned control to us */
298 XBT_DEBUG("Control returned to me: '%s'", get_cname());
300 if (context_->wannadie()) {
301 XBT_DEBUG("Actor %s@%s is dead", get_cname(), host_->get_cname());
307 XBT_DEBUG("Hey! I'm suspended.");
309 xbt_assert(exception_ == nullptr, "Gasp! This exception may be lost by subsequent calls.");
311 if (waiting_synchro_ != nullptr) // Not sure of when this will happen. Maybe when suspending early in the SR when a
312 waiting_synchro_->suspend(); // waiting_synchro was terminated
314 yield(); // Yield back to maestro without proceeding with my execution. I'll get rescheduled by resume()
317 if (exception_ != nullptr) {
318 XBT_DEBUG("Wait, maestro left me an exception");
319 std::exception_ptr exception = std::move(exception_);
320 exception_ = nullptr;
322 std::rethrow_exception(std::move(exception));
323 } catch (const simgrid::Exception& e) {
324 if (dynamic_cast<const simgrid::TimeoutException*>(&e) != nullptr) {
325 std::throw_with_nested(simgrid::TimeoutException(XBT_THROW_POINT, "Timeout raised in kernel mode."));
327 } else if (dynamic_cast<const simgrid::HostFailureException*>(&e) != nullptr) {
328 std::throw_with_nested(simgrid::HostFailureException(XBT_THROW_POINT, "HostFailure raised in kernel mode."));
330 } else if (dynamic_cast<const simgrid::NetworkFailureException*>(&e) != nullptr) {
331 std::throw_with_nested(
332 simgrid::NetworkFailureException(XBT_THROW_POINT, "NetworkFailure raised in kernel mode."));
334 } else if (dynamic_cast<const simgrid::StorageFailureException*>(&e) != nullptr) {
335 std::throw_with_nested(
336 simgrid::StorageFailureException(XBT_THROW_POINT, "StorageFailure raised in kernel mode."));
338 } else if (dynamic_cast<const simgrid::VmFailureException*>(&e) != nullptr) {
339 std::throw_with_nested(simgrid::VmFailureException(XBT_THROW_POINT, "VmFailure raised in kernel mode."));
341 } else if (dynamic_cast<const simgrid::CancelException*>(&e) != nullptr) {
342 std::throw_with_nested(simgrid::CancelException(XBT_THROW_POINT, "Cancel raised in kernel mode."));
344 } else if (dynamic_cast<const simgrid::TracingError*>(&e) != nullptr) {
345 std::throw_with_nested(simgrid::TracingError(XBT_THROW_POINT, "Tracing error raised in kernel mode."));
347 } else if (dynamic_cast<const simgrid::ParseError*>(&e) != nullptr) {
348 auto pe = dynamic_cast<const simgrid::ParseError*>(&e);
349 std::throw_with_nested(simgrid::ParseError(pe->file_, pe->line_, "Parse error raised in kernel mode."));
355 if (SMPI_switch_data_segment && not finished_) {
356 SMPI_switch_data_segment(get_iface());
360 /** This actor will be terminated automatically when the last non-daemon actor finishes */
361 void ActorImpl::daemonize()
365 simix_global->daemons.push_back(this);
369 void ActorImpl::undaemonize()
372 auto& vect = simix_global->daemons;
373 auto it = std::find(vect.begin(), vect.end(), this);
374 xbt_assert(it != vect.end(), "The dying daemon is not a daemon after all. Please report that bug.");
375 /* Don't move the whole content since we don't really care about the order */
377 std::swap(*it, vect.back());
383 s4u::Actor* ActorImpl::restart()
385 xbt_assert(this != simix_global->maestro_, "Restarting maestro is not supported");
387 XBT_DEBUG("Restarting actor %s on %s", get_cname(), host_->get_cname());
389 // retrieve the arguments of the old actor
390 ProcessArg arg = ProcessArg(host_, this);
392 // kill the old actor
393 context::Context::self()->get_actor()->kill(this);
395 // start the new actor
396 ActorImplPtr actor = ActorImpl::create(arg.name, arg.code, arg.data, arg.host, arg.properties.get(), nullptr);
397 *actor->on_exit = std::move(*arg.on_exit);
398 actor->set_kill_time(arg.kill_time);
399 actor->set_auto_restart(arg.auto_restart);
401 return actor->get_ciface();
404 void ActorImpl::suspend()
407 XBT_DEBUG("Actor '%s' is already suspended", get_cname());
413 /* If the suspended actor is waiting on a sync, suspend its synchronization.
414 * Otherwise, it will suspend itself when scheduled, ie, very soon. */
415 if (waiting_synchro_ != nullptr)
416 waiting_synchro_->suspend();
419 void ActorImpl::resume()
421 XBT_IN("actor = %p", this);
423 if (context_->wannadie()) {
424 XBT_VERB("Ignoring request to suspend an actor that is currently dying.");
432 /* resume the activity that was blocking the resumed actor. */
433 if (waiting_synchro_)
434 waiting_synchro_->resume();
435 else // Reschedule the actor if it was forcefully unscheduled in yield()
436 simix_global->actors_to_run.push_back(this);
441 activity::ActivityImplPtr ActorImpl::join(const ActorImpl* actor, double timeout)
443 activity::ActivityImplPtr sleep = this->sleep(timeout);
444 actor->on_exit->emplace_back([sleep](bool) {
445 if (sleep->surf_action_)
446 sleep->surf_action_->finish(resource::Action::State::FINISHED);
451 activity::ActivityImplPtr ActorImpl::sleep(double duration)
453 if (not host_->is_on())
454 throw_exception(std::make_exception_ptr(HostFailureException(
455 XBT_THROW_POINT, std::string("Host ") + host_->get_cname() + " failed, you cannot sleep there.")));
457 auto sleep = new activity::SleepImpl();
458 sleep->set_name("sleep").set_host(host_).set_duration(duration).start();
459 return activity::SleepImplPtr(sleep);
462 void ActorImpl::throw_exception(std::exception_ptr e)
469 /* cancel the blocking synchro if any */
470 if (waiting_synchro_) {
471 waiting_synchro_->cancel();
472 activities_.remove(waiting_synchro_);
473 waiting_synchro_ = nullptr;
477 void ActorImpl::simcall_answer()
479 if (this != simix_global->maestro_) {
480 XBT_DEBUG("Answer simcall %s (%d) issued by %s (%p)", SIMIX_simcall_name(simcall_.call_), (int)simcall_.call_,
482 xbt_assert(simcall_.call_ != simix::Simcall::NONE);
483 simcall_.call_ = simix::Simcall::NONE;
484 xbt_assert(not XBT_LOG_ISENABLED(simix_process, xbt_log_priority_debug) ||
485 std::find(begin(simix_global->actors_to_run), end(simix_global->actors_to_run), this) ==
486 end(simix_global->actors_to_run),
487 "Actor %p should not exist in actors_to_run!", this);
488 simix_global->actors_to_run.push_back(this);
492 void ActorImpl::set_host(s4u::Host* dest)
494 host_->pimpl_->remove_actor(this);
496 dest->pimpl_->add_actor(this);
499 ActorImplPtr ActorImpl::init(const std::string& name, s4u::Host* host) const
501 auto* actor = new ActorImpl(xbt::string(name), host);
502 actor->set_ppid(this->pid_);
504 intrusive_ptr_add_ref(actor);
505 /* The on_creation() signal must be delayed until there, where the pid and everything is set */
506 s4u::Actor::on_creation(*actor->get_ciface());
508 return ActorImplPtr(actor);
511 ActorImpl* ActorImpl::start(const ActorCode& code)
513 xbt_assert(code && host_ != nullptr, "Invalid parameters");
515 if (not host_->is_on()) {
516 XBT_WARN("Cannot launch actor '%s' on failed host '%s'", name_.c_str(), host_->get_cname());
517 intrusive_ptr_release(this);
518 throw HostFailureException(XBT_THROW_POINT, "Cannot start actor on failed host.");
522 XBT_VERB("Create context %s", get_cname());
523 context_.reset(simix_global->context_factory->create_context(ActorCode(code), this));
525 XBT_DEBUG("Start context '%s'", get_cname());
527 /* Add the actor to its host's actor list */
528 host_->pimpl_->add_actor(this);
529 simix_global->process_list[pid_] = this;
531 /* Now insert it in the global actor list and in the actor to run list */
532 XBT_DEBUG("Inserting [%p] %s(%s) in the to_run list", this, get_cname(), host_->get_cname());
533 simix_global->actors_to_run.push_back(this);
538 ActorImplPtr ActorImpl::create(const std::string& name, const ActorCode& code, void* data, s4u::Host* host,
539 const std::unordered_map<std::string, std::string>* properties,
540 const ActorImpl* parent_actor)
542 XBT_DEBUG("Start actor %s@'%s'", name.c_str(), host->get_cname());
545 if (parent_actor != nullptr)
546 actor = parent_actor->init(xbt::string(name), host);
548 actor = self()->init(xbt::string(name), host);
551 actor->set_user_data(data);
554 if (properties != nullptr)
555 actor->set_properties(*properties);
562 void create_maestro(const std::function<void()>& code)
564 /* Create maestro actor and initialize it */
565 auto* maestro = new ActorImpl(xbt::string(""), /*host*/ nullptr);
568 maestro->context_.reset(simix_global->context_factory->create_context(ActorCode(), maestro));
570 maestro->context_.reset(simix_global->context_factory->create_maestro(ActorCode(code), maestro));
573 maestro->simcall_.issuer_ = maestro;
574 simix_global->maestro_ = maestro;
578 } // namespace kernel
579 } // namespace simgrid
581 int SIMIX_process_count() // XBT_ATTRIB_DEPRECATED_v329
583 return simix_global->process_list.size();
586 void* SIMIX_process_self_get_data() // XBT_ATTRIB_DEPRECATED_v329
588 smx_actor_t self = simgrid::kernel::actor::ActorImpl::self();
590 if (self == nullptr) {
593 return self->get_user_data();
596 void SIMIX_process_self_set_data(void* data) // XBT_ATTRIB_DEPRECATED_v329
598 simgrid::kernel::actor::ActorImpl::self()->set_user_data(data);
601 /* needs to be public and without simcall because it is called
602 by exceptions and logging events */
603 const char* SIMIX_process_self_get_name()
605 return SIMIX_is_maestro() ? "maestro" : simgrid::kernel::actor::ActorImpl::self()->get_cname();
608 /** @brief Returns the process from PID. */
609 smx_actor_t SIMIX_process_from_PID(aid_t PID)
611 return simgrid::kernel::actor::ActorImpl::by_PID(PID);
614 void SIMIX_process_on_exit(smx_actor_t actor,
615 const std::function<void(bool /*failed*/)>& fun) // XBT_ATTRIB_DEPRECATED_v329
617 xbt_assert(actor, "current process not found: are you in maestro context ?");
618 actor->on_exit->emplace_back(fun);
621 void simcall_process_set_data(smx_actor_t process, void* data) // XBT_ATTRIB_DEPRECATED_v329
623 simgrid::kernel::actor::simcall([process, data] { process->set_user_data(data); });