1 /* Copyright (c) 2006-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. */
6 #include "simgrid/Exception.hpp"
7 #include "simgrid/actor.h"
8 #include "simgrid/modelchecker.h"
9 #include "simgrid/s4u/Actor.hpp"
10 #include "simgrid/s4u/Exec.hpp"
11 #include "simgrid/s4u/Host.hpp"
12 #include "simgrid/s4u/VirtualMachine.hpp"
13 #include "src/include/mc/mc.h"
14 #include "src/kernel/activity/ExecImpl.hpp"
15 #include "src/mc/mc_replay.hpp"
16 #include "src/simix/smx_private.hpp"
17 #include "src/surf/HostImpl.hpp"
22 XBT_LOG_NEW_DEFAULT_CATEGORY(s4u_actor, "S4U actors");
27 xbt::signal<void(Actor&)> s4u::Actor::on_creation;
28 xbt::signal<void(Actor const&)> s4u::Actor::on_suspend;
29 xbt::signal<void(Actor const&)> s4u::Actor::on_resume;
30 xbt::signal<void(Actor const&)> s4u::Actor::on_sleep;
31 xbt::signal<void(Actor const&)> s4u::Actor::on_wake_up;
32 xbt::signal<void(Actor const&)> s4u::Actor::on_migration_start;
33 xbt::signal<void(Actor const&)> s4u::Actor::on_migration_end;
34 xbt::signal<void(Actor const&)> s4u::Actor::on_termination;
35 xbt::signal<void(Actor const&)> s4u::Actor::on_destruction;
37 // ***** Actor creation *****
40 kernel::context::Context* self_context = kernel::context::Context::self();
41 if (self_context == nullptr)
44 return self_context->get_actor()->ciface();
46 ActorPtr Actor::init(const std::string& name, s4u::Host* host)
48 smx_actor_t self = SIMIX_process_self();
49 kernel::actor::ActorImpl* actor =
50 kernel::actor::simcall([self, &name, host] { return self->init(name, host).get(); });
51 return actor->iface();
54 ActorPtr Actor::start(const std::function<void()>& code)
56 simgrid::kernel::actor::simcall([this, &code] { pimpl_->start(code); });
60 ActorPtr Actor::create(const std::string& name, s4u::Host* host, const std::function<void()>& code)
62 smx_actor_t self = SIMIX_process_self();
63 kernel::actor::ActorImpl* actor =
64 kernel::actor::simcall([self, &name, host, &code] { return self->init(name, host)->start(code); });
66 return actor->iface();
69 ActorPtr Actor::create(const std::string& name, s4u::Host* host, const std::string& function,
70 std::vector<std::string> args)
72 simix::ActorCodeFactory& factory = SIMIX_get_actor_code_factory(function);
73 return create(name, host, factory(std::move(args)));
76 void intrusive_ptr_add_ref(Actor* actor)
78 intrusive_ptr_add_ref(actor->pimpl_);
80 void intrusive_ptr_release(Actor* actor)
82 intrusive_ptr_release(actor->pimpl_);
84 int Actor::get_refcount()
86 return pimpl_->get_refcount();
89 // ***** Actor methods *****
96 void Actor::join(double timeout)
98 auto issuer = SIMIX_process_self();
100 kernel::actor::simcall_blocking([issuer, target, timeout] {
101 if (target->finished_) {
102 // The joined process is already finished, just wake up the issuer right away
103 issuer->simcall_answer();
105 smx_activity_t sync = issuer->join(target, timeout);
106 sync->simcalls_.push_back(&issuer->simcall);
107 issuer->waiting_synchro = sync;
112 void Actor::set_auto_restart(bool autorestart)
114 kernel::actor::simcall([this, autorestart]() {
115 xbt_assert(autorestart && not pimpl_->has_to_auto_restart()); // FIXME: handle all cases
116 pimpl_->set_auto_restart(autorestart);
118 kernel::actor::ProcessArg* arg = new kernel::actor::ProcessArg(pimpl_->get_host(), pimpl_);
119 XBT_DEBUG("Adding Process %s to the actors_at_boot_ list of Host %s", arg->name.c_str(), arg->host->get_cname());
120 pimpl_->get_host()->pimpl_->actors_at_boot_.emplace_back(arg);
124 void Actor::on_exit(const std::function<void(int, void*)>& fun, void* data) /* deprecated */
126 on_exit([fun, data](bool failed) { fun(failed ? SMX_EXIT_FAILURE : SMX_EXIT_SUCCESS, data); });
129 void Actor::on_exit(const std::function<void(bool /*failed*/)>& fun) const
131 kernel::actor::simcall([this, &fun] { SIMIX_process_on_exit(pimpl_, fun); });
134 void Actor::migrate(Host* new_host)
136 s4u::Actor::on_migration_start(*this);
138 kernel::actor::simcall([this, new_host]() {
139 if (pimpl_->waiting_synchro != nullptr) {
140 // The actor is blocked on an activity. If it's an exec, migrate it too.
141 // FIXME: implement the migration of other kind of activities
142 kernel::activity::ExecImplPtr exec =
143 boost::dynamic_pointer_cast<kernel::activity::ExecImpl>(pimpl_->waiting_synchro);
144 xbt_assert(exec.get() != nullptr, "We can only migrate blocked actors when they are blocked on executions.");
145 exec->migrate(new_host);
147 this->pimpl_->set_host(new_host);
150 s4u::Actor::on_migration_end(*this);
153 s4u::Host* Actor::get_host() const
155 return this->pimpl_->get_host();
158 void Actor::daemonize()
160 kernel::actor::simcall([this]() { pimpl_->daemonize(); });
163 bool Actor::is_daemon() const
165 return this->pimpl_->is_daemon();
168 const simgrid::xbt::string& Actor::get_name() const
170 return this->pimpl_->get_name();
173 const char* Actor::get_cname() const
175 return this->pimpl_->get_cname();
178 aid_t Actor::get_pid() const
180 return this->pimpl_->get_pid();
183 aid_t Actor::get_ppid() const
185 return this->pimpl_->get_ppid();
188 void Actor::suspend()
190 auto issuer = SIMIX_process_self();
191 auto target = pimpl_;
192 s4u::Actor::on_suspend(*this);
193 kernel::actor::simcall_blocking([issuer, target]() {
194 target->suspend(issuer);
195 if (target != issuer) {
196 /* If we are suspending ourselves, then just do not finish the simcall now */
197 issuer->simcall_answer();
204 kernel::actor::simcall([this] { pimpl_->resume(); });
205 s4u::Actor::on_resume(*this);
208 bool Actor::is_suspended()
210 return pimpl_->is_suspended();
213 void Actor::set_kill_time(double kill_time)
215 kernel::actor::simcall([this, kill_time] { pimpl_->set_kill_time(kill_time); });
218 /** @brief Get the kill time of an actor(or 0 if unset). */
219 double Actor::get_kill_time()
221 return pimpl_->get_kill_time();
224 void Actor::kill(aid_t pid) // deprecated
226 kernel::actor::ActorImpl* killer = SIMIX_process_self();
227 kernel::actor::ActorImpl* victim = SIMIX_process_from_PID(pid);
228 if (victim != nullptr) {
229 kernel::actor::simcall([killer, victim] { killer->kill(victim); });
231 std::ostringstream oss;
232 oss << "kill: (" << pid << ") - No such actor" << std::endl;
233 throw std::runtime_error(oss.str());
239 kernel::actor::ActorImpl* process = SIMIX_process_self();
240 kernel::actor::simcall([this, process] {
241 xbt_assert(pimpl_ != simix_global->maestro_process, "Killing maestro is a rather bad idea");
242 process->kill(pimpl_);
246 // ***** Static functions *****
248 ActorPtr Actor::by_pid(aid_t pid)
250 kernel::actor::ActorImpl* process = SIMIX_process_from_PID(pid);
251 if (process != nullptr)
252 return process->iface();
257 void Actor::kill_all()
259 kernel::actor::ActorImpl* self = SIMIX_process_self();
260 kernel::actor::simcall([self] { self->kill_all(); });
263 const std::unordered_map<std::string, std::string>* Actor::get_properties() const
265 return pimpl_->get_properties();
268 /** Retrieve the property value (or nullptr if not set) */
269 const char* Actor::get_property(const std::string& key) const
271 return pimpl_->get_property(key);
274 void Actor::set_property(const std::string& key, const std::string& value)
276 kernel::actor::simcall([this, &key, &value] { pimpl_->set_property(key, value); });
279 Actor* Actor::restart()
281 return kernel::actor::simcall([this]() { return pimpl_->restart(); });
284 // ***** this_actor *****
286 namespace this_actor {
288 /** Returns true if run from the kernel mode, and false if run from a real actor
290 * Everything that is run out of any actor (simulation setup before the engine is run,
291 * computing the model evolutions as a result to the actors' action, etc) is run in
292 * kernel mode, just as in any operating systems.
294 * In SimGrid, the actor in charge of doing the stuff in kernel mode is called Maestro,
295 * because it is the one scheduling when the others should move or wait.
299 kernel::actor::ActorImpl* process = SIMIX_process_self();
300 return process == nullptr || process == simix_global->maestro_process;
303 void sleep_for(double duration)
305 xbt_assert(std::isfinite(duration), "duration is not finite!");
308 kernel::actor::ActorImpl* issuer = SIMIX_process_self();
309 Actor::on_sleep(*issuer->ciface());
311 kernel::actor::simcall_blocking([issuer, duration]() {
312 if (MC_is_active() || MC_record_replay_is_active()) {
313 MC_process_clock_add(issuer, duration);
314 issuer->simcall_answer();
317 smx_activity_t sync = issuer->sleep(duration);
318 sync->simcalls_.push_back(&issuer->simcall);
319 issuer->waiting_synchro = sync;
323 Actor::on_wake_up(*issuer->ciface());
329 kernel::actor::simcall([] { /* do nothing*/ });
332 XBT_PUBLIC void sleep_until(double wakeup_time)
334 double now = SIMIX_get_clock();
335 if (wakeup_time > now)
336 sleep_for(wakeup_time - now);
339 void execute(double flops)
341 execute(flops, 1.0 /* priority */);
344 void execute(double flops, double priority)
346 exec_init(flops)->set_priority(priority)->start()->wait();
349 void parallel_execute(const std::vector<s4u::Host*>& hosts, const std::vector<double>& flops_amounts,
350 const std::vector<double>& bytes_amounts)
352 parallel_execute(hosts, flops_amounts, bytes_amounts, -1);
355 void parallel_execute(const std::vector<s4u::Host*>& hosts, const std::vector<double>& flops_amounts,
356 const std::vector<double>& bytes_amounts, double timeout)
358 xbt_assert(hosts.size() > 0, "Your parallel executions must span over at least one host.");
359 xbt_assert(hosts.size() == flops_amounts.size() || flops_amounts.empty(),
360 "Host count (%zu) does not match flops_amount count (%zu).", hosts.size(), flops_amounts.size());
361 xbt_assert(hosts.size() * hosts.size() == bytes_amounts.size() || bytes_amounts.empty(),
362 "bytes_amounts must be a matrix of size host_count * host_count (%zu*%zu), but it's of size %zu.",
363 hosts.size(), hosts.size(), flops_amounts.size());
364 /* Check that we are not mixing VMs and PMs in the parallel task */
365 bool is_a_vm = (nullptr != dynamic_cast<VirtualMachine*>(hosts.front()));
366 xbt_assert(std::all_of(hosts.begin(), hosts.end(),
367 [is_a_vm](s4u::Host* elm) {
368 bool tmp_is_a_vm = (nullptr != dynamic_cast<VirtualMachine*>(elm));
369 return is_a_vm == tmp_is_a_vm;
371 "parallel_execute: mixing VMs and PMs is not supported (yet).");
372 /* checking for infinite values */
373 xbt_assert(std::all_of(flops_amounts.begin(), flops_amounts.end(), [](double elm) { return std::isfinite(elm); }),
374 "flops_amounts comprises infinite values!");
375 xbt_assert(std::all_of(bytes_amounts.begin(), bytes_amounts.end(), [](double elm) { return std::isfinite(elm); }),
376 "flops_amounts comprises infinite values!");
378 exec_init(hosts, flops_amounts, bytes_amounts)->set_timeout(timeout)->wait();
382 void parallel_execute(int host_nb, s4u::Host* const* host_list, const double* flops_amount, const double* bytes_amount,
386 simcall_execution_parallel_start("", host_nb, host_list, flops_amount, bytes_amount, /* rate */ -1, timeout);
387 simcall_execution_wait(s);
388 delete[] flops_amount;
389 delete[] bytes_amount;
393 void parallel_execute(int host_nb, s4u::Host* const* host_list, const double* flops_amount, const double* bytes_amount)
395 smx_activity_t s = simcall_execution_parallel_start("", host_nb, host_list, flops_amount, bytes_amount,
396 /* rate */ -1, /*timeout*/ -1);
397 simcall_execution_wait(s);
398 delete[] flops_amount;
399 delete[] bytes_amount;
402 ExecPtr exec_init(double flops_amount)
404 return ExecPtr(new ExecSeq(get_host(), flops_amount));
407 ExecPtr exec_init(const std::vector<s4u::Host*>& hosts, const std::vector<double>& flops_amounts,
408 const std::vector<double>& bytes_amounts)
410 return ExecPtr(new ExecPar(hosts, flops_amounts, bytes_amounts));
413 ExecPtr exec_async(double flops)
415 ExecPtr res = exec_init(flops);
422 return SIMIX_process_self()->get_pid();
427 return SIMIX_process_self()->get_ppid();
430 std::string get_name()
432 return SIMIX_process_self()->get_name();
435 const char* get_cname()
437 return SIMIX_process_self()->get_cname();
442 return SIMIX_process_self()->get_host();
447 SIMIX_process_self()->iface()->suspend();
452 kernel::actor::ActorImpl* self = SIMIX_process_self();
453 kernel::actor::simcall([self] { self->resume(); });
454 Actor::on_resume(*self->ciface());
459 kernel::actor::ActorImpl* self = SIMIX_process_self();
460 simgrid::kernel::actor::simcall([self] { self->exit(); });
463 void on_exit(const std::function<void(bool)>& fun)
465 SIMIX_process_self()->iface()->on_exit(fun);
468 void on_exit(const std::function<void(int, void*)>& fun, void* data) /* deprecated */
470 SIMIX_process_self()->iface()->on_exit([fun, data](bool exit) { fun(exit, data); });
473 /** @brief Moves the current actor to another host
475 * @see simgrid::s4u::Actor::migrate() for more information
477 void migrate(Host* new_host)
479 SIMIX_process_self()->iface()->migrate(new_host);
482 } // namespace this_actor
484 } // namespace simgrid
486 /* **************************** Public C interface *************************** */
488 /** @ingroup m_actor_management
489 * @brief Returns the process ID of @a actor.
491 * This function checks whether @a actor is a valid pointer and return its PID (or 0 in case of problem).
493 aid_t sg_actor_get_PID(sg_actor_t actor)
495 /* Do not raise an exception here: this function is called by the logs
496 * and the exceptions, so it would be called back again and again */
497 if (actor == nullptr || actor->get_impl() == nullptr)
499 return actor->get_pid();
502 /** @ingroup m_actor_management
503 * @brief Returns the process ID of the parent of @a actor.
505 * This function checks whether @a actor is a valid pointer and return its parent's PID.
506 * Returns -1 if the actor has not been created by any other actor.
508 aid_t sg_actor_get_PPID(sg_actor_t actor)
510 return actor->get_ppid();
513 /** @ingroup m_actor_management
515 * @brief Return a #sg_actor_t given its PID.
517 * This function search in the list of all the created sg_actor_t for a sg_actor_t whose PID is equal to @a PID.
518 * If none is found, @c nullptr is returned.
519 Note that the PID are unique in the whole simulation, not only on a given host.
521 sg_actor_t sg_actor_by_PID(aid_t pid)
523 return simgrid::s4u::Actor::by_pid(pid).get();
526 /** @ingroup m_actor_management
527 * @brief Return the name of an actor.
529 const char* sg_actor_get_name(sg_actor_t actor)
531 return actor->get_cname();
534 sg_host_t sg_actor_get_host(sg_actor_t actor)
536 return actor->get_host();
539 /** @ingroup m_actor_management
540 * @brief Returns the value of a given actor property
542 * @param actor an actor
543 * @param name a property name
544 * @return value of a property (or nullptr if the property is not set)
546 const char* sg_actor_get_property_value(sg_actor_t actor, const char* name)
548 return actor->get_property(name);
551 /** @ingroup m_actor_management
552 * @brief Return the list of properties
554 * This function returns all the parameters associated with an actor
556 xbt_dict_t sg_actor_get_properties(sg_actor_t actor)
558 xbt_assert(actor != nullptr, "Invalid parameter: First argument must not be nullptr");
559 xbt_dict_t as_dict = xbt_dict_new_homogeneous(xbt_free_f);
560 const std::unordered_map<std::string, std::string>* props = actor->get_properties();
561 if (props == nullptr)
563 for (auto const& kv : *props) {
564 xbt_dict_set(as_dict, kv.first.c_str(), xbt_strdup(kv.second.c_str()), nullptr);
569 /** @ingroup m_actor_management
570 * @brief Suspend the actor.
572 * This function suspends the actor by suspending the task on which it was waiting for the completion.
574 void sg_actor_suspend(sg_actor_t actor)
576 xbt_assert(actor != nullptr, "Invalid parameter: First argument must not be nullptr");
580 /** @ingroup m_actor_management
581 * @brief Resume a suspended actor.
583 * This function resumes a suspended actor by resuming the task on which it was waiting for the completion.
585 void sg_actor_resume(sg_actor_t actor)
587 xbt_assert(actor != nullptr, "Invalid parameter: First argument must not be nullptr");
591 /** @ingroup m_actor_management
592 * @brief Returns true if the actor is suspended .
594 * This checks whether an actor is suspended or not by inspecting the task on which it was waiting for the completion.
596 int sg_actor_is_suspended(sg_actor_t actor)
598 return actor->is_suspended();
602 * @ingroup m_actor_management
603 * @brief Restarts an actor from the beginning.
605 sg_actor_t sg_actor_restart(sg_actor_t actor)
607 return actor->restart();
611 * @ingroup m_actor_management
612 * @brief Sets the "auto-restart" flag of the actor.
613 * If the flag is set to 1, the actor will be automatically restarted when its host comes back up.
615 void sg_actor_set_auto_restart(sg_actor_t actor, int auto_restart)
617 actor->set_auto_restart(auto_restart);
620 /** @ingroup m_actor_management
621 * @brief This actor will be terminated automatically when the last non-daemon actor finishes
623 void sg_actor_daemonize(sg_actor_t actor)
628 /** @ingroup m_actor_management
629 * @brief Migrates an actor to another location.
631 * This function changes the value of the #sg_host_t on which @a actor is running.
633 void sg_actor_migrate(sg_actor_t process, sg_host_t host)
635 process->migrate(host);
638 /** @ingroup m_actor_management
639 * @brief Wait for the completion of a #sg_actor_t.
641 * @param actor the actor to wait for
642 * @param timeout wait until the actor is over, or the timeout expires
644 void sg_actor_join(sg_actor_t actor, double timeout)
646 actor->join(timeout);
649 void sg_actor_kill(sg_actor_t actor)
654 void sg_actor_kill_all()
656 simgrid::s4u::Actor::kill_all();
659 /** @ingroup m_actor_management
660 * @brief Set the kill time of an actor.
662 * @param actor an actor
663 * @param kill_time the time when the actor is killed.
665 void sg_actor_set_kill_time(sg_actor_t actor, double kill_time)
667 actor->set_kill_time(kill_time);
670 /** Yield the current actor; let the other actors execute first */
671 void sg_actor_yield()
673 simgrid::s4u::this_actor::yield();
676 void sg_actor_sleep_for(double duration)
678 simgrid::s4u::this_actor::sleep_for(duration);
681 sg_actor_t sg_actor_attach(const char* name, void* data, sg_host_t host, xbt_dict_t properties)
683 xbt_assert(host != nullptr, "Invalid parameters: host and code params must not be nullptr");
684 std::unordered_map<std::string, std::string> props;
685 xbt_dict_cursor_t cursor = nullptr;
688 xbt_dict_foreach (properties, cursor, key, value)
690 xbt_dict_free(&properties);
692 /* Let's create the process: SIMIX may decide to start it right now, even before returning the flow control to us */
693 smx_actor_t actor = nullptr;
695 actor = simgrid::kernel::actor::ActorImpl::attach(name, data, host, &props).get();
696 } catch (simgrid::HostFailureException const&) {
697 xbt_die("Could not attach");
700 simgrid::s4u::this_actor::yield();
701 return actor->ciface();
704 void sg_actor_detach()
706 simgrid::kernel::actor::ActorImpl::detach();
709 aid_t sg_actor_self_get_pid()
711 return simgrid::s4u::this_actor::get_pid();
714 aid_t sg_actor_self_get_ppid()
716 return simgrid::s4u::this_actor::get_ppid();
719 const char* sg_actor_self_get_name()
721 return simgrid::s4u::this_actor::get_cname();
724 sg_actor_t sg_actor_self()
726 return simgrid::s4u::Actor::self();
729 void sg_actor_self_execute(double flops)
731 simgrid::s4u::this_actor::execute(flops);
734 /** @brief Take an extra reference on that actor to prevent it to be garbage-collected */
735 void sg_actor_ref(sg_actor_t actor)
737 intrusive_ptr_add_ref(actor);
739 /** @brief Release a reference on that actor so that it can get be garbage-collected */
740 void sg_actor_unref(sg_actor_t actor)
742 intrusive_ptr_release(actor);