Logo AND Algorithmique Numérique Distribuée

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