Logo AND Algorithmique Numérique Distribuée

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