Logo AND Algorithmique Numérique Distribuée

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