Logo AND Algorithmique Numérique Distribuée

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