Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Apply the default settings of 'smpi/buffering' too
[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
23 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(simix_process, simix, "Logging specific to SIMIX (process)");
24
25 /**
26  * @brief Returns the current agent.
27  *
28  * This functions returns the currently running SIMIX process.
29  *
30  * @return The SIMIX process
31  */
32 smx_actor_t SIMIX_process_self()
33 {
34   simgrid::kernel::context::Context* self_context = simgrid::kernel::context::Context::self();
35
36   return (self_context != nullptr) ? self_context->get_actor() : nullptr;
37 }
38
39 /**
40  * @brief Returns whether a process has pending asynchronous communications.
41  * @return true if there are asynchronous communications in this process
42  * @deprecated
43  */
44 int SIMIX_process_has_pending_comms(smx_actor_t process)
45 {
46
47   return process->comms.size() > 0;
48 }
49
50 namespace simgrid {
51 namespace kernel {
52 namespace actor {
53
54 static unsigned long maxpid = 0;
55 int get_maxpid()
56 {
57   return maxpid;
58 }
59
60 ActorImpl::ActorImpl(const simgrid::xbt::string& name, s4u::Host* host) : host_(host), name_(name), piface_(this)
61 {
62   pid_           = maxpid++;
63   simcall.issuer_ = this;
64 }
65
66 ActorImpl::~ActorImpl()
67 {
68   if (simix_global != nullptr && this != simix_global->maestro_process) {
69     if (context_.get() != nullptr) /* the actor was not start()ed yet. This happens if its host was initially off */
70       context_->iwannadie = false; // don't let the simcall's yield() do a Context::stop(), to avoid infinite loops
71     simgrid::kernel::actor::simcall([this] { simgrid::s4u::Actor::on_destruction(*ciface()); });
72     if (context_.get() != nullptr)
73       context_->iwannadie = true;
74   }
75 }
76
77 /* Become an actor in the simulation
78  *
79  * Currently this can only be called by the main thread (once) and only work with some thread factories
80  * (currently ThreadContextFactory).
81  *
82  * In the future, it might be extended in order to attach other threads created by a third party library.
83  */
84
85 ActorImplPtr ActorImpl::attach(const std::string& name, void* data, s4u::Host* host,
86                                const std::unordered_map<std::string, std::string>* properties)
87 {
88   // This is mostly a copy/paste from create(), it'd be nice to share some code between those two functions.
89
90   XBT_DEBUG("Attach process %s on host '%s'", name.c_str(), host->get_cname());
91
92   if (not host->is_on()) {
93     XBT_WARN("Cannot launch process '%s' on failed host '%s'", name.c_str(), host->get_cname());
94     throw simgrid::HostFailureException(XBT_THROW_POINT, "Cannot attach actor on failed host.");
95   }
96
97   ActorImpl* actor = new ActorImpl(xbt::string(name), host);
98   /* Actor data */
99   actor->set_user_data(data);
100   actor->code_ = nullptr;
101
102   XBT_VERB("Create context %s", actor->get_cname());
103   xbt_assert(simix_global != nullptr, "simix is not initialized, please call MSG_init first");
104   actor->context_.reset(simix_global->context_factory->attach(actor));
105
106   /* Add properties */
107   if (properties != nullptr)
108     actor->set_properties(*properties);
109
110   /* Add the process to it's host process list */
111   host->pimpl_->process_list_.push_back(*actor);
112
113   /* Now insert it in the global process list and in the process to run list */
114   simix_global->process_list[actor->get_pid()] = actor;
115   XBT_DEBUG("Inserting [%p] %s(%s) in the to_run list", actor, actor->get_cname(), host->get_cname());
116   simix_global->actors_to_run.push_back(actor);
117   intrusive_ptr_add_ref(actor);
118
119   auto* context = dynamic_cast<simgrid::kernel::context::AttachContext*>(actor->context_.get());
120   xbt_assert(nullptr != context, "Not a suitable context");
121   context->attach_start();
122
123   /* The on_creation() signal must be delayed until there, where the pid and everything is set */
124   simgrid::s4u::Actor::on_creation(*actor->ciface());
125
126   return ActorImplPtr(actor);
127 }
128 /** @brief Detach an actor attached with `attach()`
129  *
130  *  This is called when the current actor has finished its job.
131  *  Used in the main thread, it waits for the simulation to finish before returning. When it returns, the other
132  *  simulated actors and the maestro are destroyed.
133  */
134 void ActorImpl::detach()
135 {
136   auto* context = dynamic_cast<context::AttachContext*>(context::Context::self());
137   if (context == nullptr)
138     xbt_die("Not a suitable context");
139
140   context->get_actor()->cleanup();
141   context->attach_stop();
142 }
143
144 void ActorImpl::cleanup()
145 {
146   finished_ = true;
147
148   if (has_to_auto_restart() && not get_host()->is_on()) {
149     XBT_DEBUG("Insert host %s to watched_hosts because it's off and %s needs to restart", get_host()->get_cname(),
150               get_cname());
151     watched_hosts.insert(get_host()->get_name());
152   }
153
154   if (on_exit) {
155     // Execute the termination callbacks
156     bool failed = context_->iwannadie;
157     for (auto exit_fun = on_exit->crbegin(); exit_fun != on_exit->crend(); ++exit_fun)
158       (*exit_fun)(failed);
159     on_exit.reset();
160   }
161   undaemonize();
162
163   /* cancel non-blocking activities */
164   for (auto activity : comms)
165     boost::static_pointer_cast<activity::CommImpl>(activity)->cancel();
166   comms.clear();
167
168   XBT_DEBUG("%s@%s(%ld) should not run anymore", get_cname(), get_host()->get_cname(), get_pid());
169
170   if (this == simix_global->maestro_process) /* Do not cleanup maestro */
171     return;
172
173   XBT_DEBUG("Cleanup actor %s (%p), waiting synchro %p", get_cname(), this, waiting_synchro.get());
174
175   /* Unregister from the kill timer if any */
176   if (kill_timer != nullptr) {
177     kill_timer->remove();
178     kill_timer = nullptr;
179   }
180
181   simix_global->mutex.lock();
182
183   simix_global->process_list.erase(pid_);
184   if (host_ && host_process_list_hook.is_linked())
185     simgrid::xbt::intrusive_erase(host_->pimpl_->process_list_, *this);
186   if (not smx_destroy_list_hook.is_linked()) {
187 #if SIMGRID_HAVE_MC
188     xbt_dynar_push_as(simix_global->dead_actors_vector, ActorImpl*, this);
189 #endif
190     simix_global->actors_to_destroy.push_back(*this);
191   }
192
193   simix_global->mutex.unlock();
194
195   context_->iwannadie = false; // don't let the simcall's yield() do a Context::stop(), to avoid infinite loops
196   simgrid::kernel::actor::simcall([this] { simgrid::s4u::Actor::on_termination(*ciface()); });
197   context_->iwannadie = true;
198 }
199
200 void ActorImpl::exit()
201 {
202   context_->iwannadie = true;
203   suspended_          = false;
204   exception_          = nullptr;
205
206   /* destroy the blocking synchro if any */
207   if (waiting_synchro != nullptr) {
208     waiting_synchro->cancel();
209     waiting_synchro->state_ = SIMIX_FAILED;
210
211     activity::ExecImplPtr exec   = boost::dynamic_pointer_cast<activity::ExecImpl>(waiting_synchro);
212     activity::CommImplPtr comm   = boost::dynamic_pointer_cast<activity::CommImpl>(waiting_synchro);
213
214     if (exec != nullptr) {
215       exec->clean_action();
216     } else if (comm != nullptr) {
217       comms.remove(waiting_synchro);
218       // Remove first occurrence of &actor->simcall:
219       auto i = boost::range::find(waiting_synchro->simcalls_, &simcall);
220       if (i != waiting_synchro->simcalls_.end())
221         waiting_synchro->simcalls_.remove(&simcall);
222     } else {
223       activity::ActivityImplPtr(waiting_synchro)->finish();
224     }
225
226     waiting_synchro = nullptr;
227   }
228
229   // Forcefully kill the actor if its host is turned off. Not a HostFailureException because you should not survive that
230   this->throw_exception(std::make_exception_ptr(ForcefulKillException(host_->is_on() ? "exited" : "host failed")));
231 }
232
233 void ActorImpl::kill(ActorImpl* actor)
234 {
235   if (actor->finished_) {
236     XBT_DEBUG("Ignoring request to kill actor %s@%s that is already dead", actor->get_cname(),
237               actor->host_->get_cname());
238     return;
239   }
240
241   XBT_DEBUG("Actor '%s'@%s is killing actor '%s'@%s", get_cname(), host_ ? host_->get_cname() : "", actor->get_cname(),
242             actor->host_ ? actor->host_->get_cname() : "");
243
244   actor->exit();
245
246   if (std::find(begin(simix_global->actors_to_run), end(simix_global->actors_to_run), actor) ==
247           end(simix_global->actors_to_run) &&
248       actor != this) {
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_->iwannadie) {
288     XBT_DEBUG("Actor %s@%s is dead", get_cname(), host_->get_cname());
289     // throw simgrid::kernel::context::ForcefulKillException(); Does not seem to properly kill the actor
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(this);
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_process, "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(ActorImpl* issuer)
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     activity::ExecImpl* 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_->iwannadie) {
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(ActorImpl* actor, double timeout)
400 {
401   activity::ActivityImplPtr sleep = this->sleep(timeout);
402   SIMIX_process_on_exit(actor, [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(simgrid::HostFailureException(
413         XBT_THROW_POINT, std::string("Host ") + host_->get_cname() + " failed, you cannot sleep there.")));
414
415   activity::SleepImpl* 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
431     activity::CommImplPtr comm = boost::dynamic_pointer_cast<activity::CommImpl>(waiting_synchro);
432
433     if (comm != nullptr)
434       comms.remove(comm);
435
436     waiting_synchro = nullptr;
437   }
438 }
439
440 void ActorImpl::simcall_answer()
441 {
442   if (this != simix_global->maestro_process){
443     XBT_DEBUG("Answer simcall %s (%d) issued by %s (%p)", SIMIX_simcall_name(simcall.call_), (int)simcall.call_,
444               get_cname(), this);
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   xbt::intrusive_erase(host_->pimpl_->process_list_, *this);
457   host_ = dest;
458   dest->pimpl_->process_list_.push_back(*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 simix::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 simgrid::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(simix::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_->process_list_.push_back(*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 simix::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 = SIMIX_process_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(simix::ActorCode(), maestro));
530   } else {
531     maestro->context_.reset(simix_global->context_factory->create_maestro(simix::ActorCode(code), maestro));
532   }
533
534   maestro->simcall.issuer_      = maestro;
535   simix_global->maestro_process = maestro;
536 }
537
538 } // namespace actor
539 } // namespace kernel
540 } // namespace simgrid
541
542 void SIMIX_process_detach() // deprecated v3.25
543 {
544   simgrid::kernel::actor::ActorImpl::detach();
545 }
546
547 smx_actor_t SIMIX_process_attach(const char* name, void* data, const char* hostname,
548                                  std::unordered_map<std::string, std::string>* properties,
549                                  smx_actor_t /*parent_process*/) // deprecated 3.25
550 {
551   return simgrid::kernel::actor::ActorImpl::attach(name, data, sg_host_by_name(hostname), properties).get();
552 }
553
554 int SIMIX_process_count()
555 {
556   return simix_global->process_list.size();
557 }
558
559 void* SIMIX_process_self_get_data() // deprecated
560 {
561   smx_actor_t self = SIMIX_process_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) // deprecated
570 {
571   SIMIX_process_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
579   smx_actor_t process = SIMIX_process_self();
580   if (process == nullptr || process == simix_global->maestro_process)
581     return "maestro";
582
583   return process->get_cname();
584 }
585
586 /**
587  * @brief Calling this function makes the process to yield.
588  *
589  * Only the current process can call this function, giving back the control to maestro.
590  *
591  * @param self the current process
592  */
593
594 /** @brief Returns the list of processes to run.
595  * @deprecated
596  */
597 const std::vector<smx_actor_t>& simgrid::simix::process_get_runnable()
598 {
599   return simix_global->actors_to_run;
600 }
601
602 /** @brief Returns the process from PID. */
603 smx_actor_t SIMIX_process_from_PID(aid_t PID)
604 {
605   auto item = simix_global->process_list.find(PID);
606   if (item == simix_global->process_list.end()) {
607     for (auto& a : simix_global->actors_to_destroy)
608       if (a.get_pid() == PID)
609         return &a;
610     return nullptr; // Not found, even in the trash
611   }
612   return item->second;
613 }
614
615 void SIMIX_process_on_exit(smx_actor_t actor, int_f_pvoid_pvoid_t fun, void* data)
616 {
617   SIMIX_process_on_exit(actor, [fun, data](bool failed) {
618     intptr_t status = failed ? SMX_EXIT_FAILURE : SMX_EXIT_SUCCESS;
619     fun(reinterpret_cast<void*>(status), data);
620   });
621 }
622
623 void SIMIX_process_on_exit(smx_actor_t actor, const std::function<void(int, void*)>& fun, void* data)
624 {
625   SIMIX_process_on_exit(actor, [fun, data](bool failed) { fun(failed ? SMX_EXIT_FAILURE : SMX_EXIT_SUCCESS, data); });
626 }
627
628 void SIMIX_process_on_exit(smx_actor_t actor, const std::function<void(bool /*failed*/)>& fun)
629 {
630   xbt_assert(actor, "current process not found: are you in maestro context ?");
631   actor->on_exit->emplace_back(fun);
632 }
633
634 /** @brief Restart a process, starting it again from the beginning. */
635 /**
636  * @ingroup simix_process_management
637  * @brief Creates and runs a new SIMIX process.
638  *
639  * The structure and the corresponding thread are created and put in the list of ready processes.
640  *
641  * @param name a name for the process. It is for user-level information and can be nullptr.
642  * @param code the main function of the process
643  * @param data a pointer to any data one may want to attach to the new object. It is for user-level information and can
644  * be nullptr.
645  * It can be retrieved with the method ActorImpl::getUserData().
646  * @param host where the new agent is executed.
647  * @param properties the properties of the process
648  */
649 smx_actor_t simcall_process_create(const std::string& name, const simgrid::simix::ActorCode& code, void* data,
650                                    sg_host_t host, std::unordered_map<std::string, std::string>* properties)
651 {
652   smx_actor_t self = SIMIX_process_self();
653   return simgrid::kernel::actor::simcall([&name, &code, data, host, properties, self] {
654     return simgrid::kernel::actor::ActorImpl::create(name, code, data, host, properties, self).get();
655   });
656 }
657
658 void simcall_process_set_data(smx_actor_t process, void* data)
659 {
660   simgrid::kernel::actor::simcall([process, data] { process->set_user_data(data); });
661 }