Logo AND Algorithmique Numérique Distribuée

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