Logo AND Algorithmique Numérique Distribuée

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