Logo AND Algorithmique Numérique Distribuée

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