Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Factor un-registration of simcall.
[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 void* 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                                const std::unordered_map<std::string, std::string>* properties)
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 properties */
114   if (properties != nullptr)
115     actor->set_properties(*properties);
116
117   /* Add the actor to it's host actor list */
118   host->pimpl_->add_actor(actor);
119
120   /* Now insert it in the global actor list and in the actors to run list */
121   simix_global->process_list[actor->get_pid()] = actor;
122   XBT_DEBUG("Inserting [%p] %s(%s) in the to_run list", actor, actor->get_cname(), host->get_cname());
123   simix_global->actors_to_run.push_back(actor);
124   intrusive_ptr_add_ref(actor);
125
126   auto* context = dynamic_cast<context::AttachContext*>(actor->context_.get());
127   xbt_assert(nullptr != context, "Not a suitable context");
128   context->attach_start();
129
130   /* The on_creation() signal must be delayed until there, where the pid and everything is set */
131   s4u::Actor::on_creation(*actor->get_ciface());
132
133   return ActorImplPtr(actor);
134 }
135 /** @brief Detach an actor attached with `attach()`
136  *
137  *  This is called when the current actor has finished its job.
138  *  Used in the main thread, it waits for the simulation to finish before returning. When it returns, the other
139  *  simulated actors and the maestro are destroyed.
140  */
141 void ActorImpl::detach()
142 {
143   auto* context = dynamic_cast<context::AttachContext*>(context::Context::self());
144   xbt_assert(context != nullptr, "Not a suitable context");
145
146   context->get_actor()->cleanup();
147   context->attach_stop();
148 }
149
150 void ActorImpl::cleanup_from_simix()
151 {
152   const std::lock_guard<std::mutex> lock(simix_global->mutex);
153   simix_global->process_list.erase(pid_);
154   if (host_ && host_actor_list_hook.is_linked())
155     host_->pimpl_->remove_actor(this);
156   if (not smx_destroy_list_hook.is_linked()) {
157 #if SIMGRID_HAVE_MC
158     xbt_dynar_push_as(simix_global->dead_actors_vector, ActorImpl*, this);
159 #endif
160     simix_global->actors_to_destroy.push_back(*this);
161   }
162 }
163
164 void ActorImpl::cleanup()
165 {
166   finished_ = true;
167
168   if (has_to_auto_restart() && not get_host()->is_on()) {
169     XBT_DEBUG("Insert host %s to watched_hosts because it's off and %s needs to restart", get_host()->get_cname(),
170               get_cname());
171     watched_hosts().insert(get_host()->get_name());
172   }
173
174   if (on_exit) {
175     // Execute the termination callbacks
176     bool failed = context_->wannadie();
177     for (auto exit_fun = on_exit->crbegin(); exit_fun != on_exit->crend(); ++exit_fun)
178       (*exit_fun)(failed);
179     on_exit.reset();
180   }
181   undaemonize();
182
183   /* cancel non-blocking activities */
184   for (auto activity : activities_)
185     activity->cancel();
186   activities_.clear();
187
188   XBT_DEBUG("%s@%s(%ld) should not run anymore", get_cname(), get_host()->get_cname(), get_pid());
189
190   if (this == simix_global->maestro_) /* Do not cleanup maestro */
191     return;
192
193   XBT_DEBUG("Cleanup actor %s (%p), waiting synchro %p", get_cname(), this, waiting_synchro_.get());
194
195   /* Unregister associated timers if any */
196   if (kill_timer_ != nullptr) {
197     kill_timer_->remove();
198     kill_timer_ = nullptr;
199   }
200   if (simcall_.timeout_cb_) {
201     simcall_.timeout_cb_->remove();
202     simcall_.timeout_cb_ = nullptr;
203   }
204
205   cleanup_from_simix();
206
207   context_->set_wannadie(false); // don't let the simcall's yield() do a Context::stop(), to avoid infinite loops
208   actor::simcall([this] { s4u::Actor::on_termination(*get_ciface()); });
209   context_->set_wannadie();
210 }
211
212 void ActorImpl::exit()
213 {
214   context_->set_wannadie();
215   suspended_          = false;
216   exception_          = nullptr;
217
218   /* destroy the blocking synchro if any */
219   if (waiting_synchro_ != nullptr) {
220     waiting_synchro_->cancel();
221     waiting_synchro_->state_ = activity::State::FAILED;
222
223     activity::ExecImplPtr exec = boost::dynamic_pointer_cast<activity::ExecImpl>(waiting_synchro_);
224     activity::CommImplPtr comm = boost::dynamic_pointer_cast<activity::CommImpl>(waiting_synchro_);
225
226     if (exec != nullptr) {
227       exec->clean_action();
228     } else if (comm != nullptr) {
229       comm->unregister_simcall(&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_->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
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     try {
322       std::rethrow_exception(std::move(exception));
323     } catch (const simgrid::Exception& e) {
324       e.rethrow_nested(XBT_THROW_POINT, boost::core::demangle(typeid(e).name()) + " raised in kernel mode.");
325     }
326   }
327
328   if (SMPI_switch_data_segment && not finished_) {
329     SMPI_switch_data_segment(get_iface());
330   }
331 }
332
333 /** This actor will be terminated automatically when the last non-daemon actor finishes */
334 void ActorImpl::daemonize()
335 {
336   if (not daemon_) {
337     daemon_ = true;
338     simix_global->daemons.push_back(this);
339   }
340 }
341
342 void ActorImpl::undaemonize()
343 {
344   if (daemon_) {
345     auto& vect = simix_global->daemons;
346     auto it    = std::find(vect.begin(), vect.end(), this);
347     xbt_assert(it != vect.end(), "The dying daemon is not a daemon after all. Please report that bug.");
348     /* Don't move the whole content since we don't really care about the order */
349
350     std::swap(*it, vect.back());
351     vect.pop_back();
352     daemon_ = false;
353   }
354 }
355
356 s4u::Actor* ActorImpl::restart()
357 {
358   xbt_assert(this != simix_global->maestro_, "Restarting maestro is not supported");
359
360   XBT_DEBUG("Restarting actor %s on %s", get_cname(), host_->get_cname());
361
362   // retrieve the arguments of the old actor
363   ProcessArg arg = ProcessArg(host_, this);
364
365   // kill the old actor
366   context::Context::self()->get_actor()->kill(this);
367
368   // start the new actor
369   ActorImplPtr actor = ActorImpl::create(arg.name, arg.code, arg.data, arg.host, arg.properties.get(), nullptr);
370   *actor->on_exit = std::move(*arg.on_exit);
371   actor->set_kill_time(arg.kill_time);
372   actor->set_auto_restart(arg.auto_restart);
373
374   return actor->get_ciface();
375 }
376
377 void ActorImpl::suspend()
378 {
379   if (suspended_) {
380     XBT_DEBUG("Actor '%s' is already suspended", get_cname());
381     return;
382   }
383
384   suspended_ = true;
385
386   /* If the suspended actor is waiting on a sync, suspend its synchronization.
387    * Otherwise, it will suspend itself when scheduled, ie, very soon. */
388   if (waiting_synchro_ != nullptr)
389     waiting_synchro_->suspend();
390 }
391
392 void ActorImpl::resume()
393 {
394   XBT_IN("actor = %p", this);
395
396   if (context_->wannadie()) {
397     XBT_VERB("Ignoring request to suspend an actor that is currently dying.");
398     return;
399   }
400
401   if (not suspended_)
402     return;
403   suspended_ = false;
404
405   /* resume the activity that was blocking the resumed actor. */
406   if (waiting_synchro_)
407     waiting_synchro_->resume();
408   else // Reschedule the actor if it was forcefully unscheduled in yield()
409     simix_global->actors_to_run.push_back(this);
410
411   XBT_OUT();
412 }
413
414 activity::ActivityImplPtr ActorImpl::join(const ActorImpl* actor, double timeout)
415 {
416   activity::ActivityImplPtr sleep = this->sleep(timeout);
417   actor->on_exit->emplace_back([sleep](bool) {
418     if (sleep->surf_action_)
419       sleep->surf_action_->finish(resource::Action::State::FINISHED);
420   });
421   return sleep;
422 }
423
424 activity::ActivityImplPtr ActorImpl::sleep(double duration)
425 {
426   if (not host_->is_on())
427     throw_exception(std::make_exception_ptr(HostFailureException(
428         XBT_THROW_POINT, std::string("Host ") + host_->get_cname() + " failed, you cannot sleep there.")));
429
430   auto sleep = new activity::SleepImpl();
431   sleep->set_name("sleep").set_host(host_).set_duration(duration).start();
432   return activity::SleepImplPtr(sleep);
433 }
434
435 void ActorImpl::throw_exception(std::exception_ptr e)
436 {
437   exception_ = e;
438
439   if (suspended_)
440     resume();
441
442   /* cancel the blocking synchro if any */
443   if (waiting_synchro_) {
444     waiting_synchro_->cancel();
445     activities_.remove(waiting_synchro_);
446     waiting_synchro_ = nullptr;
447   }
448 }
449
450 void ActorImpl::simcall_answer()
451 {
452   if (this != simix_global->maestro_) {
453     XBT_DEBUG("Answer simcall %s (%d) issued by %s (%p)", SIMIX_simcall_name(simcall_.call_), (int)simcall_.call_,
454               get_cname(), this);
455     xbt_assert(simcall_.call_ != simix::Simcall::NONE);
456     simcall_.call_ = simix::Simcall::NONE;
457     xbt_assert(not XBT_LOG_ISENABLED(simix_process, xbt_log_priority_debug) ||
458                    std::find(begin(simix_global->actors_to_run), end(simix_global->actors_to_run), this) ==
459                        end(simix_global->actors_to_run),
460                "Actor %p should not exist in actors_to_run!", this);
461     simix_global->actors_to_run.push_back(this);
462   }
463 }
464
465 void ActorImpl::set_host(s4u::Host* dest)
466 {
467   host_->pimpl_->remove_actor(this);
468   host_ = dest;
469   dest->pimpl_->add_actor(this);
470 }
471
472 ActorImplPtr ActorImpl::init(const std::string& name, s4u::Host* host) const
473 {
474   auto* actor = new ActorImpl(xbt::string(name), host);
475   actor->set_ppid(this->pid_);
476
477   intrusive_ptr_add_ref(actor);
478   /* The on_creation() signal must be delayed until there, where the pid and everything is set */
479   s4u::Actor::on_creation(*actor->get_ciface());
480
481   return ActorImplPtr(actor);
482 }
483
484 ActorImpl* ActorImpl::start(const ActorCode& code)
485 {
486   xbt_assert(code && host_ != nullptr, "Invalid parameters");
487
488   if (not host_->is_on()) {
489     XBT_WARN("Cannot launch actor '%s' on failed host '%s'", name_.c_str(), host_->get_cname());
490     intrusive_ptr_release(this);
491     throw HostFailureException(XBT_THROW_POINT, "Cannot start actor on failed host.");
492   }
493
494   this->code_ = code;
495   XBT_VERB("Create context %s", get_cname());
496   context_.reset(simix_global->context_factory->create_context(ActorCode(code), this));
497
498   XBT_DEBUG("Start context '%s'", get_cname());
499
500   /* Add the actor to its host's actor list */
501   host_->pimpl_->add_actor(this);
502   simix_global->process_list[pid_] = this;
503
504   /* Now insert it in the global actor list and in the actor to run list */
505   XBT_DEBUG("Inserting [%p] %s(%s) in the to_run list", this, get_cname(), host_->get_cname());
506   simix_global->actors_to_run.push_back(this);
507
508   return this;
509 }
510
511 ActorImplPtr ActorImpl::create(const std::string& name, const ActorCode& code, void* data, s4u::Host* host,
512                                const std::unordered_map<std::string, std::string>* properties,
513                                const ActorImpl* parent_actor)
514 {
515   XBT_DEBUG("Start actor %s@'%s'", name.c_str(), host->get_cname());
516
517   ActorImplPtr actor;
518   if (parent_actor != nullptr)
519     actor = parent_actor->init(xbt::string(name), host);
520   else
521     actor = self()->init(xbt::string(name), host);
522
523   /* actor data */
524   actor->set_user_data(data);
525
526   /* Add properties */
527   if (properties != nullptr)
528     actor->set_properties(*properties);
529
530   actor->start(code);
531
532   return actor;
533 }
534
535 void create_maestro(const std::function<void()>& code)
536 {
537   /* Create maestro actor and initialize it */
538   auto* maestro = new ActorImpl(xbt::string(""), /*host*/ nullptr);
539
540   if (not code) {
541     maestro->context_.reset(simix_global->context_factory->create_context(ActorCode(), maestro));
542   } else {
543     maestro->context_.reset(simix_global->context_factory->create_maestro(ActorCode(code), maestro));
544   }
545
546   maestro->simcall_.issuer_     = maestro;
547   simix_global->maestro_        = maestro;
548 }
549
550 } // namespace actor
551 } // namespace kernel
552 } // namespace simgrid
553
554 int SIMIX_process_count() // XBT_ATTRIB_DEPRECATED_v329
555 {
556   return simix_global->process_list.size();
557 }
558
559 void* SIMIX_process_self_get_data() // XBT_ATTRIB_DEPRECATED_v329
560 {
561   smx_actor_t self = simgrid::kernel::actor::ActorImpl::self();
562
563   if (self == nullptr) {
564     return nullptr;
565   }
566   return self->get_user_data();
567 }
568
569 void SIMIX_process_self_set_data(void* data) // XBT_ATTRIB_DEPRECATED_v329
570 {
571   simgrid::kernel::actor::ActorImpl::self()->set_user_data(data);
572 }
573
574 /* needs to be public and without simcall because it is called
575    by exceptions and logging events */
576 const char* SIMIX_process_self_get_name()
577 {
578   return SIMIX_is_maestro() ? "maestro" : simgrid::kernel::actor::ActorImpl::self()->get_cname();
579 }
580
581 /** @brief Returns the process from PID. */
582 smx_actor_t SIMIX_process_from_PID(aid_t pid)
583 {
584   return simgrid::kernel::actor::ActorImpl::by_pid(pid);
585 }
586
587 void SIMIX_process_on_exit(smx_actor_t actor,
588                            const std::function<void(bool /*failed*/)>& fun) // XBT_ATTRIB_DEPRECATED_v329
589 {
590   xbt_assert(actor, "current process not found: are you in maestro context ?");
591   actor->on_exit->emplace_back(fun);
592 }
593
594 void simcall_process_set_data(smx_actor_t process, void* data) // XBT_ATTRIB_DEPRECATED_v329
595 {
596   simgrid::kernel::actor::simcall([process, data] { process->set_user_data(data); });
597 }