Logo AND Algorithmique Numérique Distribuée

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