Logo AND Algorithmique Numérique Distribuée

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