Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Sort Actor traits alphabetically + cleanups
[simgrid.git] / src / kernel / actor / ActorImpl.cpp
1 /* Copyright (c) 2007-2022. The SimGrid Team. All rights reserved.          */
2
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. */
5
6 #include <simgrid/Exception.hpp>
7 #include <simgrid/s4u/Actor.hpp>
8 #include <simgrid/s4u/Host.hpp>
9
10 #define SIMIX_H_NO_DEPRECATED_WARNING // avoid deprecation warning on include (remove with XBT_ATTRIB_DEPRECATED_v333)
11 #include <simgrid/simix.h>
12
13 #include "src/kernel/EngineImpl.hpp"
14 #if HAVE_SMPI
15 #include "src/smpi/include/private.hpp"
16 #endif
17 #include "src/surf/HostImpl.hpp"
18
19 #include <boost/core/demangle.hpp>
20 #include <typeinfo>
21 #include <utility>
22
23 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(ker_actor, kernel, "Logging specific to Actor's kernel side");
24
25 /**
26  * @brief Returns the current agent.
27  *
28  * This functions returns the currently running SIMIX process.
29  *
30  * @return The SIMIX process
31  */
32 smx_actor_t SIMIX_process_self() // XBT_ATTRIB_DEPRECATED_v333
33 {
34   return simgrid::kernel::actor::ActorImpl::self();
35 }
36
37 namespace simgrid {
38 namespace kernel {
39 namespace actor {
40
41 /*------------------------- [ ActorIDTrait ] -------------------------*/
42 static unsigned long maxpid = 0;
43 unsigned long get_maxpid()
44 {
45   return maxpid;
46 }
47 unsigned long* get_maxpid_addr()
48 {
49   return &maxpid;
50 }
51 ActorIDTrait::ActorIDTrait(std::string name, aid_t ppid) : name_(std::move(name)), pid_(maxpid++), ppid_(ppid) {}
52
53 ActorImpl* ActorImpl::by_pid(aid_t pid)
54 {
55   return EngineImpl::get_instance()->get_actor_by_pid(pid);
56 }
57
58 ActorImpl* ActorImpl::self()
59 {
60   const context::Context* self_context = context::Context::self();
61
62   return (self_context != nullptr) ? self_context->get_actor() : nullptr;
63 }
64
65 ActorImpl::ActorImpl(xbt::string name, s4u::Host* host, aid_t ppid)
66     : ActorIDTrait(std::move(name), ppid), host_(host), piface_(this)
67 {
68   simcall_.issuer_ = this;
69   stacksize_       = context::stack_size;
70 }
71
72 ActorImpl::~ActorImpl()
73 {
74   if (EngineImpl::has_instance() && not EngineImpl::get_instance()->is_maestro(this))
75     s4u::Actor::on_destruction(*get_ciface());
76 }
77
78 /* Become an actor in the simulation
79  *
80  * Currently this can only be called by the main thread (once) and only work with some thread factories
81  * (currently ThreadContextFactory).
82  *
83  * In the future, it might be extended in order to attach other threads created by a third party library.
84  */
85
86 ActorImplPtr ActorImpl::attach(const std::string& name, void* data, s4u::Host* host)
87 {
88   // This is mostly a copy/paste from create(), it'd be nice to share some code between those two functions.
89   auto* engine = EngineImpl::get_instance();
90   XBT_DEBUG("Attach actor %s on host '%s'", name.c_str(), host->get_cname());
91
92   if (not host->is_on()) {
93     XBT_WARN("Cannot attach actor '%s' on failed host '%s'", name.c_str(), host->get_cname());
94     throw HostFailureException(XBT_THROW_POINT, "Cannot attach actor on failed host.");
95   }
96
97   auto* actor = new ActorImpl(xbt::string(name), host, /*ppid*/ -1);
98   /* Actor data */
99   actor->piface_.set_data(data);
100   actor->code_ = nullptr;
101
102   XBT_VERB("Create context %s", actor->get_cname());
103   actor->context_.reset(engine->get_context_factory()->attach(actor));
104
105   /* Add the actor to it's host actor list */
106   host->get_impl()->add_actor(actor);
107
108   /* Now insert it in the global actor list and in the actors to run list */
109   engine->add_actor(actor->get_pid(), actor);
110   engine->add_actor_to_run_list_no_check(actor);
111   intrusive_ptr_add_ref(actor);
112
113   auto* context = dynamic_cast<context::AttachContext*>(actor->context_.get());
114   xbt_assert(nullptr != context, "Not a suitable context");
115   context->attach_start();
116
117   /* The on_creation() signal must be delayed until there, where the pid and everything is set */
118   s4u::Actor::on_creation(*actor->get_ciface());
119
120   return ActorImplPtr(actor);
121 }
122 /** @brief Detach an actor attached with `attach()`
123  *
124  *  This is called when the current actor has finished its job.
125  *  Used in the main thread, it waits for the simulation to finish before returning. When it returns, the other
126  *  simulated actors and the maestro are destroyed.
127  */
128 void ActorImpl::detach()
129 {
130   auto* context = dynamic_cast<context::AttachContext*>(context::Context::self());
131   xbt_assert(context != nullptr, "Not a suitable context");
132
133   context->get_actor()->cleanup_from_self();
134   context->attach_stop();
135 }
136
137 /** Whether this actor is actually maestro */
138 bool ActorImpl::is_maestro() const
139 {
140   return context_->is_maestro();
141 }
142
143 void ActorImpl::cleanup_from_kernel()
144 {
145   xbt_assert(s4u::Actor::is_maestro(), "Cleanup_from_kernel called from '%s' on '%s'", ActorImpl::self()->get_cname(),
146              get_cname());
147
148   auto* engine = EngineImpl::get_instance();
149   engine->remove_actor(get_pid());
150   if (host_ && host_actor_list_hook.is_linked())
151     host_->get_impl()->remove_actor(this);
152   if (not kernel_destroy_list_hook.is_linked())
153     engine->add_actor_to_destroy_list(*this);
154
155   if (has_to_auto_restart() && not get_host()->is_on()) {
156     XBT_DEBUG("Insert host %s to watched_hosts because it's off and %s needs to restart", get_host()->get_cname(),
157               get_cname());
158     watched_hosts().insert(get_host()->get_name());
159   }
160
161   undaemonize();
162
163   while (not mailboxes_.empty())
164     mailboxes_.back()->set_receiver(nullptr);
165 }
166
167 /* Do all the cleanups from the actor context. Warning, the simcall mechanism was not reignited so doing simcalls in
168  * this context is dangerous */
169 void ActorImpl::cleanup_from_self()
170 {
171   xbt_assert(not ActorImpl::is_maestro(), "Cleanup_from_self called from maestro on '%s'", get_cname());
172   set_to_be_freed();
173
174   if (on_exit) {
175     // Execute the termination callbacks
176     bool failed = wannadie();
177     for (auto exit_fun = on_exit->crbegin(); exit_fun != on_exit->crend(); ++exit_fun)
178       (*exit_fun)(failed);
179     on_exit.reset();
180   }
181
182   /* cancel non-blocking activities */
183   for (auto activity : activities_)
184     activity->cancel();
185   activities_.clear();
186
187   XBT_DEBUG("%s@%s(%ld) should not run anymore", get_cname(), get_host()->get_cname(), get_pid());
188
189   /* Unregister associated timers if any */
190   if (kill_timer_ != nullptr) {
191     kill_timer_->remove();
192     kill_timer_ = nullptr;
193   }
194   if (simcall_.timeout_cb_) {
195     simcall_.timeout_cb_->remove();
196     simcall_.timeout_cb_ = nullptr;
197   }
198
199   set_wannadie(false); // don't let the simcall's yield() do a Context::stop(), to avoid infinite loops
200   actor::simcall_answered([this] { s4u::Actor::on_termination(*get_ciface()); });
201   set_wannadie();
202 }
203
204 void ActorImpl::exit()
205 {
206   set_wannadie();
207   suspended_ = false;
208   exception_ = nullptr;
209
210   if (waiting_synchro_ != nullptr) {
211     /* Take an extra reference on the activity object that may be unref by Comm::finish() or friends */
212     activity::ActivityImplPtr activity = waiting_synchro_;
213     activity->cancel();
214     activity->set_state(activity::State::FAILED);
215     activity->post();
216
217     activities_.remove(waiting_synchro_);
218     waiting_synchro_ = nullptr;
219   }
220   for (auto const& activity : activities_)
221     activity->cancel();
222   activities_.clear();
223
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")));
226 }
227
228 void ActorImpl::kill(ActorImpl* actor) const
229 {
230   xbt_assert(not actor->is_maestro(), "Killing maestro is a rather bad idea.");
231   if (actor->wannadie()) {
232     XBT_DEBUG("Ignoring request to kill actor %s@%s that is already dead", actor->get_cname(),
233               actor->host_->get_cname());
234     return;
235   }
236
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() : "");
239
240   actor->exit();
241
242   if (actor == this) {
243     XBT_DEBUG("Go on, this is a suicide,");
244   } else
245     EngineImpl::get_instance()->add_actor_to_run_list(actor);
246 }
247
248 void ActorImpl::kill_all() const
249 {
250   for (auto const& kv : EngineImpl::get_instance()->get_actor_list())
251     if (kv.second != this)
252       this->kill(kv.second);
253 }
254
255 void ActorImpl::set_kill_time(double kill_time)
256 {
257   if (kill_time <= s4u::Engine::get_clock())
258     return;
259   XBT_DEBUG("Set kill time %f for actor %s@%s", kill_time, get_cname(), host_->get_cname());
260   kill_timer_ = timer::Timer::set(kill_time, [this] {
261     this->exit();
262     kill_timer_ = nullptr;
263     EngineImpl::get_instance()->add_actor_to_run_list(this);
264   });
265 }
266
267 double ActorImpl::get_kill_time() const
268 {
269   return kill_timer_ ? kill_timer_->get_date() : 0.0;
270 }
271
272 void ActorImpl::yield()
273 {
274   XBT_DEBUG("Yield actor '%s'", get_cname());
275
276   /* Go into sleep and return control to maestro */
277   context_->suspend();
278   /* Ok, maestro returned control to us */
279   XBT_DEBUG("Control returned to me: '%s'", get_cname());
280
281   if (wannadie()) {
282     XBT_DEBUG("Actor %s@%s is dead", get_cname(), host_->get_cname());
283     context_->stop();
284     THROW_IMPOSSIBLE;
285   }
286
287   if (suspended_) {
288     XBT_DEBUG("Hey! I'm suspended.");
289     xbt_assert(exception_ == nullptr, "Gasp! This exception may be lost by subsequent calls.");
290     yield(); // Yield back to maestro without proceeding with my execution. I'll get rescheduled by resume()
291   }
292
293   if (exception_ != nullptr) {
294     XBT_DEBUG("Wait, maestro left me an exception");
295     std::exception_ptr exception = std::move(exception_);
296     exception_                   = nullptr;
297     try {
298       std::rethrow_exception(std::move(exception));
299     } catch (const simgrid::Exception& e) {
300       e.rethrow_nested(XBT_THROW_POINT, boost::core::demangle(typeid(e).name()) + " raised in kernel mode.");
301     }
302   }
303 #if HAVE_SMPI
304   if (not wannadie())
305     smpi_switch_data_segment(get_iface());
306 #endif
307 }
308
309 /** This actor will be terminated automatically when the last non-daemon actor finishes */
310 void ActorImpl::daemonize()
311 {
312   if (not daemon_) {
313     daemon_ = true;
314     EngineImpl::get_instance()->add_daemon(this);
315   }
316 }
317
318 void ActorImpl::undaemonize()
319 {
320   if (daemon_) {
321     daemon_ = false;
322     EngineImpl::get_instance()->remove_daemon(this);
323   }
324 }
325
326 s4u::Actor* ActorImpl::restart()
327 {
328   xbt_assert(not this->is_maestro(), "Restarting maestro is not supported");
329
330   XBT_DEBUG("Restarting actor %s on %s", get_cname(), host_->get_cname());
331
332   // retrieve the arguments of the old actor
333   ProcessArg args(host_, this);
334
335   // kill the old actor
336   context::Context::self()->get_actor()->kill(this);
337
338   // start the new actor
339   return create(&args)->get_ciface();
340 }
341
342 void ActorImpl::suspend()
343 {
344   if (suspended_) {
345     XBT_DEBUG("Actor '%s' is already suspended", get_cname());
346     return;
347   }
348
349   suspended_ = true;
350
351   /* Suspend the activities associated with this actor. */
352   for (auto const& activity : activities_)
353     activity->suspend();
354 }
355
356 void ActorImpl::resume()
357 {
358   XBT_IN("actor = %p", this);
359
360   if (wannadie()) {
361     XBT_VERB("Ignoring request to resume an actor that is currently dying.");
362     return;
363   }
364
365   if (not suspended_)
366     return;
367   suspended_ = false;
368
369   /* resume the activities that were blocked when suspending the actor. */
370   for (auto const& activity : activities_)
371     activity->resume();
372   if (not waiting_synchro_) // Reschedule the actor if it was forcefully unscheduled in yield()
373     EngineImpl::get_instance()->add_actor_to_run_list_no_check(this);
374
375   XBT_OUT();
376 }
377
378 activity::ActivityImplPtr ActorImpl::join(const ActorImpl* actor, double timeout)
379 {
380   activity::ActivityImplPtr sleep = this->sleep(timeout);
381   if (actor->wannadie() || actor->to_be_freed()) {
382     if (sleep->surf_action_)
383       sleep->surf_action_->finish(resource::Action::State::FINISHED);
384   } else {
385     actor->on_exit->emplace_back([sleep](bool) {
386       if (sleep->surf_action_)
387         sleep->surf_action_->finish(resource::Action::State::FINISHED);
388     });
389   }
390   return sleep;
391 }
392
393 activity::ActivityImplPtr ActorImpl::sleep(double duration)
394 {
395   if (not host_->is_on())
396     throw_exception(std::make_exception_ptr(HostFailureException(
397         XBT_THROW_POINT, std::string("Host ") + host_->get_cname() + " failed, you cannot sleep there.")));
398
399   auto sleep = new activity::SleepImpl();
400   sleep->set_name("sleep").set_host(host_).set_duration(duration).start();
401   return activity::SleepImplPtr(sleep);
402 }
403
404 void ActorImpl::throw_exception(std::exception_ptr e)
405 {
406   exception_ = e;
407
408   if (suspended_)
409     resume();
410
411   /* cancel the blocking synchro if any */
412   if (waiting_synchro_) {
413     waiting_synchro_->cancel();
414     activities_.remove(waiting_synchro_);
415     waiting_synchro_ = nullptr;
416   }
417 }
418
419 void ActorImpl::simcall_answer()
420 {
421   auto* engine = EngineImpl::get_instance();
422   if (not this->is_maestro()) {
423     XBT_DEBUG("Answer simcall %s issued by %s (%p)", simcall_.get_cname(), get_cname(), this);
424     xbt_assert(simcall_.call_ != Simcall::Type::NONE);
425     simcall_.call_            = Simcall::Type::NONE;
426     const auto& actors_to_run = engine->get_actors_to_run();
427     xbt_assert(not XBT_LOG_ISENABLED(ker_actor, xbt_log_priority_debug) ||
428                    std::find(begin(actors_to_run), end(actors_to_run), this) == end(actors_to_run),
429                "Actor %p should not exist in actors_to_run!", this);
430     engine->add_actor_to_run_list_no_check(this);
431   }
432 }
433
434 void ActorImpl::set_host(s4u::Host* dest)
435 {
436   host_->get_impl()->remove_actor(this);
437   host_ = dest;
438   dest->get_impl()->add_actor(this);
439 }
440
441 ActorImplPtr ActorImpl::init(const std::string& name, s4u::Host* host) const
442 {
443   auto* actor = new ActorImpl(xbt::string(name), host, get_pid());
444
445   intrusive_ptr_add_ref(actor);
446   /* The on_creation() signal must be delayed until there, where the pid and everything is set */
447   s4u::Actor::on_creation(*actor->get_ciface());
448
449   return ActorImplPtr(actor);
450 }
451
452 ActorImpl* ActorImpl::start(const ActorCode& code)
453 {
454   xbt_assert(code && host_ != nullptr, "Invalid parameters");
455   auto* engine = EngineImpl::get_instance();
456
457   if (not host_->is_on()) {
458     XBT_WARN("Cannot launch actor '%s' on failed host '%s'", get_cname(), host_->get_cname());
459     intrusive_ptr_release(this);
460     throw HostFailureException(XBT_THROW_POINT, "Cannot start actor on failed host.");
461   }
462
463   this->code_ = code;
464   XBT_VERB("Create context %s", get_cname());
465   context_.reset(engine->get_context_factory()->create_context(ActorCode(code), this));
466
467   XBT_DEBUG("Start context '%s'", get_cname());
468
469   /* Add the actor to its host's actor list */
470   host_->get_impl()->add_actor(this);
471   engine->add_actor(get_pid(), this);
472
473   /* Now insert it in the global actor list and in the actor to run list */
474   engine->add_actor_to_run_list_no_check(this);
475
476   return this;
477 }
478
479 ActorImplPtr ActorImpl::create(const std::string& name, const ActorCode& code, void* data, s4u::Host* host,
480                                const ActorImpl* parent_actor)
481 {
482   XBT_DEBUG("Start actor %s@'%s'", name.c_str(), host->get_cname());
483
484   ActorImplPtr actor;
485   if (parent_actor != nullptr)
486     actor = parent_actor->init(xbt::string(name), host);
487   else
488     actor = self()->init(xbt::string(name), host);
489
490   actor->piface_.set_data(data); /* actor data */
491
492   actor->start(code);
493
494   return actor;
495 }
496 ActorImplPtr ActorImpl::create(ProcessArg* args)
497 {
498   ActorImplPtr actor    = ActorImpl::create(args->name, args->code, nullptr, args->host, nullptr);
499   actor->restart_count_ = args->restart_count_;
500   actor->set_properties(args->properties);
501   if (args->on_exit)
502     *actor->on_exit = *args->on_exit;
503   if (args->kill_time >= 0)
504     actor->set_kill_time(args->kill_time);
505   if (args->auto_restart)
506     actor->set_auto_restart(args->auto_restart);
507   if (args->daemon_)
508     actor->daemonize();
509   return actor;
510 }
511 void ActorImpl::set_wannadie(bool value)
512 {
513   XBT_DEBUG("Actor %s gonna die.", get_cname());
514   iwannadie_ = value;
515 }
516
517 void create_maestro(const std::function<void()>& code)
518 {
519   auto* engine = EngineImpl::get_instance();
520   /* Create maestro actor and initialize it */
521   auto* maestro = new ActorImpl(xbt::string(""), /*host*/ nullptr, /*ppid*/ -1);
522
523   if (not code) {
524     maestro->context_.reset(engine->get_context_factory()->create_context(ActorCode(), maestro));
525   } else {
526     maestro->context_.reset(engine->get_context_factory()->create_maestro(ActorCode(code), maestro));
527   }
528
529   maestro->simcall_.issuer_ = maestro;
530   engine->set_maestro(maestro);
531 }
532
533 } // namespace actor
534 } // namespace kernel
535 } // namespace simgrid
536
537 /* needs to be public and without simcall because it is called by exceptions and logging events */
538 const char* SIMIX_process_self_get_name() // XBT_ATTRIB_DEPRECATED_v333
539 {
540   return simgrid::s4u::Actor::is_maestro() ? "maestro" : simgrid::kernel::actor::ActorImpl::self()->get_cname();
541 }
542
543 int SIMIX_is_maestro() // XBT_ATTRIB_DEPRECATED_v333
544 {
545   const auto* self = simgrid::kernel::actor::ActorImpl::self();
546   return self != nullptr && self->is_maestro();
547 }