Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
remove smx_global.cpp
[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/s4u/Actor.hpp"
7 #include "mc/mc.h"
8 #include "simgrid/Exception.hpp"
9 #include "simgrid/s4u/Exec.hpp"
10 #include "src/kernel/EngineImpl.hpp"
11 #include "src/kernel/activity/CommImpl.hpp"
12 #include "src/kernel/activity/ExecImpl.hpp"
13 #include "src/kernel/activity/IoImpl.hpp"
14 #include "src/kernel/activity/SleepImpl.hpp"
15 #include "src/kernel/activity/SynchroRaw.hpp"
16 #include "src/mc/mc_replay.hpp"
17 #include "src/mc/remote/AppSide.hpp"
18 #if HAVE_SMPI
19 #include "src/smpi/include/private.hpp"
20 #endif
21 #include "src/surf/HostImpl.hpp"
22 #include "src/surf/cpu_interface.hpp"
23
24 #include <boost/core/demangle.hpp>
25 #include <typeinfo>
26 #include <utility>
27
28 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(simix_process, simix, "Logging specific to SIMIX (process)");
29
30 /**
31  * @brief Returns the current agent.
32  *
33  * This functions returns the currently running SIMIX process.
34  *
35  * @return The SIMIX process
36  */
37 smx_actor_t SIMIX_process_self()
38 {
39   return simgrid::kernel::actor::ActorImpl::self();
40 }
41
42 namespace simgrid {
43 namespace kernel {
44 namespace actor {
45
46 static unsigned long maxpid = 0;
47 unsigned long get_maxpid()
48 {
49   return maxpid;
50 }
51 unsigned long* get_maxpid_addr()
52 {
53   return &maxpid;
54 }
55 ActorImpl* ActorImpl::by_pid(aid_t pid)
56 {
57   return EngineImpl::get_instance()->get_actor_by_pid(pid);
58 }
59
60 ActorImpl* ActorImpl::self()
61 {
62   const context::Context* self_context = context::Context::self();
63
64   return (self_context != nullptr) ? self_context->get_actor() : nullptr;
65 }
66
67 ActorImpl::ActorImpl(xbt::string name, s4u::Host* host) : host_(host), name_(std::move(name)), piface_(this)
68 {
69   pid_            = maxpid++;
70   simcall_.issuer_ = this;
71   stacksize_      = smx_context_stack_size;
72 }
73
74 ActorImpl::~ActorImpl()
75 {
76   if (EngineImpl::has_instance() && not EngineImpl::get_instance()->is_maestro(this))
77     s4u::Actor::on_destruction(*get_ciface());
78 }
79
80 /* Become an actor in the simulation
81  *
82  * Currently this can only be called by the main thread (once) and only work with some thread factories
83  * (currently ThreadContextFactory).
84  *
85  * In the future, it might be extended in order to attach other threads created by a third party library.
86  */
87
88 ActorImplPtr ActorImpl::attach(const std::string& name, void* data, s4u::Host* host)
89 {
90   // This is mostly a copy/paste from create(), it'd be nice to share some code between those two functions.
91   auto* engine = EngineImpl::get_instance();
92   XBT_DEBUG("Attach actor %s on host '%s'", name.c_str(), host->get_cname());
93
94   if (not host->is_on()) {
95     XBT_WARN("Cannot attach actor '%s' on failed host '%s'", name.c_str(), host->get_cname());
96     throw HostFailureException(XBT_THROW_POINT, "Cannot attach actor on failed host.");
97   }
98
99   auto* actor = new ActorImpl(xbt::string(name), host);
100   /* Actor data */
101   actor->piface_.set_data(data);
102   actor->code_ = nullptr;
103
104   XBT_VERB("Create context %s", actor->get_cname());
105   actor->context_.reset(engine->get_context_factory()->attach(actor));
106
107   /* Add the actor to it's host actor list */
108   host->get_impl()->add_actor(actor);
109
110   /* Now insert it in the global actor list and in the actors to run list */
111   engine->add_actor(actor->get_pid(), actor);
112   engine->add_actor_to_run_list_no_check(actor);
113   intrusive_ptr_add_ref(actor);
114
115   auto* context = dynamic_cast<context::AttachContext*>(actor->context_.get());
116   xbt_assert(nullptr != context, "Not a suitable context");
117   context->attach_start();
118
119   /* The on_creation() signal must be delayed until there, where the pid and everything is set */
120   s4u::Actor::on_creation(*actor->get_ciface());
121
122   return ActorImplPtr(actor);
123 }
124 /** @brief Detach an actor attached with `attach()`
125  *
126  *  This is called when the current actor has finished its job.
127  *  Used in the main thread, it waits for the simulation to finish before returning. When it returns, the other
128  *  simulated actors and the maestro are destroyed.
129  */
130 void ActorImpl::detach()
131 {
132   auto* context = dynamic_cast<context::AttachContext*>(context::Context::self());
133   xbt_assert(context != nullptr, "Not a suitable context");
134
135   context->get_actor()->cleanup();
136   context->attach_stop();
137 }
138
139 void ActorImpl::cleanup_from_simix()
140 {
141   auto* engine = EngineImpl::get_instance();
142   const std::lock_guard<std::mutex> lock(engine->get_mutex());
143   engine->remove_actor(pid_);
144   if (host_ && host_actor_list_hook.is_linked())
145     host_->get_impl()->remove_actor(this);
146   if (not kernel_destroy_list_hook.is_linked()) {
147 #if SIMGRID_HAVE_MC
148     engine->add_dead_actor_to_dynar(this);
149 #endif
150     engine->add_actor_to_destroy_list(*this);
151   }
152 }
153
154 void ActorImpl::cleanup()
155 {
156   finished_ = true;
157
158   if (has_to_auto_restart() && not get_host()->is_on()) {
159     XBT_DEBUG("Insert host %s to watched_hosts because it's off and %s needs to restart", get_host()->get_cname(),
160               get_cname());
161     watched_hosts().insert(get_host()->get_name());
162   }
163
164   if (on_exit) {
165     // Execute the termination callbacks
166     bool failed = context_->wannadie();
167     for (auto exit_fun = on_exit->crbegin(); exit_fun != on_exit->crend(); ++exit_fun)
168       (*exit_fun)(failed);
169     on_exit.reset();
170   }
171   undaemonize();
172
173   /* cancel non-blocking activities */
174   for (auto activity : activities_)
175     activity->cancel();
176   activities_.clear();
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([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 (waiting_synchro_ != nullptr) {
210     waiting_synchro_->cancel();
211     waiting_synchro_->state_ = activity::State::FAILED;
212
213     activity::ExecImplPtr exec = boost::dynamic_pointer_cast<activity::ExecImpl>(waiting_synchro_);
214     activity::CommImplPtr comm = boost::dynamic_pointer_cast<activity::CommImpl>(waiting_synchro_);
215
216     if (exec != nullptr) {
217       exec->clean_action();
218     } else if (comm != nullptr) {
219       comm->unregister_simcall(&simcall_);
220     } else {
221       activity::ActivityImplPtr(waiting_synchro_)->finish();
222     }
223
224     activities_.remove(waiting_synchro_);
225     waiting_synchro_ = nullptr;
226   }
227   for (auto const& activity : activities_)
228     activity->cancel();
229   activities_.clear();
230
231   // Forcefully kill the actor if its host is turned off. Not a HostFailureException because you should not survive that
232   this->throw_exception(std::make_exception_ptr(ForcefulKillException(host_->is_on() ? "exited" : "host failed")));
233 }
234
235 void ActorImpl::kill(ActorImpl* actor) const
236 {
237   auto* engine = EngineImpl::get_instance();
238   xbt_assert(not engine->is_maestro(actor), "Killing maestro is a rather bad idea");
239   if (actor->finished_) {
240     XBT_DEBUG("Ignoring request to kill actor %s@%s that is already dead", actor->get_cname(),
241               actor->host_->get_cname());
242     return;
243   }
244
245   XBT_DEBUG("Actor '%s'@%s is killing actor '%s'@%s", get_cname(), host_ ? host_->get_cname() : "", actor->get_cname(),
246             actor->host_ ? actor->host_->get_cname() : "");
247
248   actor->exit();
249
250   if (actor == this) {
251     XBT_DEBUG("Go on, this is a suicide,");
252   } else
253     engine->add_actor_to_run_list(actor);
254 }
255
256 void ActorImpl::kill_all() const
257 {
258   for (auto const& kv : EngineImpl::get_instance()->get_actor_list())
259     if (kv.second != this)
260       this->kill(kv.second);
261 }
262
263 void ActorImpl::set_kill_time(double kill_time)
264 {
265   if (kill_time <= s4u::Engine::get_clock())
266     return;
267   XBT_DEBUG("Set kill time %f for actor %s@%s", kill_time, get_cname(), host_->get_cname());
268   kill_timer_ = timer::Timer::set(kill_time, [this] {
269     this->exit();
270     kill_timer_ = nullptr;
271   });
272 }
273
274 double ActorImpl::get_kill_time() const
275 {
276   return kill_timer_ ? kill_timer_->get_date() : 0.0;
277 }
278
279 void ActorImpl::yield()
280 {
281   XBT_DEBUG("Yield actor '%s'", get_cname());
282
283   /* Go into sleep and return control to maestro */
284   context_->suspend();
285
286   /* Ok, maestro returned control to us */
287   XBT_DEBUG("Control returned to me: '%s'", get_cname());
288
289   if (context_->wannadie()) {
290     XBT_DEBUG("Actor %s@%s is dead", get_cname(), host_->get_cname());
291     context_->stop();
292     THROW_IMPOSSIBLE;
293   }
294
295   if (suspended_) {
296     XBT_DEBUG("Hey! I'm suspended.");
297     xbt_assert(exception_ == nullptr, "Gasp! This exception may be lost by subsequent calls.");
298     yield(); // Yield back to maestro without proceeding with my execution. I'll get rescheduled by resume()
299   }
300
301   if (exception_ != nullptr) {
302     XBT_DEBUG("Wait, maestro left me an exception");
303     std::exception_ptr exception = std::move(exception_);
304     exception_                   = nullptr;
305     try {
306       std::rethrow_exception(std::move(exception));
307     } catch (const simgrid::Exception& e) {
308       e.rethrow_nested(XBT_THROW_POINT, boost::core::demangle(typeid(e).name()) + " raised in kernel mode.");
309     }
310   }
311
312 #if HAVE_SMPI
313   if (not finished_)
314     smpi_switch_data_segment(get_iface());
315 #endif
316 }
317
318 /** This actor will be terminated automatically when the last non-daemon actor finishes */
319 void ActorImpl::daemonize()
320 {
321   if (not daemon_) {
322     daemon_ = true;
323     EngineImpl::get_instance()->add_daemon(this);
324   }
325 }
326
327 void ActorImpl::undaemonize()
328 {
329   if (daemon_) {
330     daemon_ = false;
331     EngineImpl::get_instance()->remove_daemon(this);
332   }
333 }
334
335 s4u::Actor* ActorImpl::restart()
336 {
337   xbt_assert(not EngineImpl::get_instance()->is_maestro(this), "Restarting maestro is not supported");
338
339   XBT_DEBUG("Restarting actor %s on %s", get_cname(), host_->get_cname());
340
341   // retrieve the arguments of the old actor
342   ProcessArg arg(host_, this);
343
344   // kill the old actor
345   context::Context::self()->get_actor()->kill(this);
346
347   // start the new actor
348   ActorImplPtr actor = ActorImpl::create(arg.name, arg.code, arg.data, arg.host, nullptr);
349   actor->set_properties(arg.properties);
350   *actor->on_exit = std::move(*arg.on_exit);
351   actor->set_kill_time(arg.kill_time);
352   actor->set_auto_restart(arg.auto_restart);
353
354   return actor->get_ciface();
355 }
356
357 void ActorImpl::suspend()
358 {
359   if (suspended_) {
360     XBT_DEBUG("Actor '%s' is already suspended", get_cname());
361     return;
362   }
363
364   suspended_ = true;
365
366   /* Suspend the activities associated with this actor. */
367   for (auto const& activity : activities_)
368     activity->suspend();
369 }
370
371 void ActorImpl::resume()
372 {
373   XBT_IN("actor = %p", this);
374
375   if (context_->wannadie()) {
376     XBT_VERB("Ignoring request to suspend an actor that is currently dying.");
377     return;
378   }
379
380   if (not suspended_)
381     return;
382   suspended_ = false;
383
384   /* resume the activities that were blocked when suspending the actor. */
385   for (auto const& activity : activities_)
386     activity->resume();
387   if (not waiting_synchro_) // Reschedule the actor if it was forcefully unscheduled in yield()
388     EngineImpl::get_instance()->add_actor_to_run_list_no_check(this);
389
390   XBT_OUT();
391 }
392
393 activity::ActivityImplPtr ActorImpl::join(const ActorImpl* actor, double timeout)
394 {
395   activity::ActivityImplPtr sleep = this->sleep(timeout);
396   actor->on_exit->emplace_back([sleep](bool) {
397     if (sleep->surf_action_)
398       sleep->surf_action_->finish(resource::Action::State::FINISHED);
399   });
400   return sleep;
401 }
402
403 activity::ActivityImplPtr ActorImpl::sleep(double duration)
404 {
405   if (not host_->is_on())
406     throw_exception(std::make_exception_ptr(HostFailureException(
407         XBT_THROW_POINT, std::string("Host ") + host_->get_cname() + " failed, you cannot sleep there.")));
408
409   auto sleep = new activity::SleepImpl();
410   sleep->set_name("sleep").set_host(host_).set_duration(duration).start();
411   return activity::SleepImplPtr(sleep);
412 }
413
414 void ActorImpl::throw_exception(std::exception_ptr e)
415 {
416   exception_ = e;
417
418   if (suspended_)
419     resume();
420
421   /* cancel the blocking synchro if any */
422   if (waiting_synchro_) {
423     waiting_synchro_->cancel();
424     activities_.remove(waiting_synchro_);
425     waiting_synchro_ = nullptr;
426   }
427 }
428
429 void ActorImpl::simcall_answer()
430 {
431   auto* engine = EngineImpl::get_instance();
432   if (not engine->is_maestro(this)) {
433     XBT_DEBUG("Answer simcall %s issued by %s (%p)", SIMIX_simcall_name(simcall_), get_cname(), this);
434     xbt_assert(simcall_.call_ != simix::Simcall::NONE);
435     simcall_.call_ = simix::Simcall::NONE;
436     const auto& actors_to_run = engine->get_actors_to_run();
437     xbt_assert(not XBT_LOG_ISENABLED(simix_process, xbt_log_priority_debug) ||
438                    std::find(begin(actors_to_run), end(actors_to_run), this) == end(actors_to_run),
439                "Actor %p should not exist in actors_to_run!", this);
440     engine->add_actor_to_run_list_no_check(this);
441   }
442 }
443
444 void ActorImpl::set_host(s4u::Host* dest)
445 {
446   host_->get_impl()->remove_actor(this);
447   host_ = dest;
448   dest->get_impl()->add_actor(this);
449 }
450
451 ActorImplPtr ActorImpl::init(const std::string& name, s4u::Host* host) const
452 {
453   auto* actor = new ActorImpl(xbt::string(name), host);
454   actor->set_ppid(this->pid_);
455
456   intrusive_ptr_add_ref(actor);
457   /* The on_creation() signal must be delayed until there, where the pid and everything is set */
458   s4u::Actor::on_creation(*actor->get_ciface());
459
460   return ActorImplPtr(actor);
461 }
462
463 ActorImpl* ActorImpl::start(const ActorCode& code)
464 {
465   xbt_assert(code && host_ != nullptr, "Invalid parameters");
466   auto* engine = EngineImpl::get_instance();
467
468   if (not host_->is_on()) {
469     XBT_WARN("Cannot launch actor '%s' on failed host '%s'", name_.c_str(), host_->get_cname());
470     intrusive_ptr_release(this);
471     throw HostFailureException(XBT_THROW_POINT, "Cannot start actor on failed host.");
472   }
473
474   this->code_ = code;
475   XBT_VERB("Create context %s", get_cname());
476   context_.reset(engine->get_context_factory()->create_context(ActorCode(code), this));
477
478   XBT_DEBUG("Start context '%s'", get_cname());
479
480   /* Add the actor to its host's actor list */
481   host_->get_impl()->add_actor(this);
482   engine->add_actor(pid_, this);
483
484   /* Now insert it in the global actor list and in the actor to run list */
485   engine->add_actor_to_run_list_no_check(this);
486
487   return this;
488 }
489
490 ActorImplPtr ActorImpl::create(const std::string& name, const ActorCode& code, void* data, s4u::Host* host,
491                                const ActorImpl* parent_actor)
492 {
493   XBT_DEBUG("Start actor %s@'%s'", name.c_str(), host->get_cname());
494
495   ActorImplPtr actor;
496   if (parent_actor != nullptr)
497     actor = parent_actor->init(xbt::string(name), host);
498   else
499     actor = self()->init(xbt::string(name), host);
500
501   /* actor data */
502   actor->piface_.set_data(data);
503
504   actor->start(code);
505
506   return actor;
507 }
508
509 void create_maestro(const std::function<void()>& code)
510 {
511   auto* engine = EngineImpl::get_instance();
512   /* Create maestro actor and initialize it */
513   auto* maestro = new ActorImpl(xbt::string(""), /*host*/ nullptr);
514
515   if (not code) {
516     maestro->context_.reset(engine->get_context_factory()->create_context(ActorCode(), maestro));
517   } else {
518     maestro->context_.reset(engine->get_context_factory()->create_maestro(ActorCode(code), maestro));
519   }
520
521   maestro->simcall_.issuer_ = maestro;
522   engine->set_maestro(maestro);
523 }
524
525 } // namespace actor
526 } // namespace kernel
527 } // namespace simgrid
528
529 /* needs to be public and without simcall because it is called by exceptions and logging events */
530 const char* SIMIX_process_self_get_name()
531 {
532   return SIMIX_is_maestro() ? "maestro" : simgrid::kernel::actor::ActorImpl::self()->get_cname();
533 }
534
535 /** @brief Returns the process from PID. */
536 smx_actor_t SIMIX_process_from_PID(aid_t pid) // XBT_ATTRIB_DEPRECATD_v331
537 {
538   return simgrid::kernel::actor::ActorImpl::by_pid(pid);
539 }
540
541 int SIMIX_is_maestro()
542 {
543   const auto* self = simgrid::kernel::actor::ActorImpl::self();
544   return self == nullptr || simgrid::kernel::EngineImpl::get_instance()->is_maestro(self);
545 }