Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
28fcc0f4ed8ff21dc95f07e171b860bc690c44da
[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(simgrid::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_process) {
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     simgrid::kernel::actor::simcall([this] { simgrid::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 process %s on host '%s'", name.c_str(), host->get_cname());
86
87   if (not host->is_on()) {
88     XBT_WARN("Cannot launch process '%s' on failed host '%s'", name.c_str(), host->get_cname());
89     throw simgrid::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 process to it's host process list */
106   host->pimpl_->add_actor(actor);
107
108   /* Now insert it in the global process list and in the process 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<simgrid::kernel::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   simgrid::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()
140 {
141   finished_ = true;
142
143   if (has_to_auto_restart() && not get_host()->is_on()) {
144     XBT_DEBUG("Insert host %s to watched_hosts because it's off and %s needs to restart", get_host()->get_cname(),
145               get_cname());
146     watched_hosts.insert(get_host()->get_name());
147   }
148
149   if (on_exit) {
150     // Execute the termination callbacks
151     bool failed = context_->iwannadie;
152     for (auto exit_fun = on_exit->crbegin(); exit_fun != on_exit->crend(); ++exit_fun)
153       (*exit_fun)(failed);
154     on_exit.reset();
155   }
156   undaemonize();
157
158   /* cancel non-blocking activities */
159   for (auto activity : comms)
160     boost::static_pointer_cast<activity::CommImpl>(activity)->cancel();
161   comms.clear();
162
163   XBT_DEBUG("%s@%s(%ld) should not run anymore", get_cname(), get_host()->get_cname(), get_pid());
164
165   if (this == simix_global->maestro_process) /* Do not cleanup maestro */
166     return;
167
168   XBT_DEBUG("Cleanup actor %s (%p), waiting synchro %p", get_cname(), this, waiting_synchro.get());
169
170   /* Unregister from the kill timer if any */
171   if (kill_timer != nullptr) {
172     kill_timer->remove();
173     kill_timer = nullptr;
174   }
175
176   simix_global->mutex.lock();
177
178   simix_global->process_list.erase(pid_);
179   if (host_ && host_actor_list_hook.is_linked())
180     host_->pimpl_->remove_actor(this);
181   if (not smx_destroy_list_hook.is_linked()) {
182 #if SIMGRID_HAVE_MC
183     xbt_dynar_push_as(simix_global->dead_actors_vector, ActorImpl*, this);
184 #endif
185     simix_global->actors_to_destroy.push_back(*this);
186   }
187
188   simix_global->mutex.unlock();
189
190   context_->iwannadie = false; // don't let the simcall's yield() do a Context::stop(), to avoid infinite loops
191   simgrid::kernel::actor::simcall([this] { simgrid::s4u::Actor::on_termination(*ciface()); });
192   context_->iwannadie = true;
193 }
194
195 void ActorImpl::exit()
196 {
197   context_->iwannadie = true;
198   suspended_          = false;
199   exception_          = nullptr;
200
201   /* destroy the blocking synchro if any */
202   if (waiting_synchro != nullptr) {
203     waiting_synchro->cancel();
204     waiting_synchro->state_ = activity::State::FAILED;
205
206     activity::ExecImplPtr exec   = boost::dynamic_pointer_cast<activity::ExecImpl>(waiting_synchro);
207     activity::CommImplPtr comm   = boost::dynamic_pointer_cast<activity::CommImpl>(waiting_synchro);
208
209     if (exec != nullptr) {
210       exec->clean_action();
211     } else if (comm != nullptr) {
212       comms.remove(waiting_synchro);
213       // Remove first occurrence of &actor->simcall:
214       auto i = boost::range::find(waiting_synchro->simcalls_, &simcall);
215       if (i != waiting_synchro->simcalls_.end())
216         waiting_synchro->simcalls_.remove(&simcall);
217     } else {
218       activity::ActivityImplPtr(waiting_synchro)->finish();
219     }
220
221     waiting_synchro = nullptr;
222   }
223
224   // Forcefully kill the actor if its host is turned off. Not a HostFailureException because you should not survive that
225   this->throw_exception(std::make_exception_ptr(ForcefulKillException(host_->is_on() ? "exited" : "host failed")));
226 }
227
228 void ActorImpl::kill(ActorImpl* actor)
229 {
230   xbt_assert(actor != simix_global->maestro_process, "Killing maestro is a rather bad idea");
231   if (actor->finished_) {
232     XBT_DEBUG("Ignoring request to kill actor %s@%s that is already dead", actor->get_cname(),
233               actor->host_->get_cname());
234     return;
235   }
236
237   XBT_DEBUG("Actor '%s'@%s is killing actor '%s'@%s", get_cname(), host_ ? host_->get_cname() : "", actor->get_cname(),
238             actor->host_ ? actor->host_->get_cname() : "");
239
240   actor->exit();
241
242   if (std::find(begin(simix_global->actors_to_run), end(simix_global->actors_to_run), actor) ==
243           end(simix_global->actors_to_run) &&
244       actor != this) {
245     XBT_DEBUG("Inserting %s in the to_run list", actor->get_cname());
246     simix_global->actors_to_run.push_back(actor);
247   }
248 }
249
250 void ActorImpl::kill_all()
251 {
252   for (auto const& kv : simix_global->process_list)
253     if (kv.second != this)
254       this->kill(kv.second);
255 }
256
257 void ActorImpl::set_kill_time(double kill_time)
258 {
259   if (kill_time <= SIMIX_get_clock())
260     return;
261   XBT_DEBUG("Set kill time %f for actor %s@%s", kill_time, get_cname(), host_->get_cname());
262   kill_timer = simix::Timer::set(kill_time, [this] {
263     this->exit();
264     kill_timer = nullptr;
265   });
266 }
267
268 double ActorImpl::get_kill_time()
269 {
270   return kill_timer ? kill_timer->get_date() : 0;
271 }
272
273 void ActorImpl::yield()
274 {
275   XBT_DEBUG("Yield actor '%s'", get_cname());
276
277   /* Go into sleep and return control to maestro */
278   context_->suspend();
279
280   /* Ok, maestro returned control to us */
281   XBT_DEBUG("Control returned to me: '%s'", get_cname());
282
283   if (context_->iwannadie) {
284     XBT_DEBUG("Actor %s@%s is dead", get_cname(), host_->get_cname());
285     context_->stop();
286     THROW_IMPOSSIBLE;
287   }
288
289   if (suspended_) {
290     XBT_DEBUG("Hey! I'm suspended.");
291
292     xbt_assert(exception_ == nullptr, "Gasp! This exception may be lost by subsequent calls.");
293     suspended_ = false;
294     suspend();
295   }
296
297   if (exception_ != nullptr) {
298     XBT_DEBUG("Wait, maestro left me an exception");
299     std::exception_ptr exception = std::move(exception_);
300     exception_                   = nullptr;
301     std::rethrow_exception(std::move(exception));
302   }
303
304   if (SMPI_switch_data_segment && not finished_) {
305     SMPI_switch_data_segment(iface());
306   }
307 }
308
309 /** This actor will be terminated automatically when the last non-daemon actor finishes */
310 void ActorImpl::daemonize()
311 {
312   if (not daemon_) {
313     daemon_ = true;
314     simix_global->daemons.push_back(this);
315   }
316 }
317
318 void ActorImpl::undaemonize()
319 {
320   if (daemon_) {
321     auto& vect = simix_global->daemons;
322     auto it    = std::find(vect.begin(), vect.end(), this);
323     xbt_assert(it != vect.end(), "The dying daemon is not a daemon after all. Please report that bug.");
324     /* Don't move the whole content since we don't really care about the order */
325
326     std::swap(*it, vect.back());
327     vect.pop_back();
328     daemon_ = false;
329   }
330 }
331
332 s4u::Actor* ActorImpl::restart()
333 {
334   xbt_assert(this != simix_global->maestro_process, "Restarting maestro is not supported");
335
336   XBT_DEBUG("Restarting actor %s on %s", get_cname(), host_->get_cname());
337
338   // retrieve the arguments of the old actor
339   ProcessArg arg = ProcessArg(host_, this);
340
341   // kill the old actor
342   context::Context::self()->get_actor()->kill(this);
343
344   // start the new actor
345   ActorImplPtr actor =
346       ActorImpl::create(arg.name, std::move(arg.code), arg.data, arg.host, arg.properties.get(), nullptr);
347   *actor->on_exit = std::move(*arg.on_exit);
348   actor->set_kill_time(arg.kill_time);
349   actor->set_auto_restart(arg.auto_restart);
350
351   return actor->ciface();
352 }
353
354 void ActorImpl::suspend()
355 {
356   if (suspended_) {
357     XBT_DEBUG("Actor '%s' is already suspended", get_cname());
358     return;
359   }
360
361   suspended_ = true;
362
363   /* If the suspended actor is waiting on a sync, suspend its synchronization. */
364   if (waiting_synchro == nullptr) {
365     auto exec = new activity::ExecImpl();
366     exec->set_name("suspend").set_host(host_).set_flops_amount(0.0).start();
367     waiting_synchro = activity::ExecImplPtr(exec);
368
369     waiting_synchro->simcalls_.push_back(&simcall);
370   }
371   waiting_synchro->suspend();
372 }
373
374 void ActorImpl::resume()
375 {
376   XBT_IN("actor = %p", this);
377
378   if (context_->iwannadie) {
379     XBT_VERB("Ignoring request to suspend an actor that is currently dying.");
380     return;
381   }
382
383   if (not suspended_)
384     return;
385   suspended_ = false;
386
387   /* resume the synchronization that was blocking the resumed actor. */
388   if (waiting_synchro)
389     waiting_synchro->resume();
390
391   XBT_OUT();
392 }
393
394 activity::ActivityImplPtr ActorImpl::join(ActorImpl* actor, double timeout)
395 {
396   activity::ActivityImplPtr sleep = this->sleep(timeout);
397   actor->on_exit->emplace_back([sleep](bool) {
398     if (sleep->surf_action_)
399       sleep->surf_action_->finish(resource::Action::State::FINISHED);
400   });
401   return sleep;
402 }
403
404 activity::ActivityImplPtr ActorImpl::sleep(double duration)
405 {
406   if (not host_->is_on())
407     throw_exception(std::make_exception_ptr(simgrid::HostFailureException(
408         XBT_THROW_POINT, std::string("Host ") + host_->get_cname() + " failed, you cannot sleep there.")));
409
410   auto sleep = new activity::SleepImpl();
411   sleep->set_name("sleep").set_host(host_).set_duration(duration).start();
412   return activity::SleepImplPtr(sleep);
413 }
414
415 void ActorImpl::throw_exception(std::exception_ptr e)
416 {
417   exception_ = e;
418
419   if (suspended_)
420     resume();
421
422   /* cancel the blocking synchro if any */
423   if (waiting_synchro) {
424     waiting_synchro->cancel();
425
426     activity::CommImplPtr comm = boost::dynamic_pointer_cast<activity::CommImpl>(waiting_synchro);
427
428     if (comm != nullptr)
429       comms.remove(comm);
430
431     waiting_synchro = nullptr;
432   }
433 }
434
435 void ActorImpl::simcall_answer()
436 {
437   if (this != simix_global->maestro_process){
438     XBT_DEBUG("Answer simcall %s (%d) issued by %s (%p)", SIMIX_simcall_name(simcall.call_), (int)simcall.call_,
439               get_cname(), this);
440     simcall.call_ = SIMCALL_NONE;
441     xbt_assert(not XBT_LOG_ISENABLED(simix_process, xbt_log_priority_debug) ||
442                    std::find(begin(simix_global->actors_to_run), end(simix_global->actors_to_run), this) ==
443                        end(simix_global->actors_to_run),
444                "Actor %p should not exist in actors_to_run!", this);
445     simix_global->actors_to_run.push_back(this);
446   }
447 }
448
449 void ActorImpl::set_host(s4u::Host* dest)
450 {
451   host_->pimpl_->remove_actor(this);
452   host_ = dest;
453   dest->pimpl_->add_actor(this);
454 }
455
456 ActorImplPtr ActorImpl::init(const std::string& name, s4u::Host* host)
457 {
458   ActorImpl* actor = new ActorImpl(xbt::string(name), host);
459   actor->set_ppid(this->pid_);
460
461   intrusive_ptr_add_ref(actor);
462   /* The on_creation() signal must be delayed until there, where the pid and everything is set */
463   s4u::Actor::on_creation(*actor->ciface());
464
465   return ActorImplPtr(actor);
466 }
467
468 ActorImpl* ActorImpl::start(const simix::ActorCode& code)
469 {
470   xbt_assert(code && host_ != nullptr, "Invalid parameters");
471
472   if (not host_->is_on()) {
473     XBT_WARN("Cannot launch actor '%s' on failed host '%s'", name_.c_str(), host_->get_cname());
474     intrusive_ptr_release(this);
475     throw simgrid::HostFailureException(XBT_THROW_POINT, "Cannot start actor on failed host.");
476   }
477
478   this->code_ = code;
479   XBT_VERB("Create context %s", get_cname());
480   context_.reset(simix_global->context_factory->create_context(simix::ActorCode(code), this));
481
482   XBT_DEBUG("Start context '%s'", get_cname());
483
484   /* Add the actor to its host's actor list */
485   host_->pimpl_->add_actor(this);
486   simix_global->process_list[pid_] = this;
487
488   /* Now insert it in the global actor list and in the actor to run list */
489   XBT_DEBUG("Inserting [%p] %s(%s) in the to_run list", this, get_cname(), host_->get_cname());
490   simix_global->actors_to_run.push_back(this);
491
492   return this;
493 }
494
495 ActorImplPtr ActorImpl::create(const std::string& name, const simix::ActorCode& code, void* data, s4u::Host* host,
496                                const std::unordered_map<std::string, std::string>* properties, ActorImpl* parent_actor)
497 {
498   XBT_DEBUG("Start actor %s@'%s'", name.c_str(), host->get_cname());
499
500   ActorImplPtr actor;
501   if (parent_actor != nullptr)
502     actor = parent_actor->init(xbt::string(name), host);
503   else
504     actor = self()->init(xbt::string(name), host);
505
506   /* actor data */
507   actor->set_user_data(data);
508
509   /* Add properties */
510   if (properties != nullptr)
511     actor->set_properties(*properties);
512
513   actor->start(code);
514
515   return actor;
516 }
517
518 void create_maestro(const std::function<void()>& code)
519 {
520   /* Create maestro actor and initialize it */
521   ActorImpl* maestro = new ActorImpl(xbt::string(""), /*host*/ nullptr);
522
523   if (not code) {
524     maestro->context_.reset(simix_global->context_factory->create_context(simix::ActorCode(), maestro));
525   } else {
526     maestro->context_.reset(simix_global->context_factory->create_maestro(simix::ActorCode(code), maestro));
527   }
528
529   maestro->simcall.issuer_      = maestro;
530   simix_global->maestro_process = maestro;
531 }
532
533 } // namespace actor
534 } // namespace kernel
535 } // namespace simgrid
536
537 int SIMIX_process_count() // XBT_ATTRIB_DEPRECATED_v329
538 {
539   return simix_global->process_list.size();
540 }
541
542 // XBT_DEPRECATED_v329
543 void* SIMIX_process_self_get_data()
544 {
545   smx_actor_t self = simgrid::kernel::actor::ActorImpl::self();
546
547   if (self == nullptr) {
548     return nullptr;
549   }
550   return self->get_user_data();
551 }
552
553 // XBT_DEPRECATED_v329
554 void SIMIX_process_self_set_data(void* data)
555 {
556   simgrid::kernel::actor::ActorImpl::self()->set_user_data(data);
557 }
558
559 /* needs to be public and without simcall because it is called
560    by exceptions and logging events */
561 const char* SIMIX_process_self_get_name()
562 {
563   return SIMIX_is_maestro() ? "maestro" : simgrid::kernel::actor::ActorImpl::self()->get_cname();
564 }
565
566 /**
567  * @brief Calling this function makes the process to yield.
568  *
569  * Only the current process can call this function, giving back the control to maestro.
570  *
571  * @param self the current process
572  */
573
574 /** @brief Returns the process from PID. */
575 smx_actor_t SIMIX_process_from_PID(aid_t PID)
576 {
577   auto item = simix_global->process_list.find(PID);
578   if (item == simix_global->process_list.end()) {
579     for (auto& a : simix_global->actors_to_destroy)
580       if (a.get_pid() == PID)
581         return &a;
582     return nullptr; // Not found, even in the trash
583   }
584   return item->second;
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 /** @brief Restart a process, starting it again from the beginning. */
595 /**
596  * @ingroup simix_process_management
597  * @brief Creates and runs a new SIMIX process.
598  *
599  * The structure and the corresponding thread are created and put in the list of ready processes.
600  *
601  * @param name a name for the process. It is for user-level information and can be nullptr.
602  * @param code the main function of the process
603  * @param data a pointer to any data one may want to attach to the new object. It is for user-level information and can
604  * be nullptr.
605  * It can be retrieved with the method ActorImpl::getUserData().
606  * @param host where the new agent is executed.
607  * @param properties the properties of the process
608  */
609 smx_actor_t simcall_process_create(const std::string& name, const simgrid::simix::ActorCode& code, void* data,
610                                    sg_host_t host, std::unordered_map<std::string, std::string>* properties)
611 {
612   smx_actor_t self = simgrid::kernel::actor::ActorImpl::self();
613   return simgrid::kernel::actor::simcall([&name, &code, data, host, properties, self] {
614     return simgrid::kernel::actor::ActorImpl::create(name, code, data, host, properties, self).get();
615   });
616 }
617
618 void simcall_process_set_data(smx_actor_t process, void* data)
619 {
620   simgrid::kernel::actor::simcall([process, data] { process->set_user_data(data); });
621 }