Logo AND Algorithmique Numérique Distribuée

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