Logo AND Algorithmique Numérique Distribuée

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