Logo AND Algorithmique Numérique Distribuée

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