Logo AND Algorithmique Numérique Distribuée

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