Logo AND Algorithmique Numérique Distribuée

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