Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
33d319a0223dad0e49b9b374b9d7814b2fafea67
[simgrid.git] / src / s4u / s4u_Actor.cpp
1 /* Copyright (c) 2006-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 "simgrid/Exception.hpp"
7 #include "simgrid/actor.h"
8 #include "simgrid/s4u/Actor.hpp"
9 #include "simgrid/s4u/Exec.hpp"
10 #include "simgrid/s4u/Host.hpp"
11 #include "simgrid/s4u/VirtualMachine.hpp"
12 #include "src/kernel/activity/ExecImpl.hpp"
13 #include "src/simix/smx_private.hpp"
14 #include "src/surf/HostImpl.hpp"
15
16 #include <algorithm>
17 #include <sstream>
18
19 XBT_LOG_NEW_DEFAULT_CATEGORY(s4u_actor, "S4U actors");
20
21 namespace simgrid {
22 namespace s4u {
23
24 xbt::signal<void(Actor&)> s4u::Actor::on_creation;
25 xbt::signal<void(Actor const&)> s4u::Actor::on_suspend;
26 xbt::signal<void(Actor const&)> s4u::Actor::on_resume;
27 xbt::signal<void(Actor const&)> s4u::Actor::on_sleep;
28 xbt::signal<void(Actor const&)> s4u::Actor::on_wake_up;
29 xbt::signal<void(Actor const&)> s4u::Actor::on_migration_start;
30 xbt::signal<void(Actor const&)> s4u::Actor::on_migration_end;
31 xbt::signal<void(Actor const&)> s4u::Actor::on_termination;
32 xbt::signal<void(Actor const&)> s4u::Actor::on_destruction;
33
34 // ***** Actor creation *****
35 Actor* Actor::self()
36 {
37   kernel::context::Context* self_context = kernel::context::Context::self();
38   if (self_context == nullptr)
39     return nullptr;
40
41   return self_context->get_actor()->ciface();
42 }
43 ActorPtr Actor::init(const std::string& name, s4u::Host* host)
44 {
45   smx_actor_t self = SIMIX_process_self();
46   kernel::actor::ActorImpl* actor = simix::simcall([self, &name, host] { return self->init(name, host).get(); });
47   return actor->iface();
48 }
49
50 ActorPtr Actor::start(const std::function<void()>& code)
51 {
52   simgrid::simix::simcall([this, &code] { pimpl_->start(code); });
53   return this;
54 }
55
56 ActorPtr Actor::create(const std::string& name, s4u::Host* host, const std::function<void()>& code)
57 {
58   smx_actor_t self = SIMIX_process_self();
59   kernel::actor::ActorImpl* actor =
60       simix::simcall([self, &name, host, &code] { return self->init(name, host)->start(code); });
61
62   return actor->iface();
63 }
64
65 ActorPtr Actor::create(const std::string& name, s4u::Host* host, const std::string& function,
66                        std::vector<std::string> args)
67 {
68   simix::ActorCodeFactory& factory = SIMIX_get_actor_code_factory(function);
69   return create(name, host, factory(std::move(args)));
70 }
71
72 void intrusive_ptr_add_ref(Actor* actor)
73 {
74   intrusive_ptr_add_ref(actor->pimpl_);
75 }
76 void intrusive_ptr_release(Actor* actor)
77 {
78   intrusive_ptr_release(actor->pimpl_);
79 }
80 int Actor::get_refcount()
81 {
82   return pimpl_->get_refcount();
83 }
84
85 // ***** Actor methods *****
86
87 void Actor::join()
88 {
89   simcall_process_join(this->pimpl_, -1);
90 }
91
92 void Actor::join(double timeout)
93 {
94   simcall_process_join(this->pimpl_, timeout);
95 }
96
97 void Actor::set_auto_restart(bool autorestart)
98 {
99   simix::simcall([this, autorestart]() {
100     xbt_assert(autorestart && not pimpl_->has_to_auto_restart()); // FIXME: handle all cases
101     pimpl_->set_auto_restart(autorestart);
102
103     kernel::actor::ProcessArg* arg = new kernel::actor::ProcessArg(pimpl_->get_host(), pimpl_);
104     XBT_DEBUG("Adding Process %s to the actors_at_boot_ list of Host %s", arg->name.c_str(), arg->host->get_cname());
105     pimpl_->get_host()->pimpl_->actors_at_boot_.emplace_back(arg);
106   });
107 }
108
109 void Actor::on_exit(const std::function<void(int, void*)>& fun, void* data) /* deprecated */
110 {
111   on_exit([fun, data](bool failed) { fun(failed ? SMX_EXIT_FAILURE : SMX_EXIT_SUCCESS, data); });
112 }
113
114 void Actor::on_exit(const std::function<void(bool /*failed*/)>& fun) const
115 {
116   simix::simcall([this, &fun] { SIMIX_process_on_exit(pimpl_, fun); });
117 }
118
119 void Actor::migrate(Host* new_host)
120 {
121   s4u::Actor::on_migration_start(*this);
122
123   simix::simcall([this, new_host]() {
124     if (pimpl_->waiting_synchro != nullptr) {
125       // The actor is blocked on an activity. If it's an exec, migrate it too.
126       // FIXME: implement the migration of other kind of activities
127       kernel::activity::ExecImplPtr exec =
128           boost::dynamic_pointer_cast<kernel::activity::ExecImpl>(pimpl_->waiting_synchro);
129       xbt_assert(exec.get() != nullptr, "We can only migrate blocked actors when they are blocked on executions.");
130       exec->migrate(new_host);
131     }
132     this->pimpl_->set_host(new_host);
133   });
134
135   s4u::Actor::on_migration_end(*this);
136 }
137
138 s4u::Host* Actor::get_host() const
139 {
140   return this->pimpl_->get_host();
141 }
142
143 void Actor::daemonize()
144 {
145   simix::simcall([this]() { pimpl_->daemonize(); });
146 }
147
148 bool Actor::is_daemon() const
149 {
150   return this->pimpl_->is_daemon();
151 }
152
153 const simgrid::xbt::string& Actor::get_name() const
154 {
155   return this->pimpl_->get_name();
156 }
157
158 const char* Actor::get_cname() const
159 {
160   return this->pimpl_->get_cname();
161 }
162
163 aid_t Actor::get_pid() const
164 {
165   return this->pimpl_->get_pid();
166 }
167
168 aid_t Actor::get_ppid() const
169 {
170   return this->pimpl_->get_ppid();
171 }
172
173 void Actor::suspend()
174 {
175   s4u::Actor::on_suspend(*this);
176   simcall_process_suspend(pimpl_);
177 }
178
179 void Actor::resume()
180 {
181   simix::simcall([this] { pimpl_->resume(); });
182   s4u::Actor::on_resume(*this);
183 }
184
185 bool Actor::is_suspended()
186 {
187   return simix::simcall([this] { return pimpl_->is_suspended(); });
188 }
189
190 void Actor::set_kill_time(double kill_time)
191 {
192   simix::simcall([this, kill_time] { pimpl_->set_kill_time(kill_time); });
193 }
194
195 /** @brief Get the kill time of an actor(or 0 if unset). */
196 double Actor::get_kill_time()
197 {
198   return pimpl_->get_kill_time();
199 }
200
201 void Actor::kill(aid_t pid) // deprecated
202 {
203   kernel::actor::ActorImpl* killer = SIMIX_process_self();
204   kernel::actor::ActorImpl* victim = SIMIX_process_from_PID(pid);
205   if (victim != nullptr) {
206     simix::simcall([killer, victim] { killer->kill(victim); });
207   } else {
208     std::ostringstream oss;
209     oss << "kill: (" << pid << ") - No such actor" << std::endl;
210     throw std::runtime_error(oss.str());
211   }
212 }
213
214 void Actor::kill()
215 {
216   kernel::actor::ActorImpl* process = SIMIX_process_self();
217   simix::simcall([this, process] {
218     xbt_assert(pimpl_ != simix_global->maestro_process, "Killing maestro is a rather bad idea");
219     process->kill(pimpl_);
220   });
221 }
222
223 // ***** Static functions *****
224
225 ActorPtr Actor::by_pid(aid_t pid)
226 {
227   kernel::actor::ActorImpl* process = SIMIX_process_from_PID(pid);
228   if (process != nullptr)
229     return process->iface();
230   else
231     return ActorPtr();
232 }
233
234 void Actor::kill_all()
235 {
236   kernel::actor::ActorImpl* self = SIMIX_process_self();
237   simix::simcall([self] { self->kill_all(); });
238 }
239
240 const std::unordered_map<std::string, std::string>* Actor::get_properties() const
241 {
242   return pimpl_->get_properties();
243 }
244
245 /** Retrieve the property value (or nullptr if not set) */
246 const char* Actor::get_property(const std::string& key) const
247 {
248   return pimpl_->get_property(key);
249 }
250
251 void Actor::set_property(const std::string& key, const std::string& value)
252 {
253   simix::simcall([this, &key, &value] { pimpl_->set_property(key, value); });
254 }
255
256 Actor* Actor::restart()
257 {
258   return simix::simcall([this]() { return pimpl_->restart(); });
259 }
260
261 // ***** this_actor *****
262
263 namespace this_actor {
264
265 /** Returns true if run from the kernel mode, and false if run from a real actor
266  *
267  * Everything that is run out of any actor (simulation setup before the engine is run,
268  * computing the model evolutions as a result to the actors' action, etc) is run in
269  * kernel mode, just as in any operating systems.
270  *
271  * In SimGrid, the actor in charge of doing the stuff in kernel mode is called Maestro,
272  * because it is the one scheduling when the others should move or wait.
273  */
274 bool is_maestro()
275 {
276   kernel::actor::ActorImpl* process = SIMIX_process_self();
277   return process == nullptr || process == simix_global->maestro_process;
278 }
279
280 void sleep_for(double duration)
281 {
282   if (duration > 0) {
283     kernel::actor::ActorImpl* actor = SIMIX_process_self();
284     Actor::on_sleep(*actor->ciface());
285
286     simcall_process_sleep(duration);
287
288     Actor::on_wake_up(*actor->ciface());
289   }
290 }
291
292 void yield()
293 {
294   simix::simcall([] { /* do nothing*/ });
295 }
296
297 XBT_PUBLIC void sleep_until(double wakeup_time)
298 {
299   double now = SIMIX_get_clock();
300   if (wakeup_time > now)
301     sleep_for(wakeup_time - now);
302 }
303
304 void execute(double flops)
305 {
306   execute(flops, 1.0 /* priority */);
307 }
308
309 void execute(double flops, double priority)
310 {
311   exec_init(flops)->set_priority(priority)->start()->wait();
312 }
313
314 void parallel_execute(const std::vector<s4u::Host*>& hosts, const std::vector<double>& flops_amounts,
315                       const std::vector<double>& bytes_amounts)
316 {
317   parallel_execute(hosts, flops_amounts, bytes_amounts, -1);
318 }
319
320 void parallel_execute(const std::vector<s4u::Host*>& hosts, const std::vector<double>& flops_amounts,
321                       const std::vector<double>& bytes_amounts, double timeout)
322 {
323   xbt_assert(hosts.size() > 0, "Your parallel executions must span over at least one host.");
324   xbt_assert(hosts.size() == flops_amounts.size() || flops_amounts.empty(),
325              "Host count (%zu) does not match flops_amount count (%zu).", hosts.size(), flops_amounts.size());
326   xbt_assert(hosts.size() * hosts.size() == bytes_amounts.size() || bytes_amounts.empty(),
327              "bytes_amounts must be a matrix of size host_count * host_count (%zu*%zu), but it's of size %zu.",
328              hosts.size(), hosts.size(), flops_amounts.size());
329   /* Check that we are not mixing VMs and PMs in the parallel task */
330   bool is_a_vm = (nullptr != dynamic_cast<VirtualMachine*>(hosts.front()));
331   xbt_assert(std::all_of(hosts.begin(), hosts.end(),
332                          [is_a_vm](s4u::Host* elm) {
333                            bool tmp_is_a_vm = (nullptr != dynamic_cast<VirtualMachine*>(elm));
334                            return is_a_vm == tmp_is_a_vm;
335                          }),
336              "parallel_execute: mixing VMs and PMs is not supported (yet).");
337   /* checking for infinite values */
338   xbt_assert(std::all_of(flops_amounts.begin(), flops_amounts.end(), [](double elm) { return std::isfinite(elm); }),
339              "flops_amounts comprises infinite values!");
340   xbt_assert(std::all_of(bytes_amounts.begin(), bytes_amounts.end(), [](double elm) { return std::isfinite(elm); }),
341              "flops_amounts comprises infinite values!");
342
343   exec_init(hosts, flops_amounts, bytes_amounts)->set_timeout(timeout)->wait();
344 }
345
346 // deprecated
347 void parallel_execute(int host_nb, s4u::Host* const* host_list, const double* flops_amount, const double* bytes_amount,
348                       double timeout)
349 {
350   smx_activity_t s =
351       simcall_execution_parallel_start("", host_nb, host_list, flops_amount, bytes_amount, /* rate */ -1, timeout);
352   simcall_execution_wait(s);
353   delete[] flops_amount;
354   delete[] bytes_amount;
355 }
356
357 // deprecated
358 void parallel_execute(int host_nb, s4u::Host* const* host_list, const double* flops_amount, const double* bytes_amount)
359 {
360   smx_activity_t s = simcall_execution_parallel_start("", host_nb, host_list, flops_amount, bytes_amount,
361                                                       /* rate */ -1, /*timeout*/ -1);
362   simcall_execution_wait(s);
363   delete[] flops_amount;
364   delete[] bytes_amount;
365 }
366
367 ExecPtr exec_init(double flops_amount)
368 {
369   return ExecPtr(new ExecSeq(get_host(), flops_amount));
370 }
371
372 ExecPtr exec_init(const std::vector<s4u::Host*>& hosts, const std::vector<double>& flops_amounts,
373                   const std::vector<double>& bytes_amounts)
374 {
375   return ExecPtr(new ExecPar(hosts, flops_amounts, bytes_amounts));
376 }
377
378 ExecPtr exec_async(double flops)
379 {
380   ExecPtr res = exec_init(flops);
381   res->start();
382   return res;
383 }
384
385 aid_t get_pid()
386 {
387   return SIMIX_process_self()->get_pid();
388 }
389
390 aid_t get_ppid()
391 {
392   return SIMIX_process_self()->get_ppid();
393 }
394
395 std::string get_name()
396 {
397   return SIMIX_process_self()->get_name();
398 }
399
400 const char* get_cname()
401 {
402   return SIMIX_process_self()->get_cname();
403 }
404
405 Host* get_host()
406 {
407   return SIMIX_process_self()->get_host();
408 }
409
410 void suspend()
411 {
412   kernel::actor::ActorImpl* actor = SIMIX_process_self();
413   Actor::on_suspend(*actor->ciface());
414
415   simcall_process_suspend(actor);
416 }
417
418 void resume()
419 {
420   kernel::actor::ActorImpl* self = SIMIX_process_self();
421   simix::simcall([self] { self->resume(); });
422   Actor::on_resume(*self->ciface());
423 }
424
425 void exit()
426 {
427   kernel::actor::ActorImpl* self = SIMIX_process_self();
428   simgrid::simix::simcall([self] { self->exit(); });
429 }
430
431 void on_exit(const std::function<void(bool)>& fun)
432 {
433   SIMIX_process_self()->iface()->on_exit(fun);
434 }
435
436 void on_exit(const std::function<void(int, void*)>& fun, void* data) /* deprecated */
437 {
438   SIMIX_process_self()->iface()->on_exit([fun, data](bool exit) { fun(exit, data); });
439 }
440
441 /** @brief Moves the current actor to another host
442  *
443  * @see simgrid::s4u::Actor::migrate() for more information
444  */
445 void migrate(Host* new_host)
446 {
447   SIMIX_process_self()->iface()->migrate(new_host);
448 }
449
450 } // namespace this_actor
451 } // namespace s4u
452 } // namespace simgrid
453
454 /* **************************** Public C interface *************************** */
455
456 /** @ingroup m_actor_management
457  * @brief Returns the process ID of @a actor.
458  *
459  * This function checks whether @a actor is a valid pointer and return its PID (or 0 in case of problem).
460  */
461 aid_t sg_actor_get_PID(sg_actor_t actor)
462 {
463   /* Do not raise an exception here: this function is called by the logs
464    * and the exceptions, so it would be called back again and again */
465   if (actor == nullptr || actor->get_impl() == nullptr)
466     return 0;
467   return actor->get_pid();
468 }
469
470 /** @ingroup m_actor_management
471  * @brief Returns the process ID of the parent of @a actor.
472  *
473  * This function checks whether @a actor is a valid pointer and return its parent's PID.
474  * Returns -1 if the actor has not been created by any other actor.
475  */
476 aid_t sg_actor_get_PPID(sg_actor_t actor)
477 {
478   return actor->get_ppid();
479 }
480
481 /** @ingroup m_actor_management
482  *
483  * @brief Return a #sg_actor_t given its PID.
484  *
485  * This function search in the list of all the created sg_actor_t for a sg_actor_t  whose PID is equal to @a PID.
486  * If none is found, @c nullptr is returned.
487    Note that the PID are unique in the whole simulation, not only on a given host.
488  */
489 sg_actor_t sg_actor_by_PID(aid_t pid)
490 {
491   return simgrid::s4u::Actor::by_pid(pid).get();
492 }
493
494 /** @ingroup m_actor_management
495  * @brief Return the name of an actor.
496  */
497 const char* sg_actor_get_name(sg_actor_t actor)
498 {
499   return actor->get_cname();
500 }
501
502 sg_host_t sg_actor_get_host(sg_actor_t actor)
503 {
504   return actor->get_host();
505 }
506
507 /** @ingroup m_actor_management
508  * @brief Returns the value of a given actor property
509  *
510  * @param actor an actor
511  * @param name a property name
512  * @return value of a property (or nullptr if the property is not set)
513  */
514 const char* sg_actor_get_property_value(sg_actor_t actor, const char* name)
515 {
516   return actor->get_property(name);
517 }
518
519 /** @ingroup m_actor_management
520  * @brief Return the list of properties
521  *
522  * This function returns all the parameters associated with an actor
523  */
524 xbt_dict_t sg_actor_get_properties(sg_actor_t actor)
525 {
526   xbt_assert(actor != nullptr, "Invalid parameter: First argument must not be nullptr");
527   xbt_dict_t as_dict                        = xbt_dict_new_homogeneous(xbt_free_f);
528   const std::unordered_map<std::string, std::string>* props = actor->get_properties();
529   if (props == nullptr)
530     return nullptr;
531   for (auto const& kv : *props) {
532     xbt_dict_set(as_dict, kv.first.c_str(), xbt_strdup(kv.second.c_str()), nullptr);
533   }
534   return as_dict;
535 }
536
537 /** @ingroup m_actor_management
538  * @brief Suspend the actor.
539  *
540  * This function suspends the actor by suspending the task on which it was waiting for the completion.
541  */
542 void sg_actor_suspend(sg_actor_t actor)
543 {
544   xbt_assert(actor != nullptr, "Invalid parameter: First argument must not be nullptr");
545   actor->suspend();
546 }
547
548 /** @ingroup m_actor_management
549  * @brief Resume a suspended actor.
550  *
551  * This function resumes a suspended actor by resuming the task on which it was waiting for the completion.
552  */
553 void sg_actor_resume(sg_actor_t actor)
554 {
555   xbt_assert(actor != nullptr, "Invalid parameter: First argument must not be nullptr");
556   actor->resume();
557 }
558
559 /** @ingroup m_actor_management
560  * @brief Returns true if the actor is suspended .
561  *
562  * This checks whether an actor is suspended or not by inspecting the task on which it was waiting for the completion.
563  */
564 int sg_actor_is_suspended(sg_actor_t actor)
565 {
566   return actor->is_suspended();
567 }
568
569 /**
570  * @ingroup m_actor_management
571  * @brief Restarts an actor from the beginning.
572  */
573 sg_actor_t sg_actor_restart(sg_actor_t actor)
574 {
575   return actor->restart();
576 }
577
578 /**
579  * @ingroup m_actor_management
580  * @brief Sets the "auto-restart" flag of the actor.
581  * If the flag is set to 1, the actor will be automatically restarted when its host comes back up.
582  */
583 void sg_actor_set_auto_restart(sg_actor_t actor, int auto_restart)
584 {
585   actor->set_auto_restart(auto_restart);
586 }
587
588 /** @ingroup m_actor_management
589  * @brief This actor will be terminated automatically when the last non-daemon actor finishes
590  */
591 void sg_actor_daemonize(sg_actor_t actor)
592 {
593   actor->daemonize();
594 }
595
596 /** @ingroup m_actor_management
597  * @brief Migrates an actor to another location.
598  *
599  * This function changes the value of the #sg_host_t on  which @a actor is running.
600  */
601 void sg_actor_migrate(sg_actor_t process, sg_host_t host)
602 {
603   process->migrate(host);
604 }
605
606 /** @ingroup m_actor_management
607  * @brief Wait for the completion of a #sg_actor_t.
608  *
609  * @param actor the actor to wait for
610  * @param timeout wait until the actor is over, or the timeout expires
611  */
612 void sg_actor_join(sg_actor_t actor, double timeout)
613 {
614   actor->join(timeout);
615 }
616
617 void sg_actor_kill(sg_actor_t actor)
618 {
619   actor->kill();
620 }
621
622 void sg_actor_kill_all()
623 {
624   simgrid::s4u::Actor::kill_all();
625 }
626
627 /** @ingroup m_actor_management
628  * @brief Set the kill time of an actor.
629  *
630  * @param actor an actor
631  * @param kill_time the time when the actor is killed.
632  */
633 void sg_actor_set_kill_time(sg_actor_t actor, double kill_time)
634 {
635   actor->set_kill_time(kill_time);
636 }
637
638 /** Yield the current actor; let the other actors execute first */
639 void sg_actor_yield()
640 {
641   simgrid::s4u::this_actor::yield();
642 }
643
644 void sg_actor_sleep_for(double duration)
645 {
646   simgrid::s4u::this_actor::sleep_for(duration);
647 }
648
649 sg_actor_t sg_actor_attach(const char* name, void* data, sg_host_t host, xbt_dict_t properties)
650 {
651   xbt_assert(host != nullptr, "Invalid parameters: host and code params must not be nullptr");
652   std::unordered_map<std::string, std::string> props;
653   xbt_dict_cursor_t cursor = nullptr;
654   char* key;
655   char* value;
656   xbt_dict_foreach (properties, cursor, key, value)
657     props[key] = value;
658   xbt_dict_free(&properties);
659
660   /* Let's create the process: SIMIX may decide to start it right now, even before returning the flow control to us */
661   smx_actor_t actor = nullptr;
662   try {
663     actor = simgrid::kernel::actor::ActorImpl::attach(name, data, host, &props).get();
664   } catch (simgrid::HostFailureException const&) {
665     xbt_die("Could not attach");
666   }
667
668   simgrid::s4u::this_actor::yield();
669   return actor->ciface();
670 }
671
672 void sg_actor_detach()
673 {
674   simgrid::kernel::actor::ActorImpl::detach();
675 }
676
677 aid_t sg_actor_self_get_pid()
678 {
679   return simgrid::s4u::this_actor::get_pid();
680 }
681
682 aid_t sg_actor_self_get_ppid()
683 {
684   return simgrid::s4u::this_actor::get_ppid();
685 }
686
687 const char* sg_actor_self_get_name()
688 {
689   return simgrid::s4u::this_actor::get_cname();
690 }
691
692 sg_actor_t sg_actor_self()
693 {
694   return simgrid::s4u::Actor::self();
695 }
696
697 void sg_actor_self_execute(double flops)
698 {
699   simgrid::s4u::this_actor::execute(flops);
700 }
701
702 /** @brief Take an extra reference on that actor to prevent it to be garbage-collected */
703 void sg_actor_ref(sg_actor_t actor)
704 {
705   intrusive_ptr_add_ref(actor);
706 }
707 /** @brief Release a reference on that actor so that it can get be garbage-collected */
708 void sg_actor_unref(sg_actor_t actor)
709 {
710   intrusive_ptr_release(actor);
711 }