Logo AND Algorithmique Numérique Distribuée

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