Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Suspend all the associated activities on actor suspend.
[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/activity/CommImpl.hpp"
11 #include "src/kernel/activity/ExecImpl.hpp"
12 #include "src/kernel/activity/IoImpl.hpp"
13 #include "src/kernel/activity/SleepImpl.hpp"
14 #include "src/kernel/activity/SynchroRaw.hpp"
15 #include "src/mc/mc_replay.hpp"
16 #include "src/mc/remote/AppSide.hpp"
17 #include "src/simix/smx_private.hpp"
18 #include "src/surf/HostImpl.hpp"
19 #include "src/surf/cpu_interface.hpp"
20
21 #include <boost/core/demangle.hpp>
22 #include <typeinfo>
23 #include <utility>
24
25 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(simix_process, simix, "Logging specific to SIMIX (process)");
26
27 /**
28  * @brief Returns the current agent.
29  *
30  * This functions returns the currently running SIMIX process.
31  *
32  * @return The SIMIX process
33  */
34 smx_actor_t SIMIX_process_self()
35 {
36   return simgrid::kernel::actor::ActorImpl::self();
37 }
38
39 namespace simgrid {
40 namespace kernel {
41 namespace actor {
42
43 static unsigned long maxpid = 0;
44 unsigned long get_maxpid()
45 {
46   return maxpid;
47 }
48 unsigned long* get_maxpid_addr()
49 {
50   return &maxpid;
51 }
52 ActorImpl* ActorImpl::by_pid(aid_t pid)
53 {
54   auto item = simix_global->process_list.find(pid);
55   if (item != simix_global->process_list.end())
56     return item->second;
57
58   // Search the trash
59   for (auto& a : simix_global->actors_to_destroy)
60     if (a.get_pid() == pid)
61       return &a;
62   return nullptr; // Not found, even in the trash
63 }
64
65 ActorImpl* ActorImpl::self()
66 {
67   const context::Context* self_context = context::Context::self();
68
69   return (self_context != nullptr) ? self_context->get_actor() : nullptr;
70 }
71
72 ActorImpl::ActorImpl(xbt::string name, s4u::Host* host) : host_(host), name_(std::move(name)), piface_(this)
73 {
74   pid_            = maxpid++;
75   simcall_.issuer_ = this;
76   stacksize_      = smx_context_stack_size;
77 }
78
79 ActorImpl::~ActorImpl()
80 {
81   if (simix_global != nullptr && this != simix_global->maestro_)
82     s4u::Actor::on_destruction(*get_ciface());
83 }
84
85 /* Become an actor in the simulation
86  *
87  * Currently this can only be called by the main thread (once) and only work with some thread factories
88  * (currently ThreadContextFactory).
89  *
90  * In the future, it might be extended in order to attach other threads created by a third party library.
91  */
92
93 ActorImplPtr ActorImpl::attach(const std::string& name, void* data, s4u::Host* host)
94 {
95   // This is mostly a copy/paste from create(), it'd be nice to share some code between those two functions.
96
97   XBT_DEBUG("Attach actor %s on host '%s'", name.c_str(), host->get_cname());
98
99   if (not host->is_on()) {
100     XBT_WARN("Cannot attach actor '%s' on failed host '%s'", name.c_str(), host->get_cname());
101     throw HostFailureException(XBT_THROW_POINT, "Cannot attach actor on failed host.");
102   }
103
104   auto* actor = new ActorImpl(xbt::string(name), host);
105   /* Actor data */
106   actor->set_user_data(data);
107   actor->code_ = nullptr;
108
109   XBT_VERB("Create context %s", actor->get_cname());
110   xbt_assert(simix_global != nullptr, "simix is not initialized, please call MSG_init first");
111   actor->context_.reset(simix_global->context_factory->attach(actor));
112
113   /* Add the actor to it's host actor list */
114   host->get_impl()->add_actor(actor);
115
116   /* Now insert it in the global actor list and in the actors to run list */
117   simix_global->process_list[actor->get_pid()] = actor;
118   XBT_DEBUG("Inserting [%p] %s(%s) in the to_run list", actor, actor->get_cname(), host->get_cname());
119   simix_global->actors_to_run.push_back(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
234   // Forcefully kill the actor if its host is turned off. Not a HostFailureException because you should not survive that
235   this->throw_exception(std::make_exception_ptr(ForcefulKillException(host_->is_on() ? "exited" : "host failed")));
236 }
237
238 void ActorImpl::kill(ActorImpl* actor) const
239 {
240   xbt_assert(actor != simix_global->maestro_, "Killing maestro is a rather bad idea");
241   if (actor->finished_) {
242     XBT_DEBUG("Ignoring request to kill actor %s@%s that is already dead", actor->get_cname(),
243               actor->host_->get_cname());
244     return;
245   }
246
247   XBT_DEBUG("Actor '%s'@%s is killing actor '%s'@%s", get_cname(), host_ ? host_->get_cname() : "", actor->get_cname(),
248             actor->host_ ? actor->host_->get_cname() : "");
249
250   actor->exit();
251
252   if (actor == this) {
253     XBT_DEBUG("Go on, this is a suicide,");
254   } else if (std::find(begin(simix_global->actors_to_run), end(simix_global->actors_to_run), actor) !=
255              end(simix_global->actors_to_run)) {
256     XBT_DEBUG("Actor %s is already in the to_run list", actor->get_cname());
257   } else {
258     XBT_DEBUG("Inserting %s in the to_run list", actor->get_cname());
259     simix_global->actors_to_run.push_back(actor);
260   }
261 }
262
263 void ActorImpl::kill_all() const
264 {
265   for (auto const& kv : simix_global->process_list)
266     if (kv.second != this)
267       this->kill(kv.second);
268 }
269
270 void ActorImpl::set_kill_time(double kill_time)
271 {
272   if (kill_time <= SIMIX_get_clock())
273     return;
274   XBT_DEBUG("Set kill time %f for actor %s@%s", kill_time, get_cname(), host_->get_cname());
275   kill_timer_ = simix::Timer::set(kill_time, [this] {
276     this->exit();
277     kill_timer_ = nullptr;
278   });
279 }
280
281 double ActorImpl::get_kill_time() const
282 {
283   return kill_timer_ ? kill_timer_->date : 0.0;
284 }
285
286 void ActorImpl::yield()
287 {
288   XBT_DEBUG("Yield actor '%s'", get_cname());
289
290   /* Go into sleep and return control to maestro */
291   context_->suspend();
292
293   /* Ok, maestro returned control to us */
294   XBT_DEBUG("Control returned to me: '%s'", get_cname());
295
296   if (context_->wannadie()) {
297     XBT_DEBUG("Actor %s@%s is dead", get_cname(), host_->get_cname());
298     context_->stop();
299     THROW_IMPOSSIBLE;
300   }
301
302   if (suspended_) {
303     XBT_DEBUG("Hey! I'm suspended.");
304     xbt_assert(exception_ == nullptr, "Gasp! This exception may be lost by subsequent calls.");
305     yield(); // Yield back to maestro without proceeding with my execution. I'll get rescheduled by resume()
306   }
307
308   if (exception_ != nullptr) {
309     XBT_DEBUG("Wait, maestro left me an exception");
310     std::exception_ptr exception = std::move(exception_);
311     exception_                   = nullptr;
312     try {
313       std::rethrow_exception(std::move(exception));
314     } catch (const simgrid::Exception& e) {
315       e.rethrow_nested(XBT_THROW_POINT, boost::core::demangle(typeid(e).name()) + " raised in kernel mode.");
316     }
317   }
318
319   if (SMPI_switch_data_segment && not finished_) {
320     SMPI_switch_data_segment(get_iface());
321   }
322 }
323
324 /** This actor will be terminated automatically when the last non-daemon actor finishes */
325 void ActorImpl::daemonize()
326 {
327   if (not daemon_) {
328     daemon_ = true;
329     simix_global->daemons.push_back(this);
330   }
331 }
332
333 void ActorImpl::undaemonize()
334 {
335   if (daemon_) {
336     auto& vect = simix_global->daemons;
337     auto it    = std::find(vect.begin(), vect.end(), this);
338     xbt_assert(it != vect.end(), "The dying daemon is not a daemon after all. Please report that bug.");
339     /* Don't move the whole content since we don't really care about the order */
340
341     std::swap(*it, vect.back());
342     vect.pop_back();
343     daemon_ = false;
344   }
345 }
346
347 s4u::Actor* ActorImpl::restart()
348 {
349   xbt_assert(this != simix_global->maestro_, "Restarting maestro is not supported");
350
351   XBT_DEBUG("Restarting actor %s on %s", get_cname(), host_->get_cname());
352
353   // retrieve the arguments of the old actor
354   ProcessArg arg(host_, this);
355
356   // kill the old actor
357   context::Context::self()->get_actor()->kill(this);
358
359   // start the new actor
360   ActorImplPtr actor = ActorImpl::create(arg.name, arg.code, arg.data, arg.host, nullptr);
361   actor->set_properties(arg.properties);
362   *actor->on_exit = std::move(*arg.on_exit);
363   actor->set_kill_time(arg.kill_time);
364   actor->set_auto_restart(arg.auto_restart);
365
366   return actor->get_ciface();
367 }
368
369 void ActorImpl::suspend()
370 {
371   if (suspended_) {
372     XBT_DEBUG("Actor '%s' is already suspended", get_cname());
373     return;
374   }
375
376   suspended_ = true;
377
378   /* Suspend the activities associated with this actor. */
379   for (auto& activity : activities_)
380     activity->suspend();
381 }
382
383 void ActorImpl::resume()
384 {
385   XBT_IN("actor = %p", this);
386
387   if (context_->wannadie()) {
388     XBT_VERB("Ignoring request to suspend an actor that is currently dying.");
389     return;
390   }
391
392   if (not suspended_)
393     return;
394   suspended_ = false;
395
396   /* resume the activities that were blocked when suspending the actor. */
397   for (auto& activity : activities_)
398     activity->resume();
399   if (not waiting_synchro_) // Reschedule the actor if it was forcefully unscheduled in yield()
400     simix_global->actors_to_run.push_back(this);
401
402   XBT_OUT();
403 }
404
405 activity::ActivityImplPtr ActorImpl::join(const ActorImpl* actor, double timeout)
406 {
407   activity::ActivityImplPtr sleep = this->sleep(timeout);
408   actor->on_exit->emplace_back([sleep](bool) {
409     if (sleep->surf_action_)
410       sleep->surf_action_->finish(resource::Action::State::FINISHED);
411   });
412   return sleep;
413 }
414
415 activity::ActivityImplPtr ActorImpl::sleep(double duration)
416 {
417   if (not host_->is_on())
418     throw_exception(std::make_exception_ptr(HostFailureException(
419         XBT_THROW_POINT, std::string("Host ") + host_->get_cname() + " failed, you cannot sleep there.")));
420
421   auto sleep = new activity::SleepImpl();
422   sleep->set_name("sleep").set_host(host_).set_duration(duration).start();
423   return activity::SleepImplPtr(sleep);
424 }
425
426 void ActorImpl::throw_exception(std::exception_ptr e)
427 {
428   exception_ = e;
429
430   if (suspended_)
431     resume();
432
433   /* cancel the blocking synchro if any */
434   if (waiting_synchro_) {
435     waiting_synchro_->cancel();
436     activities_.remove(waiting_synchro_);
437     waiting_synchro_ = nullptr;
438   }
439 }
440
441 void ActorImpl::simcall_answer()
442 {
443   if (this != simix_global->maestro_) {
444     XBT_DEBUG("Answer simcall %s issued by %s (%p)", SIMIX_simcall_name(simcall_), get_cname(), this);
445     xbt_assert(simcall_.call_ != simix::Simcall::NONE);
446     simcall_.call_ = simix::Simcall::NONE;
447     xbt_assert(not XBT_LOG_ISENABLED(simix_process, xbt_log_priority_debug) ||
448                    std::find(begin(simix_global->actors_to_run), end(simix_global->actors_to_run), this) ==
449                        end(simix_global->actors_to_run),
450                "Actor %p should not exist in actors_to_run!", this);
451     simix_global->actors_to_run.push_back(this);
452   }
453 }
454
455 void ActorImpl::set_host(s4u::Host* dest)
456 {
457   host_->get_impl()->remove_actor(this);
458   host_ = dest;
459   dest->get_impl()->add_actor(this);
460 }
461
462 ActorImplPtr ActorImpl::init(const std::string& name, s4u::Host* host) const
463 {
464   auto* actor = new ActorImpl(xbt::string(name), host);
465   actor->set_ppid(this->pid_);
466
467   intrusive_ptr_add_ref(actor);
468   /* The on_creation() signal must be delayed until there, where the pid and everything is set */
469   s4u::Actor::on_creation(*actor->get_ciface());
470
471   return ActorImplPtr(actor);
472 }
473
474 ActorImpl* ActorImpl::start(const ActorCode& code)
475 {
476   xbt_assert(code && host_ != nullptr, "Invalid parameters");
477
478   if (not host_->is_on()) {
479     XBT_WARN("Cannot launch actor '%s' on failed host '%s'", name_.c_str(), host_->get_cname());
480     intrusive_ptr_release(this);
481     throw HostFailureException(XBT_THROW_POINT, "Cannot start actor on failed host.");
482   }
483
484   this->code_ = code;
485   XBT_VERB("Create context %s", get_cname());
486   context_.reset(simix_global->context_factory->create_context(ActorCode(code), this));
487
488   XBT_DEBUG("Start context '%s'", get_cname());
489
490   /* Add the actor to its host's actor list */
491   host_->get_impl()->add_actor(this);
492   simix_global->process_list[pid_] = this;
493
494   /* Now insert it in the global actor list and in the actor to run list */
495   XBT_DEBUG("Inserting [%p] %s(%s) in the to_run list", this, get_cname(), host_->get_cname());
496   simix_global->actors_to_run.push_back(this);
497
498   return this;
499 }
500
501 ActorImplPtr ActorImpl::create(const std::string& name, const ActorCode& code, void* data, s4u::Host* host,
502                                const ActorImpl* parent_actor)
503 {
504   XBT_DEBUG("Start actor %s@'%s'", name.c_str(), host->get_cname());
505
506   ActorImplPtr actor;
507   if (parent_actor != nullptr)
508     actor = parent_actor->init(xbt::string(name), host);
509   else
510     actor = self()->init(xbt::string(name), host);
511
512   /* actor data */
513   actor->set_user_data(data);
514
515   actor->start(code);
516
517   return actor;
518 }
519
520 void create_maestro(const std::function<void()>& code)
521 {
522   /* Create maestro actor and initialize it */
523   auto* maestro = new ActorImpl(xbt::string(""), /*host*/ nullptr);
524
525   if (not code) {
526     maestro->context_.reset(simix_global->context_factory->create_context(ActorCode(), maestro));
527   } else {
528     maestro->context_.reset(simix_global->context_factory->create_maestro(ActorCode(code), maestro));
529   }
530
531   maestro->simcall_.issuer_     = maestro;
532   simix_global->maestro_        = maestro;
533 }
534
535 } // namespace actor
536 } // namespace kernel
537 } // namespace simgrid
538
539 int SIMIX_process_count() // XBT_ATTRIB_DEPRECATED_v329
540 {
541   return simix_global->process_list.size();
542 }
543
544 void* SIMIX_process_self_get_data() // XBT_ATTRIB_DEPRECATED_v329
545 {
546   smx_actor_t self = simgrid::kernel::actor::ActorImpl::self();
547
548   if (self == nullptr) {
549     return nullptr;
550   }
551   return self->get_user_data();
552 }
553
554 void SIMIX_process_self_set_data(void* data) // XBT_ATTRIB_DEPRECATED_v329
555 {
556   simgrid::kernel::actor::ActorImpl::self()->set_user_data(data);
557 }
558
559 /* needs to be public and without simcall because it is called
560    by exceptions and logging events */
561 const char* SIMIX_process_self_get_name()
562 {
563   return SIMIX_is_maestro() ? "maestro" : simgrid::kernel::actor::ActorImpl::self()->get_cname();
564 }
565
566 /** @brief Returns the process from PID. */
567 smx_actor_t SIMIX_process_from_PID(aid_t pid)
568 {
569   return simgrid::kernel::actor::ActorImpl::by_pid(pid);
570 }
571
572 void SIMIX_process_on_exit(smx_actor_t actor,
573                            const std::function<void(bool /*failed*/)>& fun) // XBT_ATTRIB_DEPRECATED_v329
574 {
575   xbt_assert(actor, "current process not found: are you in maestro context ?");
576   actor->on_exit->emplace_back(fun);
577 }
578
579 void simcall_process_set_data(smx_actor_t process, void* data) // XBT_ATTRIB_DEPRECATED_v329
580 {
581   simgrid::kernel::actor::simcall([process, data] { process->set_user_data(data); });
582 }