Logo AND Algorithmique Numérique Distribuée

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