Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Eventually, OOP is really good.
[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 #include "src/kernel/EngineImpl.hpp"
11 #if HAVE_SMPI
12 #include "src/smpi/include/private.hpp"
13 #endif
14 #include "src/surf/HostImpl.hpp"
15
16 #include <boost/core/demangle.hpp>
17 #include <typeinfo>
18 #include <utility>
19
20 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(ker_actor, kernel, "Logging specific to Actor's kernel side");
21
22 /**
23  * @brief Returns the current agent.
24  *
25  * This functions returns the currently running SIMIX process.
26  *
27  * @return The SIMIX process
28  */
29 smx_actor_t SIMIX_process_self() // XBT_ATTRIB_DEPRECATED_v333
30 {
31   return simgrid::kernel::actor::ActorImpl::self();
32 }
33
34 namespace simgrid {
35 namespace kernel {
36 namespace actor {
37
38 static unsigned long maxpid = 0;
39 unsigned long get_maxpid()
40 {
41   return maxpid;
42 }
43 unsigned long* get_maxpid_addr()
44 {
45   return &maxpid;
46 }
47 ActorImpl* ActorImpl::by_pid(aid_t pid)
48 {
49   return EngineImpl::get_instance()->get_actor_by_pid(pid);
50 }
51
52 ActorImpl* ActorImpl::self()
53 {
54   const context::Context* self_context = context::Context::self();
55
56   return (self_context != nullptr) ? self_context->get_actor() : nullptr;
57 }
58
59 ActorImpl::ActorImpl(xbt::string name, s4u::Host* host) : host_(host), name_(std::move(name)), piface_(this)
60 {
61   pid_            = maxpid++;
62   simcall_.issuer_ = this;
63   stacksize_       = context::stack_size;
64 }
65
66 ActorImpl::~ActorImpl()
67 {
68   if (EngineImpl::has_instance() && not EngineImpl::get_instance()->is_maestro(this))
69     s4u::Actor::on_destruction(*get_ciface());
70 }
71
72 /* Become an actor in the simulation
73  *
74  * Currently this can only be called by the main thread (once) and only work with some thread factories
75  * (currently ThreadContextFactory).
76  *
77  * In the future, it might be extended in order to attach other threads created by a third party library.
78  */
79
80 ActorImplPtr ActorImpl::attach(const std::string& name, void* data, s4u::Host* host)
81 {
82   // This is mostly a copy/paste from create(), it'd be nice to share some code between those two functions.
83   auto* engine = EngineImpl::get_instance();
84   XBT_DEBUG("Attach actor %s on host '%s'", name.c_str(), host->get_cname());
85
86   if (not host->is_on()) {
87     XBT_WARN("Cannot attach actor '%s' on failed host '%s'", name.c_str(), host->get_cname());
88     throw HostFailureException(XBT_THROW_POINT, "Cannot attach actor on failed host.");
89   }
90
91   auto* actor = new ActorImpl(xbt::string(name), host);
92   /* Actor data */
93   actor->piface_.set_data(data);
94   actor->code_ = nullptr;
95
96   XBT_VERB("Create context %s", actor->get_cname());
97   actor->context_.reset(engine->get_context_factory()->attach(actor));
98
99   /* Add the actor to it's host actor list */
100   host->get_impl()->add_actor(actor);
101
102   /* Now insert it in the global actor list and in the actors to run list */
103   engine->add_actor(actor->get_pid(), actor);
104   engine->add_actor_to_run_list_no_check(actor);
105   intrusive_ptr_add_ref(actor);
106
107   auto* context = dynamic_cast<context::AttachContext*>(actor->context_.get());
108   xbt_assert(nullptr != context, "Not a suitable context");
109   context->attach_start();
110
111   /* The on_creation() signal must be delayed until there, where the pid and everything is set */
112   s4u::Actor::on_creation(*actor->get_ciface());
113
114   return ActorImplPtr(actor);
115 }
116 /** @brief Detach an actor attached with `attach()`
117  *
118  *  This is called when the current actor has finished its job.
119  *  Used in the main thread, it waits for the simulation to finish before returning. When it returns, the other
120  *  simulated actors and the maestro are destroyed.
121  */
122 void ActorImpl::detach()
123 {
124   auto* context = dynamic_cast<context::AttachContext*>(context::Context::self());
125   xbt_assert(context != nullptr, "Not a suitable context");
126
127   context->get_actor()->cleanup();
128   context->attach_stop();
129 }
130
131 /** Whether this actor is actually maestro */
132 bool ActorImpl::is_maestro() const
133 {
134   return context_->is_maestro();
135 }
136
137 void ActorImpl::cleanup_from_simix()
138 {
139   auto* engine = EngineImpl::get_instance();
140   const std::lock_guard<std::mutex> lock(engine->get_mutex());
141   engine->remove_actor(pid_);
142   if (host_ && host_actor_list_hook.is_linked())
143     host_->get_impl()->remove_actor(this);
144   if (not kernel_destroy_list_hook.is_linked())
145     engine->add_actor_to_destroy_list(*this);
146 }
147
148 void ActorImpl::cleanup()
149 {
150   finished_ = true;
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   if (on_exit) {
159     // Execute the termination callbacks
160     bool failed = context_->wannadie();
161     for (auto exit_fun = on_exit->crbegin(); exit_fun != on_exit->crend(); ++exit_fun)
162       (*exit_fun)(failed);
163     on_exit.reset();
164   }
165   undaemonize();
166
167   /* cancel non-blocking activities */
168   for (auto activity : activities_)
169     activity->cancel();
170   activities_.clear();
171
172   XBT_DEBUG("%s@%s(%ld) should not run anymore", get_cname(), get_host()->get_cname(), get_pid());
173
174   if (EngineImpl::get_instance()->is_maestro(this)) /* Do not cleanup maestro */
175     return;
176
177   XBT_DEBUG("Cleanup actor %s (%p), waiting synchro %p", get_cname(), this, waiting_synchro_.get());
178
179   /* Unregister associated timers if any */
180   if (kill_timer_ != nullptr) {
181     kill_timer_->remove();
182     kill_timer_ = nullptr;
183   }
184   if (simcall_.timeout_cb_) {
185     simcall_.timeout_cb_->remove();
186     simcall_.timeout_cb_ = nullptr;
187   }
188
189   cleanup_from_simix();
190
191   context_->set_wannadie(false); // don't let the simcall's yield() do a Context::stop(), to avoid infinite loops
192   actor::simcall_answered([this] { s4u::Actor::on_termination(*get_ciface()); });
193   context_->set_wannadie();
194 }
195
196 void ActorImpl::exit()
197 {
198   context_->set_wannadie();
199   suspended_          = false;
200   exception_          = nullptr;
201
202   /* destroy the blocking synchro if any */
203   if (auto activity = waiting_synchro_) {
204     activities_.remove(waiting_synchro_);
205     waiting_synchro_ = nullptr;
206
207     activity->cancel();
208     activity->set_state(activity::State::FAILED);
209     activity->post();
210   }
211   for (auto const& activity : activities_)
212     activity->cancel();
213   activities_.clear();
214
215   // Forcefully kill the actor if its host is turned off. Not a HostFailureException because you should not survive that
216   this->throw_exception(std::make_exception_ptr(ForcefulKillException(host_->is_on() ? "exited" : "host failed")));
217 }
218
219 void ActorImpl::kill(ActorImpl* actor) const
220 {
221   xbt_assert(not actor->is_maestro(), "Killing maestro is a rather bad idea.");
222   if (actor->finished_) {
223     XBT_DEBUG("Ignoring request to kill actor %s@%s that is already dead", actor->get_cname(),
224               actor->host_->get_cname());
225     return;
226   }
227
228   XBT_DEBUG("Actor '%s'@%s is killing actor '%s'@%s", get_cname(), host_ ? host_->get_cname() : "", actor->get_cname(),
229             actor->host_ ? actor->host_->get_cname() : "");
230
231   actor->exit();
232
233   if (actor == this) {
234     XBT_DEBUG("Go on, this is a suicide,");
235   } else
236     EngineImpl::get_instance()->add_actor_to_run_list(actor);
237 }
238
239 void ActorImpl::kill_all() const
240 {
241   for (auto const& kv : EngineImpl::get_instance()->get_actor_list())
242     if (kv.second != this)
243       this->kill(kv.second);
244 }
245
246 void ActorImpl::set_kill_time(double kill_time)
247 {
248   if (kill_time <= s4u::Engine::get_clock())
249     return;
250   XBT_DEBUG("Set kill time %f for actor %s@%s", kill_time, get_cname(), host_->get_cname());
251   kill_timer_ = timer::Timer::set(kill_time, [this] {
252     this->exit();
253     kill_timer_ = nullptr;
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 (context_->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 finished_)
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 arg(host_, this);
324
325   // kill the old actor
326   context::Context::self()->get_actor()->kill(this);
327
328   // start the new actor
329   ActorImplPtr actor = ActorImpl::create(arg.name, arg.code, arg.data, arg.host, nullptr);
330   actor->set_properties(arg.properties);
331   *actor->on_exit = std::move(*arg.on_exit);
332   actor->set_kill_time(arg.kill_time);
333   actor->set_auto_restart(arg.auto_restart);
334
335   return actor->get_ciface();
336 }
337
338 void ActorImpl::suspend()
339 {
340   if (suspended_) {
341     XBT_DEBUG("Actor '%s' is already suspended", get_cname());
342     return;
343   }
344
345   suspended_ = true;
346
347   /* Suspend the activities associated with this actor. */
348   for (auto const& activity : activities_)
349     activity->suspend();
350 }
351
352 void ActorImpl::resume()
353 {
354   XBT_IN("actor = %p", this);
355
356   if (context_->wannadie()) {
357     XBT_VERB("Ignoring request to suspend an actor that is currently dying.");
358     return;
359   }
360
361   if (not suspended_)
362     return;
363   suspended_ = false;
364
365   /* resume the activities that were blocked when suspending the actor. */
366   for (auto const& activity : activities_)
367     activity->resume();
368   if (not waiting_synchro_) // Reschedule the actor if it was forcefully unscheduled in yield()
369     EngineImpl::get_instance()->add_actor_to_run_list_no_check(this);
370
371   XBT_OUT();
372 }
373
374 activity::ActivityImplPtr ActorImpl::join(const ActorImpl* actor, double timeout)
375 {
376   activity::ActivityImplPtr sleep = this->sleep(timeout);
377   actor->on_exit->emplace_back([sleep](bool) {
378     if (sleep->surf_action_)
379       sleep->surf_action_->finish(resource::Action::State::FINISHED);
380   });
381   return sleep;
382 }
383
384 activity::ActivityImplPtr ActorImpl::sleep(double duration)
385 {
386   if (not host_->is_on())
387     throw_exception(std::make_exception_ptr(HostFailureException(
388         XBT_THROW_POINT, std::string("Host ") + host_->get_cname() + " failed, you cannot sleep there.")));
389
390   auto sleep = new activity::SleepImpl();
391   sleep->set_name("sleep").set_host(host_).set_duration(duration).start();
392   return activity::SleepImplPtr(sleep);
393 }
394
395 void ActorImpl::throw_exception(std::exception_ptr e)
396 {
397   exception_ = e;
398
399   if (suspended_)
400     resume();
401
402   /* cancel the blocking synchro if any */
403   if (waiting_synchro_) {
404     waiting_synchro_->cancel();
405     activities_.remove(waiting_synchro_);
406     waiting_synchro_ = nullptr;
407   }
408 }
409
410 void ActorImpl::simcall_answer()
411 {
412   auto* engine = EngineImpl::get_instance();
413   if (not this->is_maestro()) {
414     XBT_DEBUG("Answer simcall %s issued by %s (%p)", SIMIX_simcall_name(simcall_), get_cname(), this);
415     xbt_assert(simcall_.call_ != simix::Simcall::NONE);
416     simcall_.call_ = simix::Simcall::NONE;
417     const auto& actors_to_run = engine->get_actors_to_run();
418     xbt_assert(not XBT_LOG_ISENABLED(ker_actor, xbt_log_priority_debug) ||
419                    std::find(begin(actors_to_run), end(actors_to_run), this) == end(actors_to_run),
420                "Actor %p should not exist in actors_to_run!", this);
421     engine->add_actor_to_run_list_no_check(this);
422   }
423 }
424
425 void ActorImpl::set_host(s4u::Host* dest)
426 {
427   host_->get_impl()->remove_actor(this);
428   host_ = dest;
429   dest->get_impl()->add_actor(this);
430 }
431
432 ActorImplPtr ActorImpl::init(const std::string& name, s4u::Host* host) const
433 {
434   auto* actor = new ActorImpl(xbt::string(name), host);
435   actor->set_ppid(this->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'", name_.c_str(), 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(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
489 void create_maestro(const std::function<void()>& code)
490 {
491   auto* engine = EngineImpl::get_instance();
492   /* Create maestro actor and initialize it */
493   auto* maestro = new ActorImpl(xbt::string(""), /*host*/ nullptr);
494
495   if (not code) {
496     maestro->context_.reset(engine->get_context_factory()->create_context(ActorCode(), maestro));
497   } else {
498     maestro->context_.reset(engine->get_context_factory()->create_maestro(ActorCode(code), maestro));
499   }
500
501   maestro->simcall_.issuer_ = maestro;
502   engine->set_maestro(maestro);
503 }
504
505 } // namespace actor
506 } // namespace kernel
507 } // namespace simgrid
508
509 /* needs to be public and without simcall because it is called by exceptions and logging events */
510 const char* SIMIX_process_self_get_name() // XBT_ATTRIB_DEPRECATED_v333
511 {
512   return simgrid::s4u::Actor::is_maestro() ? "maestro" : simgrid::kernel::actor::ActorImpl::self()->get_cname();
513 }
514
515 int SIMIX_is_maestro() // XBT_ATTRIB_DEPRECATED_v333
516 {
517   const auto* self = simgrid::kernel::actor::ActorImpl::self();
518   return self != nullptr && self->is_maestro();
519 }