Logo AND Algorithmique Numérique Distribuée

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