Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge branch 'master' of git+ssh://scm.gforge.inria.fr//gitroot/simgrid/simgrid
[simgrid.git] / src / s4u / s4u_actor.cpp
1 /* Copyright (c) 2006-2018. 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 "xbt/log.h"
7
8 #include "simgrid/s4u/Actor.hpp"
9 #include "simgrid/s4u/Comm.hpp"
10 #include "simgrid/s4u/Exec.hpp"
11 #include "simgrid/s4u/Host.hpp"
12 #include "simgrid/s4u/Mailbox.hpp"
13
14 #include "src/kernel/context/Context.hpp"
15 #include "src/simix/smx_private.hpp"
16
17 #include <sstream>
18
19 XBT_LOG_NEW_DEFAULT_CATEGORY(s4u_actor, "S4U actors");
20
21 namespace simgrid {
22 namespace s4u {
23
24 simgrid::xbt::signal<void(simgrid::s4u::ActorPtr)> s4u::Actor::onCreation;
25 simgrid::xbt::signal<void(simgrid::s4u::ActorPtr)> s4u::Actor::onDestruction;
26
27 // ***** Actor creation *****
28 ActorPtr Actor::self()
29 {
30   smx_context_t self_context = SIMIX_context_self();
31   if (self_context == nullptr)
32     return simgrid::s4u::ActorPtr();
33
34   return self_context->process()->iface();
35 }
36
37 ActorPtr Actor::createActor(const char* name, s4u::Host* host, std::function<void()> code)
38 {
39   simgrid::simix::ActorImpl* actor = simcall_process_create(name, std::move(code), nullptr, host, nullptr);
40   return actor->iface();
41 }
42
43 ActorPtr Actor::createActor(const char* name, s4u::Host* host, const char* function, std::vector<std::string> args)
44 {
45   simgrid::simix::ActorCodeFactory& factory = SIMIX_get_actor_code_factory(function);
46   simgrid::simix::ActorCode code = factory(std::move(args));
47   simgrid::simix::ActorImpl* actor          = simcall_process_create(name, std::move(code), nullptr, host, nullptr);
48   return actor->iface();
49 }
50
51 void intrusive_ptr_add_ref(Actor* actor)
52 {
53   intrusive_ptr_add_ref(actor->pimpl_);
54 }
55 void intrusive_ptr_release(Actor* actor)
56 {
57   intrusive_ptr_release(actor->pimpl_);
58 }
59
60 // ***** Actor methods *****
61
62 void Actor::join() {
63   simcall_process_join(this->pimpl_, -1);
64 }
65
66 void Actor::join(double timeout)
67 {
68   simcall_process_join(this->pimpl_, timeout);
69 }
70
71 void Actor::setAutoRestart(bool autorestart) {
72   simgrid::simix::kernelImmediate([this, autorestart]() { pimpl_->auto_restart = autorestart; });
73 }
74
75 void Actor::onExit(int_f_pvoid_pvoid_t fun, void* data)
76 {
77   simcall_process_on_exit(pimpl_, fun, data);
78 }
79
80 /** @brief Moves the actor to another host
81  *
82  * If the actor is currently blocked on an execution activity, the activity is also
83  * migrated to the new host. If it's blocked on another kind of activity, an error is
84  * raised as the mandated code is not written yet. Please report that bug if you need it.
85  *
86  * Asynchronous activities started by the actor are not migrated automatically, so you have
87  * to take care of this yourself (only you knows which ones should be migrated).
88  */
89 void Actor::migrate(Host* new_host)
90 {
91   std::string key;
92   simgrid::instr::LinkType* link = nullptr;
93   if (TRACE_actor_is_enabled()) {
94     static long long int counter = 0;
95
96     key = std::to_string(counter);
97     counter++;
98
99     // start link
100     container_t actor_container = simgrid::instr::Container::byName(instr_pid(this));
101     link                        = simgrid::instr::Container::getRoot()->getLink("ACTOR_LINK");
102     link->startEvent(actor_container, "M", key);
103
104     // destroy existing container of this process
105     actor_container->removeFromParent();
106   }
107
108   simgrid::simix::kernelImmediate([this, new_host]() {
109     if (pimpl_->waiting_synchro != nullptr) {
110       // The actor is blocked on an activity. If it's an exec, migrate it too.
111       // FIXME: implement the migration of other kind of activities
112       simgrid::kernel::activity::ExecImplPtr exec =
113           boost::dynamic_pointer_cast<simgrid::kernel::activity::ExecImpl>(pimpl_->waiting_synchro);
114       xbt_assert(exec.get() != nullptr, "We can only migrate blocked actors when they are blocked on executions.");
115       exec->migrate(new_host);
116     }
117     SIMIX_process_change_host(this->pimpl_, new_host);
118   });
119
120   if (TRACE_actor_is_enabled()) {
121     // create new container on the new_host location
122     new simgrid::instr::Container(instr_pid(this), "ACTOR", simgrid::instr::Container::byName(new_host->getName()));
123
124     // end link
125     link->endEvent(simgrid::instr::Container::byName(instr_pid(this)), "M", key);
126   }
127 }
128
129 s4u::Host* Actor::getHost()
130 {
131   return this->pimpl_->host;
132 }
133
134 void Actor::daemonize()
135 {
136   simgrid::simix::kernelImmediate([this]() { pimpl_->daemonize(); });
137 }
138
139 bool Actor::isDaemon()
140 {
141   return this->pimpl_->isDaemon();
142 }
143
144 const simgrid::xbt::string& Actor::getName() const
145 {
146   return this->pimpl_->getName();
147 }
148
149 const char* Actor::getCname() const
150 {
151   return this->pimpl_->getCname();
152 }
153
154 aid_t Actor::getPid()
155 {
156   return this->pimpl_->pid;
157 }
158
159 aid_t Actor::getPpid()
160 {
161   return this->pimpl_->ppid;
162 }
163
164 void Actor::suspend()
165 {
166   if (TRACE_actor_is_enabled())
167     simgrid::instr::Container::byName(instr_pid(this))->getState("ACTOR_STATE")->pushEvent("suspend");
168
169   simcall_process_suspend(pimpl_);
170 }
171
172 void Actor::resume()
173 {
174   simgrid::simix::kernelImmediate([this] { pimpl_->resume(); });
175   if (TRACE_actor_is_enabled())
176     simgrid::instr::Container::byName(instr_pid(this))->getState("ACTOR_STATE")->popEvent();
177 }
178
179 int Actor::isSuspended()
180 {
181   return simgrid::simix::kernelImmediate([this] { return pimpl_->suspended; });
182 }
183
184 void Actor::setKillTime(double time) {
185   simcall_process_set_kill_time(pimpl_,time);
186 }
187
188 /** \brief Get the kill time of an actor(or 0 if unset). */
189 double Actor::getKillTime()
190 {
191   return SIMIX_timer_get_date(pimpl_->kill_timer);
192 }
193
194 void Actor::kill(aid_t pid)
195 {
196   smx_actor_t killer  = SIMIX_process_self();
197   smx_actor_t process = SIMIX_process_from_PID(pid);
198   if(process != nullptr) {
199     simgrid::simix::kernelImmediate([killer, process] { SIMIX_process_kill(process, killer); });
200   } else {
201     std::ostringstream oss;
202     oss << "kill: (" << pid << ") - No such actor" << std::endl;
203     throw std::runtime_error(oss.str());
204   }
205 }
206
207 void Actor::kill() {
208   smx_actor_t process = SIMIX_process_self();
209   simgrid::simix::kernelImmediate(
210       [this, process] { SIMIX_process_kill(pimpl_, (pimpl_ == simix_global->maestro_process) ? pimpl_ : process); });
211 }
212
213 smx_actor_t Actor::getImpl()
214 {
215   return pimpl_;
216 }
217
218 // ***** Static functions *****
219
220 ActorPtr Actor::byPid(aid_t pid)
221 {
222   smx_actor_t process = SIMIX_process_from_PID(pid);
223   if (process != nullptr)
224     return process->iface();
225   else
226     return ActorPtr();
227 }
228
229 void Actor::killAll()
230 {
231   simcall_process_killall();
232 }
233
234 std::map<std::string, std::string>* Actor::getProperties()
235 {
236   return simgrid::simix::kernelImmediate([this] { return this->pimpl_->getProperties(); });
237 }
238
239 /** Retrieve the property value (or nullptr if not set) */
240 const char* Actor::getProperty(const char* key)
241 {
242   return simgrid::simix::kernelImmediate([this, key] { return pimpl_->getProperty(key); });
243 }
244
245 void Actor::setProperty(const char* key, const char* value)
246 {
247   simgrid::simix::kernelImmediate([this, key, value] { pimpl_->setProperty(key, value); });
248 }
249
250 Actor* Actor::restart()
251 {
252   return simgrid::simix::kernelImmediate([this]() { return pimpl_->restart(); });
253 }
254
255 // ***** this_actor *****
256
257 namespace this_actor {
258
259 /** Returns true if run from the kernel mode, and false if run from a real actor
260  *
261  * Everything that is run out of any actor (simulation setup before the engine is run,
262  * computing the model evolutions as a result to the actors' action, etc) is run in
263  * kernel mode, just as in any operating systems.
264  *
265  * In SimGrid, the actor in charge of doing the stuff in kernel mode is called Maestro,
266  * because it is the one scheduling when the others should move or wait.
267  */
268 bool isMaestro()
269 {
270   smx_actor_t process = SIMIX_process_self();
271   return process == nullptr || process == simix_global->maestro_process;
272 }
273
274 void sleep_for(double duration)
275 {
276   if (duration > 0)
277     simcall_process_sleep(duration);
278 }
279
280 void yield()
281 {
282   simgrid::simix::kernelImmediate([] { /* do nothing*/ });
283 }
284
285 XBT_PUBLIC void sleep_until(double timeout)
286 {
287   double now = SIMIX_get_clock();
288   if (timeout > now)
289     simcall_process_sleep(timeout - now);
290 }
291
292 void execute(double flops)
293 {
294   smx_activity_t s = simcall_execution_start(nullptr, flops, 1.0 /*priority*/, 0. /*bound*/, getHost());
295   simcall_execution_wait(s);
296 }
297
298 void execute(double flops, double priority)
299 {
300   smx_activity_t s = simcall_execution_start(nullptr, flops, 1 / priority /*priority*/, 0. /*bound*/, getHost());
301   simcall_execution_wait(s);
302 }
303
304 void parallel_execute(int host_nb, sg_host_t* host_list, double* flops_amount, double* bytes_amount, double timeout)
305 {
306   smx_activity_t s =
307       simcall_execution_parallel_start(nullptr, host_nb, host_list, flops_amount, bytes_amount, -1, timeout);
308   simcall_execution_wait(s);
309 }
310
311 void parallel_execute(int host_nb, sg_host_t* host_list, double* flops_amount, double* bytes_amount)
312 {
313   smx_activity_t s = simcall_execution_parallel_start(nullptr, host_nb, host_list, flops_amount, bytes_amount, -1, -1);
314   simcall_execution_wait(s);
315 }
316
317 ExecPtr exec_init(double flops_amount)
318 {
319   ExecPtr res        = ExecPtr(new Exec());
320   res->host_         = getHost();
321   res->flops_amount_ = flops_amount;
322   res->setRemains(flops_amount);
323   return res;
324 }
325
326 ExecPtr exec_async(double flops)
327 {
328   ExecPtr res = exec_init(flops);
329   res->start();
330   return res;
331 }
332
333 aid_t getPid()
334 {
335   return SIMIX_process_self()->pid;
336 }
337
338 aid_t getPpid()
339 {
340   return SIMIX_process_self()->ppid;
341 }
342
343 std::string getName()
344 {
345   return SIMIX_process_self()->getName();
346 }
347
348 const char* getCname()
349 {
350   return SIMIX_process_self()->getCname();
351 }
352
353 Host* getHost()
354 {
355   return SIMIX_process_self()->host;
356 }
357
358 void suspend()
359 {
360   if (TRACE_actor_is_enabled())
361     instr::Container::byName(getName() + "-" + std::to_string(getPid()))->getState("ACTOR_STATE")->pushEvent("suspend");
362   simcall_process_suspend(SIMIX_process_self());
363 }
364
365 void resume()
366 {
367   smx_actor_t process = SIMIX_process_self();
368   simgrid::simix::kernelImmediate([process] { process->resume(); });
369
370   if (TRACE_actor_is_enabled())
371     instr::Container::byName(getName() + "-" + std::to_string(getPid()))->getState("ACTOR_STATE")->popEvent();
372 }
373
374 bool isSuspended()
375 {
376   smx_actor_t process = SIMIX_process_self();
377   return simgrid::simix::kernelImmediate([process] { return process->suspended; });
378 }
379
380 void kill()
381 {
382   smx_actor_t process = SIMIX_process_self();
383   simgrid::simix::kernelImmediate([process] { SIMIX_process_kill(process, process); });
384 }
385
386 void onExit(int_f_pvoid_pvoid_t fun, void* data)
387 {
388   simcall_process_on_exit(SIMIX_process_self(), fun, data);
389 }
390
391 /** @brief Moves the current actor to another host
392  *
393  * @see simgrid::s4u::Actor::migrate() for more information
394  */
395 void migrate(Host* new_host)
396 {
397   SIMIX_process_self()->iface()->migrate(new_host);
398 }
399 } // namespace this_actor
400 } // namespace s4u
401 } // namespace simgrid
402
403 /* **************************** Public C interface *************************** */
404 SG_BEGIN_DECL()
405 /** \ingroup m_actor_management
406  * \brief Returns the process ID of \a actor.
407  *
408  * This function checks whether \a actor is a valid pointer and return its PID (or 0 in case of problem).
409  */
410 int sg_actor_get_PID(sg_actor_t actor)
411 {
412   /* Do not raise an exception here: this function is called by the logs
413    * and the exceptions, so it would be called back again and again */
414   if (actor == nullptr || actor->getImpl() == nullptr)
415     return 0;
416   return actor->getPid();
417 }
418
419 /** \ingroup m_actor_management
420  * \brief Returns the process ID of the parent of \a actor.
421  *
422  * This function checks whether \a actor is a valid pointer and return its parent's PID.
423  * Returns -1 if the actor has not been created by any other actor.
424  */
425 int sg_actor_get_PPID(sg_actor_t actor)
426 {
427   return actor->getPpid();
428 }
429
430 /** \ingroup m_actor_management
431  * \brief Return the name of an actor.
432  */
433 const char* sg_actor_get_name(sg_actor_t actor)
434 {
435   return actor->getCname();
436 }
437
438 sg_host_t sg_actor_get_host(sg_actor_t actor)
439 {
440   return actor->getHost();
441 }
442
443 /** \ingroup m_actor_management
444  * \brief Returns the value of a given actor property
445  *
446  * \param actor an actor
447  * \param name a property name
448  * \return value of a property (or nullptr if the property is not set)
449  */
450 const char* sg_actor_get_property_value(sg_actor_t actor, const char* name)
451 {
452   return actor->getProperty(name);
453 }
454
455 /** \ingroup m_actor_management
456  * \brief Return the list of properties
457  *
458  * This function returns all the parameters associated with an actor
459  */
460 xbt_dict_t sg_actor_get_properties(sg_actor_t actor)
461 {
462   xbt_assert(actor != nullptr, "Invalid parameter: First argument must not be nullptr");
463   xbt_dict_t as_dict = xbt_dict_new_homogeneous(xbt_free_f);
464   std::map<std::string, std::string>* props = actor->getProperties();
465   if (props == nullptr)
466     return nullptr;
467   for (auto const& elm : *props) {
468     xbt_dict_set(as_dict, elm.first.c_str(), xbt_strdup(elm.second.c_str()), nullptr);
469   }
470   return as_dict;
471 }
472
473 /** \ingroup m_actor_management
474  * \brief Suspend the actor.
475  *
476  * This function suspends the actor by suspending the task on which it was waiting for the completion.
477  */
478 void sg_actor_suspend(sg_actor_t actor)
479 {
480   xbt_assert(actor != nullptr, "Invalid parameter: First argument must not be nullptr");
481   actor->suspend();
482 }
483
484 /** \ingroup m_actor_management
485  * \brief Resume a suspended actor.
486  *
487  * This function resumes a suspended actor by resuming the task on which it was waiting for the completion.
488  */
489 void sg_actor_resume(sg_actor_t actor)
490 {
491   xbt_assert(actor != nullptr, "Invalid parameter: First argument must not be nullptr");
492   actor->resume();
493 }
494
495 /** \ingroup m_actor_management
496  * \brief Returns true if the actor is suspended .
497  *
498  * This checks whether an actor is suspended or not by inspecting the task on which it was waiting for the completion.
499  */
500 int sg_actor_is_suspended(sg_actor_t actor)
501 {
502   return actor->isSuspended();
503 }
504
505 /**
506  * \ingroup m_actor_management
507  * \brief Restarts an actor from the beginning.
508  */
509 sg_actor_t sg_actor_restart(sg_actor_t actor)
510 {
511   return actor->restart();
512 }
513
514 /** @ingroup m_actor_management
515  * @brief This actor will be terminated automatically when the last non-daemon actor finishes
516  */
517 void sg_actor_daemonize(sg_actor_t actor)
518 {
519   actor->daemonize();
520 }
521
522 /** \ingroup m_process_management
523  * \brief Migrates an actor to another location.
524  *
525  * This function changes the value of the #sg_host_t on  which \a actor is running.
526  */
527 void sg_actor_migrate(sg_actor_t process, sg_host_t host)
528 {
529   process->migrate(host);
530 }
531
532 SG_END_DECL()