Logo AND Algorithmique Numérique Distribuée

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