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();
47 ActorPtr Actor::init(const std::string& name, s4u::Host* host)
49 kernel::actor::ActorImpl* self = SIMIX_process_self();
50 kernel::actor::ActorImpl* actor =
51 kernel::actor::simcall([self, &name, host] { return self->init(name, host).get(); });
52 return actor->iface();
55 ActorPtr Actor::start(const std::function<void()>& code)
57 simgrid::kernel::actor::simcall([this, &code] { pimpl_->start(code); });
61 ActorPtr Actor::create(const std::string& name, s4u::Host* host, const std::function<void()>& code)
63 kernel::actor::ActorImpl* self = SIMIX_process_self();
64 kernel::actor::ActorImpl* actor =
65 kernel::actor::simcall([self, &name, host, &code] { return self->init(name, host)->start(code); });
67 return actor->iface();
70 ActorPtr Actor::create(const std::string& name, s4u::Host* host, const std::string& function,
71 std::vector<std::string> args)
73 simix::ActorCodeFactory& factory = SIMIX_get_actor_code_factory(function);
74 return create(name, host, factory(std::move(args)));
77 void intrusive_ptr_add_ref(Actor* actor)
79 intrusive_ptr_add_ref(actor->pimpl_);
81 void intrusive_ptr_release(Actor* actor)
83 intrusive_ptr_release(actor->pimpl_);
85 int Actor::get_refcount()
87 return pimpl_->get_refcount();
90 // ***** Actor methods *****
97 void Actor::join(double timeout)
99 kernel::actor::ActorImpl* issuer = SIMIX_process_self();
100 kernel::actor::ActorImpl* target = pimpl_;
101 kernel::actor::simcall_blocking<void>([issuer, target, timeout] {
102 if (target->finished_) {
103 // The joined process is already finished, just wake up the issuer right away
104 issuer->simcall_answer();
106 smx_activity_t sync = issuer->join(target, timeout);
107 sync->register_simcall(&issuer->simcall);
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 %s to the actors_at_boot_ list of Host %s", arg->name.c_str(), arg->host->get_cname());
120 pimpl_->get_host()->pimpl_->add_actor_at_boot(arg);
124 void Actor::on_exit(const std::function<void(bool /*failed*/)>& fun) const
126 kernel::actor::simcall([this, &fun] { SIMIX_process_on_exit(pimpl_, fun); });
129 void Actor::migrate(Host* new_host)
131 s4u::Actor::on_migration_start(*this);
133 kernel::actor::simcall([this, new_host]() {
134 if (pimpl_->waiting_synchro != nullptr) {
135 // The actor is blocked on an activity. If it's an exec, migrate it too.
136 // FIXME: implement the migration of other kinds of activities
137 kernel::activity::ExecImplPtr exec =
138 boost::dynamic_pointer_cast<kernel::activity::ExecImpl>(pimpl_->waiting_synchro);
139 xbt_assert(exec.get() != nullptr, "We can only migrate blocked actors when they are blocked on executions.");
140 exec->migrate(new_host);
142 this->pimpl_->set_host(new_host);
145 s4u::Actor::on_migration_end(*this);
148 s4u::Host* Actor::get_host() const
150 return this->pimpl_->get_host();
153 void Actor::daemonize()
155 kernel::actor::simcall([this]() { pimpl_->daemonize(); });
158 bool Actor::is_daemon() const
160 return this->pimpl_->is_daemon();
163 const simgrid::xbt::string& Actor::get_name() const
165 return this->pimpl_->get_name();
168 const char* Actor::get_cname() const
170 return this->pimpl_->get_cname();
173 aid_t Actor::get_pid() const
175 return this->pimpl_->get_pid();
178 aid_t Actor::get_ppid() const
180 return this->pimpl_->get_ppid();
183 void Actor::suspend()
185 kernel::actor::ActorImpl* issuer = SIMIX_process_self();
186 kernel::actor::ActorImpl* target = pimpl_;
187 s4u::Actor::on_suspend(*this);
188 kernel::actor::simcall_blocking<void>([issuer, target]() {
190 if (target != issuer) {
191 /* If we are suspending ourselves, then just do not finish the simcall now */
192 issuer->simcall_answer();
199 kernel::actor::simcall([this] { pimpl_->resume(); });
200 s4u::Actor::on_resume(*this);
203 bool Actor::is_suspended()
205 return pimpl_->is_suspended();
208 void Actor::set_kill_time(double kill_time)
210 kernel::actor::simcall([this, kill_time] { pimpl_->set_kill_time(kill_time); });
213 /** @brief Get the kill time of an actor(or 0 if unset). */
214 double Actor::get_kill_time()
216 return pimpl_->get_kill_time();
221 kernel::actor::ActorImpl* self = SIMIX_process_self();
222 kernel::actor::simcall([this, self] {
223 xbt_assert(pimpl_ != simix_global->maestro_process, "Killing maestro is a rather bad idea");
228 // ***** Static functions *****
230 ActorPtr Actor::by_pid(aid_t pid)
232 kernel::actor::ActorImpl* actor = SIMIX_process_from_PID(pid);
233 if (actor != nullptr)
234 return actor->iface();
239 void Actor::kill_all()
241 kernel::actor::ActorImpl* self = SIMIX_process_self();
242 kernel::actor::simcall([self] { self->kill_all(); });
245 const std::unordered_map<std::string, std::string>* Actor::get_properties() const
247 return pimpl_->get_properties();
250 /** Retrieve the property value (or nullptr if not set) */
251 const char* Actor::get_property(const std::string& key) const
253 return pimpl_->get_property(key);
256 void Actor::set_property(const std::string& key, const std::string& value)
258 kernel::actor::simcall([this, &key, &value] { pimpl_->set_property(key, value); });
261 Actor* Actor::restart()
263 return kernel::actor::simcall([this]() { return pimpl_->restart(); });
266 // ***** this_actor *****
268 namespace this_actor {
270 /** Returns true if run from the kernel mode, and false if run from a real actor
272 * Everything that is run out of any actor (simulation setup before the engine is run,
273 * computing the model evolutions as a result to the actors' action, etc) is run in
274 * kernel mode, just as in any operating systems.
276 * In SimGrid, the actor in charge of doing the stuff in kernel mode is called Maestro,
277 * because it is the one scheduling when the others should move or wait.
281 kernel::actor::ActorImpl* self = SIMIX_process_self();
282 return self == nullptr || self == simix_global->maestro_process;
285 void sleep_for(double duration)
287 xbt_assert(std::isfinite(duration), "duration is not finite!");
290 kernel::actor::ActorImpl* issuer = SIMIX_process_self();
291 Actor::on_sleep(*issuer->ciface());
293 kernel::actor::simcall_blocking<void>([issuer, duration]() {
294 if (MC_is_active() || MC_record_replay_is_active()) {
295 MC_process_clock_add(issuer, duration);
296 issuer->simcall_answer();
299 smx_activity_t sync = issuer->sleep(duration);
300 sync->register_simcall(&issuer->simcall);
303 Actor::on_wake_up(*issuer->ciface());
309 kernel::actor::simcall([] { /* do nothing*/ });
312 XBT_PUBLIC void sleep_until(double wakeup_time)
314 double now = SIMIX_get_clock();
315 if (wakeup_time > now)
316 sleep_for(wakeup_time - now);
319 void execute(double flops)
321 execute(flops, 1.0 /* priority */);
324 void execute(double flops, double priority)
326 exec_init(flops)->set_priority(priority)->start()->wait();
329 void parallel_execute(const std::vector<s4u::Host*>& hosts, const std::vector<double>& flops_amounts,
330 const std::vector<double>& bytes_amounts)
332 parallel_execute(hosts, flops_amounts, bytes_amounts, -1);
335 void parallel_execute(const std::vector<s4u::Host*>& hosts, const std::vector<double>& flops_amounts,
336 const std::vector<double>& bytes_amounts, double timeout)
338 xbt_assert(hosts.size() > 0, "Your parallel executions must span over at least one host.");
339 xbt_assert(hosts.size() == flops_amounts.size() || flops_amounts.empty(),
340 "Host count (%zu) does not match flops_amount count (%zu).", hosts.size(), flops_amounts.size());
341 xbt_assert(hosts.size() * hosts.size() == bytes_amounts.size() || bytes_amounts.empty(),
342 "bytes_amounts must be a matrix of size host_count * host_count (%zu*%zu), but it's of size %zu.",
343 hosts.size(), hosts.size(), flops_amounts.size());
344 /* Check that we are not mixing VMs and PMs in the parallel task */
345 bool is_a_vm = (nullptr != dynamic_cast<VirtualMachine*>(hosts.front()));
346 xbt_assert(std::all_of(hosts.begin(), hosts.end(),
347 [is_a_vm](s4u::Host* elm) {
348 bool tmp_is_a_vm = (nullptr != dynamic_cast<VirtualMachine*>(elm));
349 return is_a_vm == tmp_is_a_vm;
351 "parallel_execute: mixing VMs and PMs is not supported (yet).");
352 /* checking for infinite values */
353 xbt_assert(std::all_of(flops_amounts.begin(), flops_amounts.end(), [](double elm) { return std::isfinite(elm); }),
354 "flops_amounts comprises infinite values!");
355 xbt_assert(std::all_of(bytes_amounts.begin(), bytes_amounts.end(), [](double elm) { return std::isfinite(elm); }),
356 "flops_amounts comprises infinite values!");
358 exec_init(hosts, flops_amounts, bytes_amounts)->set_timeout(timeout)->wait();
361 ExecPtr exec_init(double flops_amount)
363 return ExecPtr(new ExecSeq(get_host(), flops_amount));
366 ExecPtr exec_init(const std::vector<s4u::Host*>& hosts, const std::vector<double>& flops_amounts,
367 const std::vector<double>& bytes_amounts)
369 return ExecPtr(new ExecPar(hosts, flops_amounts, bytes_amounts));
372 ExecPtr exec_async(double flops)
374 ExecPtr res = exec_init(flops);
381 return SIMIX_process_self()->get_pid();
386 return SIMIX_process_self()->get_ppid();
389 std::string get_name()
391 return SIMIX_process_self()->get_name();
394 const char* get_cname()
396 return SIMIX_process_self()->get_cname();
401 return SIMIX_process_self()->get_host();
406 kernel::actor::ActorImpl* self = SIMIX_process_self();
407 s4u::Actor::on_suspend(*self->ciface());
408 kernel::actor::simcall_blocking<void>([self] { self->suspend(); });
413 kernel::actor::ActorImpl* self = SIMIX_process_self();
414 kernel::actor::simcall([self] { self->resume(); });
415 Actor::on_resume(*self->ciface());
420 kernel::actor::ActorImpl* self = SIMIX_process_self();
421 simgrid::kernel::actor::simcall([self] { self->exit(); });
424 void on_exit(const std::function<void(bool)>& fun)
426 SIMIX_process_self()->iface()->on_exit(fun);
429 /** @brief Moves the current actor to another host
431 * @see simgrid::s4u::Actor::migrate() for more information
433 void migrate(Host* new_host)
435 SIMIX_process_self()->iface()->migrate(new_host);
438 } // namespace this_actor
440 } // namespace simgrid
442 /* **************************** Public C interface *************************** */
444 sg_actor_t sg_actor_init(const char* name, sg_host_t host)
446 return simgrid::s4u::Actor::init(name, host).get();
449 void sg_actor_start(sg_actor_t actor, xbt_main_func_t code, int argc, char** argv)
451 simgrid::simix::ActorCode function;
453 function = simgrid::xbt::wrap_main(code, argc, static_cast<const char* const*>(argv));
454 actor->start(std::move(function));
457 /** @ingroup m_actor_management
458 * @brief Returns the process ID of @a actor.
460 * This function checks whether @a actor is a valid pointer and return its PID (or 0 in case of problem).
462 aid_t sg_actor_get_PID(sg_actor_t actor)
464 /* Do not raise an exception here: this function is called by the logs
465 * and the exceptions, so it would be called back again and again */
466 if (actor == nullptr || actor->get_impl() == nullptr)
468 return actor->get_pid();
471 /** @ingroup m_actor_management
472 * @brief Returns the process ID of the parent of @a actor.
474 * This function checks whether @a actor is a valid pointer and return its parent's PID.
475 * Returns -1 if the actor has not been created by any other actor.
477 aid_t sg_actor_get_PPID(sg_actor_t actor)
479 return actor->get_ppid();
482 /** @ingroup m_actor_management
484 * @brief Return a #sg_actor_t given its PID.
486 * 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.
487 * If none is found, @c nullptr is returned.
488 Note that the PID are unique in the whole simulation, not only on a given host.
490 sg_actor_t sg_actor_by_PID(aid_t pid)
492 return simgrid::s4u::Actor::by_pid(pid).get();
495 /** @ingroup m_actor_management
496 * @brief Return the name of an actor.
498 const char* sg_actor_get_name(sg_actor_t actor)
500 return actor->get_cname();
503 sg_host_t sg_actor_get_host(sg_actor_t actor)
505 return actor->get_host();
508 /** @ingroup m_actor_management
509 * @brief Returns the value of a given actor property
511 * @param actor an actor
512 * @param name a property name
513 * @return value of a property (or nullptr if the property is not set)
515 const char* sg_actor_get_property_value(sg_actor_t actor, const char* name)
517 return actor->get_property(name);
520 /** @ingroup m_actor_management
521 * @brief Return the list of properties
523 * This function returns all the parameters associated with an actor
525 xbt_dict_t sg_actor_get_properties(sg_actor_t actor)
527 xbt_assert(actor != nullptr, "Invalid parameter: First argument must not be nullptr");
528 xbt_dict_t as_dict = xbt_dict_new_homogeneous(xbt_free_f);
529 const std::unordered_map<std::string, std::string>* props = actor->get_properties();
530 if (props == nullptr)
532 for (auto const& kv : *props) {
533 xbt_dict_set(as_dict, kv.first.c_str(), xbt_strdup(kv.second.c_str()));
538 /** @ingroup m_actor_management
539 * @brief Suspend the actor.
541 * This function suspends the actor by suspending the task on which it was waiting for the completion.
543 void sg_actor_suspend(sg_actor_t actor)
545 xbt_assert(actor != nullptr, "Invalid parameter: First argument must not be nullptr");
549 /** @ingroup m_actor_management
550 * @brief Resume a suspended actor.
552 * This function resumes a suspended actor by resuming the task on which it was waiting for the completion.
554 void sg_actor_resume(sg_actor_t actor)
556 xbt_assert(actor != nullptr, "Invalid parameter: First argument must not be nullptr");
560 /** @ingroup m_actor_management
561 * @brief Returns true if the actor is suspended .
563 * This checks whether an actor is suspended or not by inspecting the task on which it was waiting for the completion.
565 int sg_actor_is_suspended(sg_actor_t actor)
567 return actor->is_suspended();
571 * @ingroup m_actor_management
572 * @brief Restarts an actor from the beginning.
574 sg_actor_t sg_actor_restart(sg_actor_t actor)
576 return actor->restart();
580 * @ingroup m_actor_management
581 * @brief Sets the "auto-restart" flag of the actor.
582 * If the flag is set to 1, the actor will be automatically restarted when its host comes back up.
584 void sg_actor_set_auto_restart(sg_actor_t actor, int auto_restart)
586 actor->set_auto_restart(auto_restart);
589 /** @ingroup m_actor_management
590 * @brief This actor will be terminated automatically when the last non-daemon actor finishes
592 void sg_actor_daemonize(sg_actor_t actor)
597 /** @ingroup m_actor_management
598 * @brief Migrates an actor to another location.
600 * This function changes the value of the #sg_host_t on which @a actor is running.
602 void sg_actor_migrate(sg_actor_t process, sg_host_t host)
604 process->migrate(host);
607 /** @ingroup m_actor_management
608 * @brief Wait for the completion of a #sg_actor_t.
610 * @param actor the actor to wait for
611 * @param timeout wait until the actor is over, or the timeout expires
613 void sg_actor_join(sg_actor_t actor, double timeout)
615 actor->join(timeout);
618 void sg_actor_kill(sg_actor_t actor)
623 void sg_actor_kill_all()
625 simgrid::s4u::Actor::kill_all();
628 /** @ingroup m_actor_management
629 * @brief Set the kill time of an actor.
631 * @param actor an actor
632 * @param kill_time the time when the actor is killed.
634 void sg_actor_set_kill_time(sg_actor_t actor, double kill_time)
636 actor->set_kill_time(kill_time);
639 /** Yield the current actor; let the other actors execute first */
640 void sg_actor_yield()
642 simgrid::s4u::this_actor::yield();
645 void sg_actor_sleep_for(double duration)
647 simgrid::s4u::this_actor::sleep_for(duration);
650 sg_actor_t sg_actor_attach(const char* name, void* data, sg_host_t host, xbt_dict_t properties)
652 xbt_assert(host != nullptr, "Invalid parameters: host and code params must not be nullptr");
653 std::unordered_map<std::string, std::string> props;
654 xbt_dict_cursor_t cursor = nullptr;
657 xbt_dict_foreach (properties, cursor, key, value)
659 xbt_dict_free(&properties);
661 /* Let's create the process: SIMIX may decide to start it right now, even before returning the flow control to us */
662 smx_actor_t actor = nullptr;
664 actor = simgrid::kernel::actor::ActorImpl::attach(name, data, host, &props).get();
665 } catch (simgrid::HostFailureException const&) {
666 xbt_die("Could not attach");
669 simgrid::s4u::this_actor::yield();
670 return actor->ciface();
673 void sg_actor_detach()
675 simgrid::kernel::actor::ActorImpl::detach();
678 aid_t sg_actor_self_get_pid()
680 return simgrid::s4u::this_actor::get_pid();
683 aid_t sg_actor_self_get_ppid()
685 return simgrid::s4u::this_actor::get_ppid();
688 const char* sg_actor_self_get_name()
690 return simgrid::s4u::this_actor::get_cname();
693 sg_actor_t sg_actor_self()
695 return simgrid::s4u::Actor::self();
698 void sg_actor_self_execute(double flops)
700 simgrid::s4u::this_actor::execute(flops);
703 /** @brief Take an extra reference on that actor to prevent it to be garbage-collected */
704 void sg_actor_ref(sg_actor_t actor)
706 intrusive_ptr_add_ref(actor);
708 /** @brief Release a reference on that actor so that it can get be garbage-collected */
709 void sg_actor_unref(sg_actor_t actor)
711 intrusive_ptr_release(actor);
714 /** @brief Return the user data of a #sg_actor_t */
715 void* sg_actor_data(sg_actor_t actor)
717 return actor->get_data();
719 /** @brief Set the user data of a #sg_actor_t */
720 void sg_actor_data_set(sg_actor_t actor, void* userdata)
722 actor->set_data(userdata);