Logo AND Algorithmique Numérique Distribuée

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