Logo AND Algorithmique Numérique Distribuée

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