Logo AND Algorithmique Numérique Distribuée

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