Logo AND Algorithmique Numérique Distribuée

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