Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Update copyright lines.
[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/range/algorithm.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 ActorImpl* ActorImpl::by_PID(aid_t PID)
48 {
49   auto item = simix_global->process_list.find(PID);
50   if (item != simix_global->process_list.end())
51     return item->second;
52
53   // Search the trash
54   for (auto& a : simix_global->actors_to_destroy)
55     if (a.get_pid() == PID)
56       return &a;
57   return nullptr; // Not found, even in the trash
58 }
59
60 ActorImpl* ActorImpl::self()
61 {
62   const context::Context* self_context = context::Context::self();
63
64   return (self_context != nullptr) ? self_context->get_actor() : nullptr;
65 }
66
67 ActorImpl::ActorImpl(xbt::string name, s4u::Host* host) : host_(host), name_(std::move(name)), piface_(this)
68 {
69   pid_            = maxpid++;
70   simcall_.issuer_ = this;
71   stacksize_      = smx_context_stack_size;
72 }
73
74 ActorImpl::~ActorImpl()
75 {
76   if (simix_global != nullptr && this != simix_global->maestro_)
77     s4u::Actor::on_destruction(*get_ciface());
78 }
79
80 /* Become an actor in the simulation
81  *
82  * Currently this can only be called by the main thread (once) and only work with some thread factories
83  * (currently ThreadContextFactory).
84  *
85  * In the future, it might be extended in order to attach other threads created by a third party library.
86  */
87
88 ActorImplPtr ActorImpl::attach(const std::string& name, void* data, s4u::Host* host,
89                                const std::unordered_map<std::string, std::string>* properties)
90 {
91   // This is mostly a copy/paste from create(), it'd be nice to share some code between those two functions.
92
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->set_user_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->context_factory->attach(actor));
108
109   /* Add properties */
110   if (properties != nullptr)
111     actor->set_properties(*properties);
112
113   /* Add the actor to it's host actor list */
114   host->pimpl_->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   if (context == nullptr)
141     xbt_die("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_->pimpl_->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       // Remove first occurrence of &actor->simcall:
227       auto i = boost::range::find(waiting_synchro_->simcalls_, &simcall_);
228       if (i != waiting_synchro_->simcalls_.end())
229         waiting_synchro_->simcalls_.remove(&simcall_);
230     } else {
231       activity::ActivityImplPtr(waiting_synchro_)->finish();
232     }
233
234     activities_.remove(waiting_synchro_);
235     waiting_synchro_ = nullptr;
236   }
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_ = simix::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;
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
309     xbt_assert(exception_ == nullptr, "Gasp! This exception may be lost by subsequent calls.");
310
311     if (waiting_synchro_ != nullptr) // Not sure of when this will happen. Maybe when suspending early in the SR when a
312       waiting_synchro_->suspend();   // waiting_synchro was terminated
313
314     yield(); // Yield back to maestro without proceeding with my execution. I'll get rescheduled by resume()
315   }
316
317   if (exception_ != nullptr) {
318     XBT_DEBUG("Wait, maestro left me an exception");
319     std::exception_ptr exception = std::move(exception_);
320     exception_                   = nullptr;
321     std::rethrow_exception(std::move(exception));
322   }
323
324   if (SMPI_switch_data_segment && not finished_) {
325     SMPI_switch_data_segment(get_iface());
326   }
327 }
328
329 /** This actor will be terminated automatically when the last non-daemon actor finishes */
330 void ActorImpl::daemonize()
331 {
332   if (not daemon_) {
333     daemon_ = true;
334     simix_global->daemons.push_back(this);
335   }
336 }
337
338 void ActorImpl::undaemonize()
339 {
340   if (daemon_) {
341     auto& vect = simix_global->daemons;
342     auto it    = std::find(vect.begin(), vect.end(), this);
343     xbt_assert(it != vect.end(), "The dying daemon is not a daemon after all. Please report that bug.");
344     /* Don't move the whole content since we don't really care about the order */
345
346     std::swap(*it, vect.back());
347     vect.pop_back();
348     daemon_ = false;
349   }
350 }
351
352 s4u::Actor* ActorImpl::restart()
353 {
354   xbt_assert(this != simix_global->maestro_, "Restarting maestro is not supported");
355
356   XBT_DEBUG("Restarting actor %s on %s", get_cname(), host_->get_cname());
357
358   // retrieve the arguments of the old actor
359   ProcessArg arg = ProcessArg(host_, this);
360
361   // kill the old actor
362   context::Context::self()->get_actor()->kill(this);
363
364   // start the new actor
365   ActorImplPtr actor = ActorImpl::create(arg.name, arg.code, arg.data, arg.host, arg.properties.get(), nullptr);
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_->pimpl_->remove_actor(this);
464   host_ = dest;
465   dest->pimpl_->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_->pimpl_->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 std::unordered_map<std::string, std::string>* properties,
509                                const ActorImpl* parent_actor)
510 {
511   XBT_DEBUG("Start actor %s@'%s'", name.c_str(), host->get_cname());
512
513   ActorImplPtr actor;
514   if (parent_actor != nullptr)
515     actor = parent_actor->init(xbt::string(name), host);
516   else
517     actor = self()->init(xbt::string(name), host);
518
519   /* actor data */
520   actor->set_user_data(data);
521
522   /* Add properties */
523   if (properties != nullptr)
524     actor->set_properties(*properties);
525
526   actor->start(code);
527
528   return actor;
529 }
530
531 void create_maestro(const std::function<void()>& code)
532 {
533   /* Create maestro actor and initialize it */
534   auto* maestro = new ActorImpl(xbt::string(""), /*host*/ nullptr);
535
536   if (not code) {
537     maestro->context_.reset(simix_global->context_factory->create_context(ActorCode(), maestro));
538   } else {
539     maestro->context_.reset(simix_global->context_factory->create_maestro(ActorCode(code), maestro));
540   }
541
542   maestro->simcall_.issuer_     = maestro;
543   simix_global->maestro_        = maestro;
544 }
545
546 } // namespace actor
547 } // namespace kernel
548 } // namespace simgrid
549
550 int SIMIX_process_count() // XBT_ATTRIB_DEPRECATED_v329
551 {
552   return simix_global->process_list.size();
553 }
554
555 void* SIMIX_process_self_get_data() // XBT_ATTRIB_DEPRECATED_v329
556 {
557   smx_actor_t self = simgrid::kernel::actor::ActorImpl::self();
558
559   if (self == nullptr) {
560     return nullptr;
561   }
562   return self->get_user_data();
563 }
564
565 void SIMIX_process_self_set_data(void* data) // XBT_ATTRIB_DEPRECATED_v329
566 {
567   simgrid::kernel::actor::ActorImpl::self()->set_user_data(data);
568 }
569
570 /* needs to be public and without simcall because it is called
571    by exceptions and logging events */
572 const char* SIMIX_process_self_get_name()
573 {
574   return SIMIX_is_maestro() ? "maestro" : simgrid::kernel::actor::ActorImpl::self()->get_cname();
575 }
576
577 /** @brief Returns the process from PID. */
578 smx_actor_t SIMIX_process_from_PID(aid_t PID)
579 {
580   return simgrid::kernel::actor::ActorImpl::by_PID(PID);
581 }
582
583 void SIMIX_process_on_exit(smx_actor_t actor,
584                            const std::function<void(bool /*failed*/)>& fun) // XBT_ATTRIB_DEPRECATED_v329
585 {
586   xbt_assert(actor, "current process not found: are you in maestro context ?");
587   actor->on_exit->emplace_back(fun);
588 }
589
590 void simcall_process_set_data(smx_actor_t process, void* data) // XBT_ATTRIB_DEPRECATED_v329
591 {
592   simgrid::kernel::actor::simcall([process, data] { process->set_user_data(data); });
593 }