Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
deprecate SIMIX_is_maestro
[simgrid.git] / src / kernel / actor / ActorImpl.cpp
1 /* Copyright (c) 2007-2021. 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(simix_process, simix, "Logging specific to SIMIX (process)");
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 void ActorImpl::cleanup_from_simix()
132 {
133   auto* engine = EngineImpl::get_instance();
134   const std::lock_guard<std::mutex> lock(engine->get_mutex());
135   engine->remove_actor(pid_);
136   if (host_ && host_actor_list_hook.is_linked())
137     host_->get_impl()->remove_actor(this);
138   if (not kernel_destroy_list_hook.is_linked()) {
139 #if SIMGRID_HAVE_MC
140     engine->add_dead_actor_to_dynar(this);
141 #endif
142     engine->add_actor_to_destroy_list(*this);
143   }
144 }
145
146 void ActorImpl::cleanup()
147 {
148   finished_ = true;
149
150   if (has_to_auto_restart() && not get_host()->is_on()) {
151     XBT_DEBUG("Insert host %s to watched_hosts because it's off and %s needs to restart", get_host()->get_cname(),
152               get_cname());
153     watched_hosts().insert(get_host()->get_name());
154   }
155
156   if (on_exit) {
157     // Execute the termination callbacks
158     bool failed = context_->wannadie();
159     for (auto exit_fun = on_exit->crbegin(); exit_fun != on_exit->crend(); ++exit_fun)
160       (*exit_fun)(failed);
161     on_exit.reset();
162   }
163   undaemonize();
164
165   /* cancel non-blocking activities */
166   for (auto activity : activities_)
167     activity->cancel();
168   activities_.clear();
169
170   XBT_DEBUG("%s@%s(%ld) should not run anymore", get_cname(), get_host()->get_cname(), get_pid());
171
172   if (EngineImpl::get_instance()->is_maestro(this)) /* Do not cleanup maestro */
173     return;
174
175   XBT_DEBUG("Cleanup actor %s (%p), waiting synchro %p", get_cname(), this, waiting_synchro_.get());
176
177   /* Unregister associated timers if any */
178   if (kill_timer_ != nullptr) {
179     kill_timer_->remove();
180     kill_timer_ = nullptr;
181   }
182   if (simcall_.timeout_cb_) {
183     simcall_.timeout_cb_->remove();
184     simcall_.timeout_cb_ = nullptr;
185   }
186
187   cleanup_from_simix();
188
189   context_->set_wannadie(false); // don't let the simcall's yield() do a Context::stop(), to avoid infinite loops
190   actor::simcall([this] { s4u::Actor::on_termination(*get_ciface()); });
191   context_->set_wannadie();
192 }
193
194 void ActorImpl::exit()
195 {
196   context_->set_wannadie();
197   suspended_          = false;
198   exception_          = nullptr;
199
200   /* destroy the blocking synchro if any */
201   if (waiting_synchro_ != nullptr) {
202     waiting_synchro_->cancel();
203     waiting_synchro_->state_ = activity::State::FAILED;
204
205     activity::ExecImplPtr exec = boost::dynamic_pointer_cast<activity::ExecImpl>(waiting_synchro_);
206     activity::CommImplPtr comm = boost::dynamic_pointer_cast<activity::CommImpl>(waiting_synchro_);
207
208     if (exec != nullptr) {
209       exec->clean_action();
210     } else if (comm != nullptr) {
211       comm->unregister_simcall(&simcall_);
212     } else {
213       activity::ActivityImplPtr(waiting_synchro_)->finish();
214     }
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   auto* engine = EngineImpl::get_instance();
230   xbt_assert(not engine->is_maestro(actor), "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     engine->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
278   /* Ok, maestro returned control to us */
279   XBT_DEBUG("Control returned to me: '%s'", get_cname());
280
281   if (context_->wannadie()) {
282     XBT_DEBUG("Actor %s@%s is dead", get_cname(), host_->get_cname());
283     context_->stop();
284     THROW_IMPOSSIBLE;
285   }
286
287   if (suspended_) {
288     XBT_DEBUG("Hey! I'm suspended.");
289     xbt_assert(exception_ == nullptr, "Gasp! This exception may be lost by subsequent calls.");
290     yield(); // Yield back to maestro without proceeding with my execution. I'll get rescheduled by resume()
291   }
292
293   if (exception_ != nullptr) {
294     XBT_DEBUG("Wait, maestro left me an exception");
295     std::exception_ptr exception = std::move(exception_);
296     exception_                   = nullptr;
297     try {
298       std::rethrow_exception(std::move(exception));
299     } catch (const simgrid::Exception& e) {
300       e.rethrow_nested(XBT_THROW_POINT, boost::core::demangle(typeid(e).name()) + " raised in kernel mode.");
301     }
302   }
303
304 #if HAVE_SMPI
305   if (not finished_)
306     smpi_switch_data_segment(get_iface());
307 #endif
308 }
309
310 /** This actor will be terminated automatically when the last non-daemon actor finishes */
311 void ActorImpl::daemonize()
312 {
313   if (not daemon_) {
314     daemon_ = true;
315     EngineImpl::get_instance()->add_daemon(this);
316   }
317 }
318
319 void ActorImpl::undaemonize()
320 {
321   if (daemon_) {
322     daemon_ = false;
323     EngineImpl::get_instance()->remove_daemon(this);
324   }
325 }
326
327 s4u::Actor* ActorImpl::restart()
328 {
329   xbt_assert(not EngineImpl::get_instance()->is_maestro(this), "Restarting maestro is not supported");
330
331   XBT_DEBUG("Restarting actor %s on %s", get_cname(), host_->get_cname());
332
333   // retrieve the arguments of the old actor
334   ProcessArg arg(host_, this);
335
336   // kill the old actor
337   context::Context::self()->get_actor()->kill(this);
338
339   // start the new actor
340   ActorImplPtr actor = ActorImpl::create(arg.name, arg.code, arg.data, arg.host, nullptr);
341   actor->set_properties(arg.properties);
342   *actor->on_exit = std::move(*arg.on_exit);
343   actor->set_kill_time(arg.kill_time);
344   actor->set_auto_restart(arg.auto_restart);
345
346   return actor->get_ciface();
347 }
348
349 void ActorImpl::suspend()
350 {
351   if (suspended_) {
352     XBT_DEBUG("Actor '%s' is already suspended", get_cname());
353     return;
354   }
355
356   suspended_ = true;
357
358   /* Suspend the activities associated with this actor. */
359   for (auto const& activity : activities_)
360     activity->suspend();
361 }
362
363 void ActorImpl::resume()
364 {
365   XBT_IN("actor = %p", this);
366
367   if (context_->wannadie()) {
368     XBT_VERB("Ignoring request to suspend an actor that is currently dying.");
369     return;
370   }
371
372   if (not suspended_)
373     return;
374   suspended_ = false;
375
376   /* resume the activities that were blocked when suspending the actor. */
377   for (auto const& activity : activities_)
378     activity->resume();
379   if (not waiting_synchro_) // Reschedule the actor if it was forcefully unscheduled in yield()
380     EngineImpl::get_instance()->add_actor_to_run_list_no_check(this);
381
382   XBT_OUT();
383 }
384
385 activity::ActivityImplPtr ActorImpl::join(const ActorImpl* actor, double timeout)
386 {
387   activity::ActivityImplPtr sleep = this->sleep(timeout);
388   actor->on_exit->emplace_back([sleep](bool) {
389     if (sleep->surf_action_)
390       sleep->surf_action_->finish(resource::Action::State::FINISHED);
391   });
392   return sleep;
393 }
394
395 activity::ActivityImplPtr ActorImpl::sleep(double duration)
396 {
397   if (not host_->is_on())
398     throw_exception(std::make_exception_ptr(HostFailureException(
399         XBT_THROW_POINT, std::string("Host ") + host_->get_cname() + " failed, you cannot sleep there.")));
400
401   auto sleep = new activity::SleepImpl();
402   sleep->set_name("sleep").set_host(host_).set_duration(duration).start();
403   return activity::SleepImplPtr(sleep);
404 }
405
406 void ActorImpl::throw_exception(std::exception_ptr e)
407 {
408   exception_ = e;
409
410   if (suspended_)
411     resume();
412
413   /* cancel the blocking synchro if any */
414   if (waiting_synchro_) {
415     waiting_synchro_->cancel();
416     activities_.remove(waiting_synchro_);
417     waiting_synchro_ = nullptr;
418   }
419 }
420
421 void ActorImpl::simcall_answer()
422 {
423   auto* engine = EngineImpl::get_instance();
424   if (not engine->is_maestro(this)) {
425     XBT_DEBUG("Answer simcall %s issued by %s (%p)", SIMIX_simcall_name(simcall_), get_cname(), this);
426     xbt_assert(simcall_.call_ != simix::Simcall::NONE);
427     simcall_.call_ = simix::Simcall::NONE;
428     const auto& actors_to_run = engine->get_actors_to_run();
429     xbt_assert(not XBT_LOG_ISENABLED(simix_process, xbt_log_priority_debug) ||
430                    std::find(begin(actors_to_run), end(actors_to_run), this) == end(actors_to_run),
431                "Actor %p should not exist in actors_to_run!", this);
432     engine->add_actor_to_run_list_no_check(this);
433   }
434 }
435
436 void ActorImpl::set_host(s4u::Host* dest)
437 {
438   host_->get_impl()->remove_actor(this);
439   host_ = dest;
440   dest->get_impl()->add_actor(this);
441 }
442
443 ActorImplPtr ActorImpl::init(const std::string& name, s4u::Host* host) const
444 {
445   auto* actor = new ActorImpl(xbt::string(name), host);
446   actor->set_ppid(this->pid_);
447
448   intrusive_ptr_add_ref(actor);
449   /* The on_creation() signal must be delayed until there, where the pid and everything is set */
450   s4u::Actor::on_creation(*actor->get_ciface());
451
452   return ActorImplPtr(actor);
453 }
454
455 ActorImpl* ActorImpl::start(const ActorCode& code)
456 {
457   xbt_assert(code && host_ != nullptr, "Invalid parameters");
458   auto* engine = EngineImpl::get_instance();
459
460   if (not host_->is_on()) {
461     XBT_WARN("Cannot launch actor '%s' on failed host '%s'", name_.c_str(), host_->get_cname());
462     intrusive_ptr_release(this);
463     throw HostFailureException(XBT_THROW_POINT, "Cannot start actor on failed host.");
464   }
465
466   this->code_ = code;
467   XBT_VERB("Create context %s", get_cname());
468   context_.reset(engine->get_context_factory()->create_context(ActorCode(code), this));
469
470   XBT_DEBUG("Start context '%s'", get_cname());
471
472   /* Add the actor to its host's actor list */
473   host_->get_impl()->add_actor(this);
474   engine->add_actor(pid_, this);
475
476   /* Now insert it in the global actor list and in the actor to run list */
477   engine->add_actor_to_run_list_no_check(this);
478
479   return this;
480 }
481
482 ActorImplPtr ActorImpl::create(const std::string& name, const ActorCode& code, void* data, s4u::Host* host,
483                                const ActorImpl* parent_actor)
484 {
485   XBT_DEBUG("Start actor %s@'%s'", name.c_str(), host->get_cname());
486
487   ActorImplPtr actor;
488   if (parent_actor != nullptr)
489     actor = parent_actor->init(xbt::string(name), host);
490   else
491     actor = self()->init(xbt::string(name), host);
492
493   /* actor data */
494   actor->piface_.set_data(data);
495
496   actor->start(code);
497
498   return actor;
499 }
500
501 void create_maestro(const std::function<void()>& code)
502 {
503   auto* engine = EngineImpl::get_instance();
504   /* Create maestro actor and initialize it */
505   auto* maestro = new ActorImpl(xbt::string(""), /*host*/ nullptr);
506
507   if (not code) {
508     maestro->context_.reset(engine->get_context_factory()->create_context(ActorCode(), maestro));
509   } else {
510     maestro->context_.reset(engine->get_context_factory()->create_maestro(ActorCode(code), maestro));
511   }
512
513   maestro->simcall_.issuer_ = maestro;
514   engine->set_maestro(maestro);
515 }
516
517 } // namespace actor
518 } // namespace kernel
519 } // namespace simgrid
520
521 /* needs to be public and without simcall because it is called by exceptions and logging events */
522 const char* SIMIX_process_self_get_name() // XBT_ATTRIB_DEPRECATED_v333
523 {
524   return simgrid::s4u::Actor::is_maestro() ? "maestro" : simgrid::kernel::actor::ActorImpl::self()->get_cname();
525 }
526
527 /** @brief Returns the process from PID. */
528 smx_actor_t SIMIX_process_from_PID(aid_t pid) // XBT_ATTRIB_DEPRECATED_v331
529 {
530   return simgrid::kernel::actor::ActorImpl::by_pid(pid);
531 }
532
533 int SIMIX_is_maestro() // XBT_ATTRIB_DEPRECATED_v333
534 {
535   return simgrid::s4u::Actor::is_maestro();
536 }