Logo AND Algorithmique Numérique Distribuée

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