Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
387f597feb2dea26707daeb0b25f4f0bf5e099e7
[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   const 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   stacksize_      = smx_context_stack_size;
60 }
61
62 ActorImpl::~ActorImpl()
63 {
64   if (simix_global != nullptr && this != simix_global->maestro_)
65     s4u::Actor::on_destruction(*ciface());
66 }
67
68 /* Become an actor in the simulation
69  *
70  * Currently this can only be called by the main thread (once) and only work with some thread factories
71  * (currently ThreadContextFactory).
72  *
73  * In the future, it might be extended in order to attach other threads created by a third party library.
74  */
75
76 ActorImplPtr ActorImpl::attach(const std::string& name, void* data, s4u::Host* host,
77                                const std::unordered_map<std::string, std::string>* properties)
78 {
79   // This is mostly a copy/paste from create(), it'd be nice to share some code between those two functions.
80
81   XBT_DEBUG("Attach actor %s on host '%s'", name.c_str(), host->get_cname());
82
83   if (not host->is_on()) {
84     XBT_WARN("Cannot attach actor '%s' on failed host '%s'", name.c_str(), host->get_cname());
85     throw HostFailureException(XBT_THROW_POINT, "Cannot attach actor on failed host.");
86   }
87
88   ActorImpl* actor = new ActorImpl(xbt::string(name), host);
89   /* Actor data */
90   actor->set_user_data(data);
91   actor->code_ = nullptr;
92
93   XBT_VERB("Create context %s", actor->get_cname());
94   xbt_assert(simix_global != nullptr, "simix is not initialized, please call MSG_init first");
95   actor->context_.reset(simix_global->context_factory->attach(actor));
96
97   /* Add properties */
98   if (properties != nullptr)
99     actor->set_properties(*properties);
100
101   /* Add the actor to it's host actor list */
102   host->pimpl_->add_actor(actor);
103
104   /* Now insert it in the global actor list and in the actors to run list */
105   simix_global->process_list[actor->get_pid()] = actor;
106   XBT_DEBUG("Inserting [%p] %s(%s) in the to_run list", actor, actor->get_cname(), host->get_cname());
107   simix_global->actors_to_run.push_back(actor);
108   intrusive_ptr_add_ref(actor);
109
110   auto* context = dynamic_cast<context::AttachContext*>(actor->context_.get());
111   xbt_assert(nullptr != context, "Not a suitable context");
112   context->attach_start();
113
114   /* The on_creation() signal must be delayed until there, where the pid and everything is set */
115   s4u::Actor::on_creation(*actor->ciface());
116
117   return ActorImplPtr(actor);
118 }
119 /** @brief Detach an actor attached with `attach()`
120  *
121  *  This is called when the current actor has finished its job.
122  *  Used in the main thread, it waits for the simulation to finish before returning. When it returns, the other
123  *  simulated actors and the maestro are destroyed.
124  */
125 void ActorImpl::detach()
126 {
127   auto* context = dynamic_cast<context::AttachContext*>(context::Context::self());
128   if (context == nullptr)
129     xbt_die("Not a suitable context");
130
131   context->get_actor()->cleanup();
132   context->attach_stop();
133 }
134
135 void ActorImpl::cleanup_from_simix()
136 {
137   const std::lock_guard<std::mutex> lock(simix_global->mutex);
138   simix_global->process_list.erase(pid_);
139   if (host_ && host_actor_list_hook.is_linked())
140     host_->pimpl_->remove_actor(this);
141   if (not smx_destroy_list_hook.is_linked()) {
142 #if SIMGRID_HAVE_MC
143     xbt_dynar_push_as(simix_global->dead_actors_vector, ActorImpl*, this);
144 #endif
145     simix_global->actors_to_destroy.push_back(*this);
146   }
147 }
148
149 void ActorImpl::cleanup()
150 {
151   finished_ = true;
152
153   if (has_to_auto_restart() && not get_host()->is_on()) {
154     XBT_DEBUG("Insert host %s to watched_hosts because it's off and %s needs to restart", get_host()->get_cname(),
155               get_cname());
156     watched_hosts.insert(get_host()->get_name());
157   }
158
159   if (on_exit) {
160     // Execute the termination callbacks
161     bool failed = context_->wannadie();
162     for (auto exit_fun = on_exit->crbegin(); exit_fun != on_exit->crend(); ++exit_fun)
163       (*exit_fun)(failed);
164     on_exit.reset();
165   }
166   undaemonize();
167
168   /* cancel non-blocking activities */
169   for (auto activity : activities)
170     activity->cancel();
171   activities.clear();
172
173   XBT_DEBUG("%s@%s(%ld) should not run anymore", get_cname(), get_host()->get_cname(), get_pid());
174
175   if (this == simix_global->maestro_) /* Do not cleanup maestro */
176     return;
177
178   XBT_DEBUG("Cleanup actor %s (%p), waiting synchro %p", get_cname(), this, waiting_synchro.get());
179
180   /* Unregister associated timers if any */
181   if (kill_timer != nullptr) {
182     kill_timer->remove();
183     kill_timer = nullptr;
184   }
185   if (simcall.timeout_cb_) {
186     simcall.timeout_cb_->remove();
187     simcall.timeout_cb_ = nullptr;
188   }
189
190   cleanup_from_simix();
191
192   context_->set_wannadie(false); // don't let the simcall's yield() do a Context::stop(), to avoid infinite loops
193   actor::simcall([this] { s4u::Actor::on_termination(*ciface()); });
194   context_->set_wannadie();
195 }
196
197 void ActorImpl::exit()
198 {
199   context_->set_wannadie();
200   suspended_          = false;
201   exception_          = nullptr;
202
203   /* destroy the blocking synchro if any */
204   if (waiting_synchro != nullptr) {
205     waiting_synchro->cancel();
206     waiting_synchro->state_ = activity::State::FAILED;
207
208     activity::ExecImplPtr exec   = boost::dynamic_pointer_cast<activity::ExecImpl>(waiting_synchro);
209     activity::CommImplPtr comm   = boost::dynamic_pointer_cast<activity::CommImpl>(waiting_synchro);
210
211     if (exec != nullptr) {
212       exec->clean_action();
213     } else if (comm != nullptr) {
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     activities.remove(waiting_synchro);
223     waiting_synchro = nullptr;
224   }
225
226   // Forcefully kill the actor if its host is turned off. Not a HostFailureException because you should not survive that
227   this->throw_exception(std::make_exception_ptr(ForcefulKillException(host_->is_on() ? "exited" : "host failed")));
228 }
229
230 void ActorImpl::kill(ActorImpl* actor)
231 {
232   xbt_assert(actor != simix_global->maestro_, "Killing maestro is a rather bad idea");
233   if (actor->finished_) {
234     XBT_DEBUG("Ignoring request to kill actor %s@%s that is already dead", actor->get_cname(),
235               actor->host_->get_cname());
236     return;
237   }
238
239   XBT_DEBUG("Actor '%s'@%s is killing actor '%s'@%s", get_cname(), host_ ? host_->get_cname() : "", actor->get_cname(),
240             actor->host_ ? actor->host_->get_cname() : "");
241
242   actor->exit();
243
244   if (actor == this) {
245     XBT_DEBUG("Go on, this is a suicide,");
246   } else if (std::find(begin(simix_global->actors_to_run), end(simix_global->actors_to_run), actor) !=
247              end(simix_global->actors_to_run)) {
248     XBT_DEBUG("Actor %s is already in the to_run list", actor->get_cname());
249   } else {
250     XBT_DEBUG("Inserting %s in the to_run list", actor->get_cname());
251     simix_global->actors_to_run.push_back(actor);
252   }
253 }
254
255 void ActorImpl::kill_all()
256 {
257   for (auto const& kv : simix_global->process_list)
258     if (kv.second != this)
259       this->kill(kv.second);
260 }
261
262 void ActorImpl::set_kill_time(double kill_time)
263 {
264   if (kill_time <= SIMIX_get_clock())
265     return;
266   XBT_DEBUG("Set kill time %f for actor %s@%s", kill_time, get_cname(), host_->get_cname());
267   kill_timer = simix::Timer::set(kill_time, [this] {
268     this->exit();
269     kill_timer = nullptr;
270   });
271 }
272
273 double ActorImpl::get_kill_time()
274 {
275   return kill_timer ? kill_timer->get_date() : 0;
276 }
277
278 void ActorImpl::yield()
279 {
280   XBT_DEBUG("Yield actor '%s'", get_cname());
281
282   /* Go into sleep and return control to maestro */
283   context_->suspend();
284
285   /* Ok, maestro returned control to us */
286   XBT_DEBUG("Control returned to me: '%s'", get_cname());
287
288   if (context_->wannadie()) {
289     XBT_DEBUG("Actor %s@%s is dead", get_cname(), host_->get_cname());
290     context_->stop();
291     THROW_IMPOSSIBLE;
292   }
293
294   if (suspended_) {
295     XBT_DEBUG("Hey! I'm suspended.");
296
297     xbt_assert(exception_ == nullptr, "Gasp! This exception may be lost by subsequent calls.");
298     suspended_ = false;
299     suspend();
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     std::rethrow_exception(std::move(exception));
307   }
308
309   if (SMPI_switch_data_segment && not finished_) {
310     SMPI_switch_data_segment(iface());
311   }
312 }
313
314 /** This actor will be terminated automatically when the last non-daemon actor finishes */
315 void ActorImpl::daemonize()
316 {
317   if (not daemon_) {
318     daemon_ = true;
319     simix_global->daemons.push_back(this);
320   }
321 }
322
323 void ActorImpl::undaemonize()
324 {
325   if (daemon_) {
326     auto& vect = simix_global->daemons;
327     auto it    = std::find(vect.begin(), vect.end(), this);
328     xbt_assert(it != vect.end(), "The dying daemon is not a daemon after all. Please report that bug.");
329     /* Don't move the whole content since we don't really care about the order */
330
331     std::swap(*it, vect.back());
332     vect.pop_back();
333     daemon_ = false;
334   }
335 }
336
337 s4u::Actor* ActorImpl::restart()
338 {
339   xbt_assert(this != simix_global->maestro_, "Restarting maestro is not supported");
340
341   XBT_DEBUG("Restarting actor %s on %s", get_cname(), host_->get_cname());
342
343   // retrieve the arguments of the old actor
344   ProcessArg arg = ProcessArg(host_, this);
345
346   // kill the old actor
347   context::Context::self()->get_actor()->kill(this);
348
349   // start the new actor
350   ActorImplPtr actor =
351       ActorImpl::create(arg.name, std::move(arg.code), arg.data, arg.host, arg.properties.get(), nullptr);
352   *actor->on_exit = std::move(*arg.on_exit);
353   actor->set_kill_time(arg.kill_time);
354   actor->set_auto_restart(arg.auto_restart);
355
356   return actor->ciface();
357 }
358
359 void ActorImpl::suspend()
360 {
361   if (suspended_) {
362     XBT_DEBUG("Actor '%s' is already suspended", get_cname());
363     return;
364   }
365
366   suspended_ = true;
367
368   /* If the suspended actor is waiting on a sync, suspend its synchronization. */
369   if (waiting_synchro == nullptr) {
370     auto exec = new activity::ExecImpl();
371     exec->set_name("suspend").set_host(host_).set_flops_amount(0.0).start();
372     waiting_synchro = activity::ExecImplPtr(exec);
373
374     waiting_synchro->simcalls_.push_back(&simcall);
375   }
376   waiting_synchro->suspend();
377 }
378
379 void ActorImpl::resume()
380 {
381   XBT_IN("actor = %p", this);
382
383   if (context_->wannadie()) {
384     XBT_VERB("Ignoring request to suspend an actor that is currently dying.");
385     return;
386   }
387
388   if (not suspended_)
389     return;
390   suspended_ = false;
391
392   /* resume the synchronization that was blocking the resumed actor. */
393   if (waiting_synchro)
394     waiting_synchro->resume();
395
396   XBT_OUT();
397 }
398
399 activity::ActivityImplPtr ActorImpl::join(const ActorImpl* actor, double timeout)
400 {
401   activity::ActivityImplPtr sleep = this->sleep(timeout);
402   actor->on_exit->emplace_back([sleep](bool) {
403     if (sleep->surf_action_)
404       sleep->surf_action_->finish(resource::Action::State::FINISHED);
405   });
406   return sleep;
407 }
408
409 activity::ActivityImplPtr ActorImpl::sleep(double duration)
410 {
411   if (not host_->is_on())
412     throw_exception(std::make_exception_ptr(HostFailureException(
413         XBT_THROW_POINT, std::string("Host ") + host_->get_cname() + " failed, you cannot sleep there.")));
414
415   auto sleep = new activity::SleepImpl();
416   sleep->set_name("sleep").set_host(host_).set_duration(duration).start();
417   return activity::SleepImplPtr(sleep);
418 }
419
420 void ActorImpl::throw_exception(std::exception_ptr e)
421 {
422   exception_ = e;
423
424   if (suspended_)
425     resume();
426
427   /* cancel the blocking synchro if any */
428   if (waiting_synchro) {
429     waiting_synchro->cancel();
430     activities.remove(waiting_synchro);
431     waiting_synchro = nullptr;
432   }
433 }
434
435 void ActorImpl::simcall_answer()
436 {
437   if (this != simix_global->maestro_) {
438     XBT_DEBUG("Answer simcall %s (%d) issued by %s (%p)", SIMIX_simcall_name(simcall.call_), (int)simcall.call_,
439               get_cname(), this);
440     xbt_assert(simcall.call_ != SIMCALL_NONE);
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 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(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 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(ActorCode(), maestro));
526   } else {
527     maestro->context_.reset(simix_global->context_factory->create_maestro(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::kernel::actor::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) // XBT_ATTRIB_DEPRECATED_v329
620 {
621   simgrid::kernel::actor::simcall([process, data] { process->set_user_data(data); });
622 }