Logo AND Algorithmique Numérique Distribuée

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