Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Move Simcall from namespace simix to kernel::actor.
[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();
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_simix()
141 {
142   auto* engine = EngineImpl::get_instance();
143   const std::lock_guard<std::mutex> lock(engine->get_mutex());
144   engine->remove_actor(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
151 void ActorImpl::cleanup()
152 {
153   finished_ = true;
154
155   if (has_to_auto_restart() && not get_host()->is_on()) {
156     XBT_DEBUG("Insert host %s to watched_hosts because it's off and %s needs to restart", get_host()->get_cname(),
157               get_cname());
158     watched_hosts().insert(get_host()->get_name());
159   }
160
161   if (on_exit) {
162     // Execute the termination callbacks
163     bool failed = context_->wannadie();
164     for (auto exit_fun = on_exit->crbegin(); exit_fun != on_exit->crend(); ++exit_fun)
165       (*exit_fun)(failed);
166     on_exit.reset();
167   }
168   undaemonize();
169
170   /* cancel non-blocking activities */
171   for (auto activity : activities_)
172     activity->cancel();
173   activities_.clear();
174
175   while (not mailboxes.empty())
176     mailboxes.back()->set_receiver(nullptr);
177
178   XBT_DEBUG("%s@%s(%ld) should not run anymore", get_cname(), get_host()->get_cname(), get_pid());
179
180   if (EngineImpl::get_instance()->is_maestro(this)) /* Do not cleanup maestro */
181     return;
182
183   XBT_DEBUG("Cleanup actor %s (%p), waiting synchro %p", get_cname(), this, waiting_synchro_.get());
184
185   /* Unregister associated timers if any */
186   if (kill_timer_ != nullptr) {
187     kill_timer_->remove();
188     kill_timer_ = nullptr;
189   }
190   if (simcall_.timeout_cb_) {
191     simcall_.timeout_cb_->remove();
192     simcall_.timeout_cb_ = nullptr;
193   }
194
195   cleanup_from_simix();
196
197   context_->set_wannadie(false); // don't let the simcall's yield() do a Context::stop(), to avoid infinite loops
198   actor::simcall_answered([this] { s4u::Actor::on_termination(*get_ciface()); });
199   context_->set_wannadie();
200 }
201
202 void ActorImpl::exit()
203 {
204   context_->set_wannadie();
205   suspended_          = false;
206   exception_          = nullptr;
207
208   /* destroy the blocking synchro if any */
209   if (auto activity = waiting_synchro_) {
210     activities_.remove(waiting_synchro_);
211     waiting_synchro_ = nullptr;
212
213     activity->cancel();
214     activity->set_state(activity::State::FAILED);
215     activity->post();
216   }
217   for (auto const& activity : activities_)
218     activity->cancel();
219   activities_.clear();
220
221   while (not mailboxes.empty())
222     mailboxes.back()->set_receiver(nullptr);
223
224   // Forcefully kill the actor if its host is turned off. Not a HostFailureException because you should not survive that
225   this->throw_exception(std::make_exception_ptr(ForcefulKillException(host_->is_on() ? "exited" : "host failed")));
226 }
227
228 void ActorImpl::kill(ActorImpl* actor) const
229 {
230   xbt_assert(not actor->is_maestro(), "Killing maestro is a rather bad idea.");
231   if (actor->finished_) {
232     XBT_DEBUG("Ignoring request to kill actor %s@%s that is already dead", actor->get_cname(),
233               actor->host_->get_cname());
234     return;
235   }
236
237   XBT_DEBUG("Actor '%s'@%s is killing actor '%s'@%s", get_cname(), host_ ? host_->get_cname() : "", actor->get_cname(),
238             actor->host_ ? actor->host_->get_cname() : "");
239
240   actor->exit();
241
242   if (actor == this) {
243     XBT_DEBUG("Go on, this is a suicide,");
244   } else
245     EngineImpl::get_instance()->add_actor_to_run_list(actor);
246 }
247
248 void ActorImpl::kill_all() const
249 {
250   for (auto const& kv : EngineImpl::get_instance()->get_actor_list())
251     if (kv.second != this)
252       this->kill(kv.second);
253 }
254
255 void ActorImpl::set_kill_time(double kill_time)
256 {
257   if (kill_time <= s4u::Engine::get_clock())
258     return;
259   XBT_DEBUG("Set kill time %f for actor %s@%s", kill_time, get_cname(), host_->get_cname());
260   kill_timer_ = timer::Timer::set(kill_time, [this] {
261     this->exit();
262     kill_timer_ = nullptr;
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 (context_->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 finished_)
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 arg(host_, this);
333
334   // kill the old actor
335   context::Context::self()->get_actor()->kill(this);
336
337   // start the new actor
338   ActorImplPtr actor = ActorImpl::create(arg.name, arg.code, arg.data, arg.host, nullptr);
339   actor->set_properties(arg.properties);
340   *actor->on_exit = std::move(*arg.on_exit);
341   actor->set_kill_time(arg.kill_time);
342   actor->set_auto_restart(arg.auto_restart);
343
344   return actor->get_ciface();
345 }
346
347 void ActorImpl::suspend()
348 {
349   if (suspended_) {
350     XBT_DEBUG("Actor '%s' is already suspended", get_cname());
351     return;
352   }
353
354   suspended_ = true;
355
356   /* Suspend the activities associated with this actor. */
357   for (auto const& activity : activities_)
358     activity->suspend();
359 }
360
361 void ActorImpl::resume()
362 {
363   XBT_IN("actor = %p", this);
364
365   if (context_->wannadie()) {
366     XBT_VERB("Ignoring request to suspend an actor that is currently dying.");
367     return;
368   }
369
370   if (not suspended_)
371     return;
372   suspended_ = false;
373
374   /* resume the activities that were blocked when suspending the actor. */
375   for (auto const& activity : activities_)
376     activity->resume();
377   if (not waiting_synchro_) // Reschedule the actor if it was forcefully unscheduled in yield()
378     EngineImpl::get_instance()->add_actor_to_run_list_no_check(this);
379
380   XBT_OUT();
381 }
382
383 activity::ActivityImplPtr ActorImpl::join(const ActorImpl* actor, double timeout)
384 {
385   activity::ActivityImplPtr sleep = this->sleep(timeout);
386   actor->on_exit->emplace_back([sleep](bool) {
387     if (sleep->surf_action_)
388       sleep->surf_action_->finish(resource::Action::State::FINISHED);
389   });
390   return sleep;
391 }
392
393 activity::ActivityImplPtr ActorImpl::sleep(double duration)
394 {
395   if (not host_->is_on())
396     throw_exception(std::make_exception_ptr(HostFailureException(
397         XBT_THROW_POINT, std::string("Host ") + host_->get_cname() + " failed, you cannot sleep there.")));
398
399   auto sleep = new activity::SleepImpl();
400   sleep->set_name("sleep").set_host(host_).set_duration(duration).start();
401   return activity::SleepImplPtr(sleep);
402 }
403
404 void ActorImpl::throw_exception(std::exception_ptr e)
405 {
406   exception_ = e;
407
408   if (suspended_)
409     resume();
410
411   /* cancel the blocking synchro if any */
412   if (waiting_synchro_) {
413     waiting_synchro_->cancel();
414     activities_.remove(waiting_synchro_);
415     waiting_synchro_ = nullptr;
416   }
417 }
418
419 void ActorImpl::simcall_answer()
420 {
421   auto* engine = EngineImpl::get_instance();
422   if (not this->is_maestro()) {
423     XBT_DEBUG("Answer simcall %s issued by %s (%p)", simcall_.get_cname(), get_cname(), this);
424     xbt_assert(simcall_.call_ != Simcall::Type::NONE);
425     simcall_.call_            = Simcall::Type::NONE;
426     const auto& actors_to_run = engine->get_actors_to_run();
427     xbt_assert(not XBT_LOG_ISENABLED(ker_actor, xbt_log_priority_debug) ||
428                    std::find(begin(actors_to_run), end(actors_to_run), this) == end(actors_to_run),
429                "Actor %p should not exist in actors_to_run!", this);
430     engine->add_actor_to_run_list_no_check(this);
431   }
432 }
433
434 void ActorImpl::set_host(s4u::Host* dest)
435 {
436   host_->get_impl()->remove_actor(this);
437   host_ = dest;
438   dest->get_impl()->add_actor(this);
439 }
440
441 ActorImplPtr ActorImpl::init(const std::string& name, s4u::Host* host) const
442 {
443   auto* actor = new ActorImpl(xbt::string(name), host);
444   actor->set_ppid(this->pid_);
445
446   intrusive_ptr_add_ref(actor);
447   /* The on_creation() signal must be delayed until there, where the pid and everything is set */
448   s4u::Actor::on_creation(*actor->get_ciface());
449
450   return ActorImplPtr(actor);
451 }
452
453 ActorImpl* ActorImpl::start(const ActorCode& code)
454 {
455   xbt_assert(code && host_ != nullptr, "Invalid parameters");
456   auto* engine = EngineImpl::get_instance();
457
458   if (not host_->is_on()) {
459     XBT_WARN("Cannot launch actor '%s' on failed host '%s'", name_.c_str(), host_->get_cname());
460     intrusive_ptr_release(this);
461     throw HostFailureException(XBT_THROW_POINT, "Cannot start actor on failed host.");
462   }
463
464   this->code_ = code;
465   XBT_VERB("Create context %s", get_cname());
466   context_.reset(engine->get_context_factory()->create_context(ActorCode(code), this));
467
468   XBT_DEBUG("Start context '%s'", get_cname());
469
470   /* Add the actor to its host's actor list */
471   host_->get_impl()->add_actor(this);
472   engine->add_actor(pid_, this);
473
474   /* Now insert it in the global actor list and in the actor to run list */
475   engine->add_actor_to_run_list_no_check(this);
476
477   return this;
478 }
479
480 ActorImplPtr ActorImpl::create(const std::string& name, const ActorCode& code, void* data, s4u::Host* host,
481                                const ActorImpl* parent_actor)
482 {
483   XBT_DEBUG("Start actor %s@'%s'", name.c_str(), host->get_cname());
484
485   ActorImplPtr actor;
486   if (parent_actor != nullptr)
487     actor = parent_actor->init(xbt::string(name), host);
488   else
489     actor = self()->init(xbt::string(name), host);
490
491   actor->piface_.set_data(data); /* actor data */
492
493   actor->start(code);
494
495   return actor;
496 }
497
498 void create_maestro(const std::function<void()>& code)
499 {
500   auto* engine = EngineImpl::get_instance();
501   /* Create maestro actor and initialize it */
502   auto* maestro = new ActorImpl(xbt::string(""), /*host*/ nullptr);
503
504   if (not code) {
505     maestro->context_.reset(engine->get_context_factory()->create_context(ActorCode(), maestro));
506   } else {
507     maestro->context_.reset(engine->get_context_factory()->create_maestro(ActorCode(code), maestro));
508   }
509
510   maestro->simcall_.issuer_ = maestro;
511   engine->set_maestro(maestro);
512 }
513
514 } // namespace actor
515 } // namespace kernel
516 } // namespace simgrid
517
518 /* needs to be public and without simcall because it is called by exceptions and logging events */
519 const char* SIMIX_process_self_get_name() // XBT_ATTRIB_DEPRECATED_v333
520 {
521   return simgrid::s4u::Actor::is_maestro() ? "maestro" : simgrid::kernel::actor::ActorImpl::self()->get_cname();
522 }
523
524 int SIMIX_is_maestro() // XBT_ATTRIB_DEPRECATED_v333
525 {
526   const auto* self = simgrid::kernel::actor::ActorImpl::self();
527   return self != nullptr && self->is_maestro();
528 }