Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
s4u::Exec now has 2 child classes
[simgrid.git] / src / msg / msg_task.cpp
1 /* Copyright (c) 2004-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 "msg_private.hpp"
7 #include "src/instr/instr_private.hpp"
8 #include <simgrid/s4u/Comm.hpp>
9 #include <simgrid/s4u/Exec.hpp>
10 #include <simgrid/s4u/Host.hpp>
11 #include <simgrid/s4u/Mailbox.hpp>
12
13 #include <algorithm>
14 #include <vector>
15
16 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(msg_task, msg, "Logging specific to MSG (task)");
17
18 namespace simgrid {
19 namespace msg {
20
21 Task::Task(std::string name, double flops_amount, double bytes_amount, void* data)
22     : name_(std::move(name)), userdata_(data), flops_amount(flops_amount), bytes_amount(bytes_amount)
23 {
24   static std::atomic_ullong counter{0};
25   id_ = counter++;
26   if (MC_is_active())
27     MC_ignore_heap(&(id_), sizeof(id_));
28 }
29
30 Task::Task(std::string name, std::vector<s4u::Host*> hosts, std::vector<double> flops_amount,
31            std::vector<double> bytes_amount, void* data)
32     : Task(std::move(name), 1.0, 0, data)
33 {
34   parallel_             = true;
35   hosts_                = std::move(hosts);
36   flops_parallel_amount = std::move(flops_amount);
37   bytes_parallel_amount = std::move(bytes_amount);
38 }
39
40 Task* Task::create(std::string name, double flops_amount, double bytes_amount, void* data)
41 {
42   return new Task(std::move(name), flops_amount, bytes_amount, data);
43 }
44
45 Task* Task::create_parallel(std::string name, int host_nb, const msg_host_t* host_list, double* flops_amount,
46                             double* bytes_amount, void* data)
47 {
48   std::vector<s4u::Host*> hosts;
49   std::vector<double> flops;
50   std::vector<double> bytes;
51
52   for (int i = 0; i < host_nb; i++) {
53     hosts.push_back(host_list[i]);
54     if (flops_amount != nullptr)
55       flops.push_back(flops_amount[i]);
56     if (bytes_amount != nullptr) {
57       for (int j = 0; j < host_nb; j++)
58         bytes.push_back(bytes_amount[host_nb * i + j]);
59     }
60   }
61   return new Task(std::move(name), std::move(hosts), std::move(flops), std::move(bytes), data);
62 }
63
64 msg_error_t Task::execute()
65 {
66   /* checking for infinite values */
67   xbt_assert(std::isfinite(flops_amount), "flops_amount is not finite!");
68
69   msg_error_t status = MSG_OK;
70   if (flops_amount <= 0.0)
71     return MSG_OK;
72
73   set_used();
74   try {
75     s4u::ExecPtr e = s4u::this_actor::exec_init(flops_amount)
76                          ->set_priority(1 / priority_)
77                          ->set_bound(bound_)
78                          ->set_tracing_category(tracing_category_)
79                          ->start();
80     compute = boost::static_pointer_cast<kernel::activity::ExecImpl>(e->get_impl());
81
82     e->wait();
83
84     set_not_used();
85     XBT_DEBUG("Execution task '%s' finished", get_cname());
86   } catch (HostFailureException& e) {
87     status = MSG_HOST_FAILURE;
88   } catch (TimeoutError& e) {
89     status = MSG_TIMEOUT;
90   } catch (CancelException& e) {
91     status = MSG_TASK_CANCELED;
92   }
93
94   /* action ended, set comm and compute = nullptr, the actions is already destroyed in the main function */
95   flops_amount = 0.0;
96   comm         = nullptr;
97   compute      = nullptr;
98
99   return status;
100 }
101
102 s4u::CommPtr Task::send_async(std::string alias, void_f_pvoid_t cleanup, bool detached)
103 {
104   if (TRACE_actor_is_enabled()) {
105     container_t process_container = simgrid::instr::Container::by_name(instr_pid(MSG_process_self()));
106     std::string key               = std::string("p") + std::to_string(get_id());
107     simgrid::instr::Container::get_root()->get_link("ACTOR_TASK_LINK")->start_event(process_container, "SR", key);
108   }
109
110   /* Prepare the task to send */
111   set_used();
112   this->comm = nullptr;
113   msg_global->sent_msg++;
114
115   s4u::CommPtr comm = s4u::Mailbox::by_name(alias)->put_init(this, bytes_amount)->set_rate(get_rate());
116   this->comm        = comm;
117
118   if (detached)
119     comm->detach(cleanup);
120   else
121     comm->start();
122
123   if (TRACE_is_enabled() && has_tracing_category())
124     simgrid::simix::simcall([comm, this] { comm->get_impl()->set_category(std::move(tracing_category_)); });
125
126   return comm;
127 }
128
129 void Task::cancel()
130 {
131   if (compute) {
132     simgrid::simix::simcall([this] { compute->cancel(); });
133   } else if (comm) {
134     comm->cancel();
135   }
136   set_not_used();
137 }
138
139 void Task::set_priority(double priority)
140 {
141   xbt_assert(std::isfinite(1.0 / priority), "priority is not finite!");
142   priority_ = 1.0 / priority;
143 }
144
145 s4u::Actor* Task::get_sender()
146 {
147   return comm ? comm->get_sender().get() : nullptr;
148 }
149
150 s4u::Host* Task::get_source()
151 {
152   return comm ? comm->get_sender()->get_host() : nullptr;
153 }
154
155 void Task::set_used()
156 {
157   if (is_used_)
158     report_multiple_use();
159   is_used_ = true;
160 }
161
162 void Task::report_multiple_use() const
163 {
164   if (msg_global->debug_multiple_use){
165     XBT_ERROR("This task is already used in there:");
166     // TODO, backtrace
167     XBT_ERROR("<missing backtrace>");
168     XBT_ERROR("And you try to reuse it from here:");
169     xbt_backtrace_display_current();
170   } else {
171     xbt_die("This task is still being used somewhere else. You cannot send it now. Go fix your code!"
172              "(use --cfg=msg/debug-multiple-use:on to get the backtrace of the other process)");
173   }
174 }
175 } // namespace msg
176 } // namespace simgrid
177
178 /********************************* Task **************************************/
179 /** @brief Creates a new task
180  *
181  * A constructor for msg_task_t taking four arguments.
182  *
183  * @param name a name for the object. It is for user-level information and can be nullptr.
184  * @param flop_amount a value of the processing amount (in flop) needed to process this new task.
185  * If 0, then it cannot be executed with MSG_task_execute(). This value has to be >=0.
186  * @param message_size a value of the amount of data (in bytes) needed to transfer this new task. If 0, then it cannot
187  * be transfered with MSG_task_send() and MSG_task_recv(). This value has to be >=0.
188  * @param data a pointer to any data may want to attach to the new object.  It is for user-level information and can
189  * be nullptr. It can be retrieved with the function @ref MSG_task_get_data.
190  * @return The new corresponding object.
191  */
192 msg_task_t MSG_task_create(const char *name, double flop_amount, double message_size, void *data)
193 {
194   return simgrid::msg::Task::create(name ? std::string(name) : "", flop_amount, message_size, data);
195 }
196
197 /** @brief Creates a new parallel task
198  *
199  * A constructor for #msg_task_t taking six arguments.
200  *
201  * \rst
202  * See :cpp:func:`void simgrid::s4u::this_actor::parallel_execute(int, s4u::Host**, double*, double*)` for
203  * the exact semantic of the parameters.
204  * \endrst
205  *
206  * @param name a name for the object. It is for user-level information and can be nullptr.
207  * @param host_nb the number of hosts implied in the parallel task.
208  * @param host_list an array of @p host_nb msg_host_t.
209  * @param flops_amount an array of @p host_nb doubles.
210  *        flops_amount[i] is the total number of operations that have to be performed on host_list[i].
211  * @param bytes_amount an array of @p host_nb* @p host_nb doubles.
212  * @param data a pointer to any data may want to attach to the new object.
213  *             It is for user-level information and can be nullptr.
214  *             It can be retrieved with the function @ref MSG_task_get_data().
215  */
216 msg_task_t MSG_parallel_task_create(const char *name, int host_nb, const msg_host_t * host_list,
217                                     double *flops_amount, double *bytes_amount, void *data)
218 {
219   // Task's flops amount is set to an arbitrary value > 0.0 to be able to distinguish, in
220   // MSG_task_get_remaining_work_ratio(), a finished task and a task that has not started yet.
221   return simgrid::msg::Task::create_parallel(name ? name : "", host_nb, host_list, flops_amount, bytes_amount, data);
222 }
223
224 /** @brief Return the user data of the given task */
225 void* MSG_task_get_data(msg_task_t task)
226 {
227   return task->get_user_data();
228 }
229
230 /** @brief Sets the user data of a given task */
231 void MSG_task_set_data(msg_task_t task, void *data)
232 {
233   task->set_user_data(data);
234 }
235
236 /** @brief Sets a function to be called when a task has just been copied.
237  * @param callback a callback function
238  */
239 void MSG_task_set_copy_callback(void (*callback) (msg_task_t task, msg_process_t sender, msg_process_t receiver)) {
240
241   msg_global->task_copy_callback = callback;
242
243   if (callback) {
244     SIMIX_comm_set_copy_data_callback(MSG_comm_copy_data_from_SIMIX);
245   } else {
246     SIMIX_comm_set_copy_data_callback(SIMIX_comm_copy_pointer_callback);
247   }
248 }
249
250 /** @brief Returns the sender of the given task */
251 msg_process_t MSG_task_get_sender(msg_task_t task)
252 {
253   return task->get_sender();
254 }
255
256 /** @brief Returns the source (the sender's host) of the given task */
257 msg_host_t MSG_task_get_source(msg_task_t task)
258 {
259   return task->get_source();
260 }
261
262 /** @brief Returns the name of the given task. */
263 const char *MSG_task_get_name(msg_task_t task)
264 {
265   return task->get_cname();
266 }
267
268 /** @brief Sets the name of the given task. */
269 void MSG_task_set_name(msg_task_t task, const char *name)
270 {
271   task->set_name(name);
272 }
273
274 /**
275  * @brief Executes a task and waits for its termination.
276  *
277  * This function is used for describing the behavior of a process. It takes only one parameter.
278  * @param task a #msg_task_t to execute on the location on which the process is running.
279  * @return #MSG_OK if the task was successfully completed, #MSG_TASK_CANCELED or #MSG_HOST_FAILURE otherwise
280  */
281 msg_error_t MSG_task_execute(msg_task_t task)
282 {
283   return task->is_parallel() ? MSG_parallel_task_execute(task) : task->execute();
284 }
285 /**
286  * @brief Sends a task on a mailbox.
287  *
288  * This is a non blocking function: use MSG_comm_wait() or MSG_comm_test() to end the communication.
289  *
290  * @param task a #msg_task_t to send on another location.
291  * @param alias name of the mailbox to sent the task to
292  * @return the msg_comm_t communication created
293  */
294 msg_comm_t MSG_task_isend(msg_task_t task, const char* alias)
295 {
296   return new simgrid::msg::Comm(task, nullptr, task->send_async(alias, nullptr, false));
297 }
298
299 /**
300  * @brief Sends a task on a mailbox with a maximum rate
301  *
302  * This is a non blocking function: use MSG_comm_wait() or MSG_comm_test() to end the communication. The maxrate
303  * parameter allows the application to limit the bandwidth utilization of network links when sending the task.
304  *
305  * @param task a #msg_task_t to send on another location.
306  * @param alias name of the mailbox to sent the task to
307  * @param maxrate the maximum communication rate for sending this task (byte/sec).
308  * @return the msg_comm_t communication created
309  */
310 msg_comm_t MSG_task_isend_bounded(msg_task_t task, const char* alias, double maxrate)
311 {
312   task->set_rate(maxrate);
313   return new simgrid::msg::Comm(task, nullptr, task->send_async(alias, nullptr, false));
314 }
315
316 /**
317  * @brief Sends a task on a mailbox.
318  *
319  * This is a non blocking detached send function.
320  * Think of it as a best effort send. Keep in mind that the third parameter is only called if the communication fails.
321  * If the communication does work, it is responsibility of the receiver code to free anything related to the task, as
322  * usual. More details on this can be obtained on
323  * <a href="http://lists.gforge.inria.fr/pipermail/simgrid-user/2011-November/002649.html">this thread</a>
324  * in the SimGrid-user mailing list archive.
325  *
326  * @param task a #msg_task_t to send on another location.
327  * @param alias name of the mailbox to sent the task to
328  * @param cleanup a function to destroy the task if the communication fails, e.g. MSG_task_destroy
329  * (if nullptr, no function will be called)
330  */
331 void MSG_task_dsend(msg_task_t task, const char* alias, void_f_pvoid_t cleanup)
332 {
333   task->send_async(alias, cleanup, true);
334 }
335
336 /**
337  * @brief Sends a task on a mailbox with a maximal rate.
338  *
339  * This is a non blocking detached send function.
340  * Think of it as a best effort send. Keep in mind that the third parameter is only called if the communication fails.
341  * If the communication does work, it is responsibility of the receiver code to free anything related to the task, as
342  * usual. More details on this can be obtained on
343  * <a href="http://lists.gforge.inria.fr/pipermail/simgrid-user/2011-November/002649.html">this thread</a>
344  * in the SimGrid-user mailing list archive.
345  *
346  * The rate parameter can be used to send a task with a limited bandwidth (smaller than the physical available value).
347  * Use MSG_task_dsend() if you don't limit the rate (or pass -1 as a rate value do disable this feature).
348  *
349  * @param task a #msg_task_t to send on another location.
350  * @param alias name of the mailbox to sent the task to
351  * @param cleanup a function to destroy the task if the communication fails, e.g. MSG_task_destroy (if nullptr, no
352  *        function will be called)
353  * @param maxrate the maximum communication rate for sending this task (byte/sec)
354  *
355  */
356 void MSG_task_dsend_bounded(msg_task_t task, const char* alias, void_f_pvoid_t cleanup, double maxrate)
357 {
358   task->set_rate(maxrate);
359   task->send_async(alias, cleanup, true);
360 }
361
362 /** @brief Destroys the given task.
363  *
364  * You should free user data, if any, @b before calling this destructor.
365  *
366  * Only the process that owns the task can destroy it.
367  * The owner changes after a successful send.
368  * If a task is successfully sent, the receiver becomes the owner and is supposed to destroy it. The sender should not
369  * use it anymore.
370  * If the task failed to be sent, the sender remains the owner of the task.
371  */
372 msg_error_t MSG_task_destroy(msg_task_t task)
373 {
374   if (task->is_used()) {
375     /* the task is being sent or executed: cancel it first */
376     task->cancel();
377   }
378
379   /* free main structures */
380   delete task;
381
382   return MSG_OK;
383 }
384
385 /** @brief Cancel the given task
386  *
387  * If it was currently executed or transfered, the working process is stopped.
388  */
389 msg_error_t MSG_task_cancel(msg_task_t task)
390 {
391   xbt_assert((task != nullptr), "Cannot cancel a nullptr task");
392   task->cancel();
393   return MSG_OK;
394 }
395
396 /** @brief Returns a value in ]0,1[ that represent the task remaining work
397  *    to do: starts at 1 and goes to 0. Returns 0 if not started or finished.
398  *
399  * It works for either parallel or sequential tasks.
400  */
401 double MSG_task_get_remaining_work_ratio(msg_task_t task) {
402
403   xbt_assert((task != nullptr), "Cannot get information from a nullptr task");
404   if (task->compute) {
405     // Task in progress
406     if (task->is_parallel())
407       return task->compute->get_par_remaining_ratio();
408     else
409       return task->compute->get_seq_remaining_ratio();
410   } else {
411     // Task not started (flops_amount is > 0.0) or finished (flops_amount is set to 0.0)
412     return task->flops_amount > 0.0 ? 1.0 : 0.0;
413   }
414 }
415
416 /** @brief Returns the amount of flops that remain to be computed
417  *
418  * The returned value is initially the cost that you defined for the task, then it decreases until it reaches 0
419  *
420  * It works for sequential tasks, but the remaining amount of work is not a scalar value for parallel tasks.
421  * So you will get an exception if you call this function on parallel tasks. Just don't do it.
422  */
423 double MSG_task_get_flops_amount(msg_task_t task) {
424   if (task->compute != nullptr) {
425     return task->compute->get_remaining();
426   } else {
427     // Not started or already done.
428     // - Before starting, flops_amount is initially the task cost
429     // - After execution, flops_amount is set to 0 (until someone uses MSG_task_set_flops_amount, if any)
430     return task->flops_amount;
431   }
432 }
433
434 /** @brief set the computation amount needed to process the given task.
435  *
436  * @warning If the computation is ongoing (already started and not finished),
437  * it is not modified by this call. Moreover, after its completion, the ongoing execution with set the flops_amount to
438  * zero, overriding any value set during the execution.
439  */
440 void MSG_task_set_flops_amount(msg_task_t task, double flops_amount)
441 {
442   task->flops_amount = flops_amount;
443 }
444
445 /** @brief set the amount data attached with the given task.
446  *
447  * @warning If the transfer is ongoing (already started and not finished), it is not modified by this call.
448  */
449 void MSG_task_set_bytes_amount(msg_task_t task, double data_size)
450 {
451   task->bytes_amount = data_size;
452 }
453
454 /** @brief Returns the total amount received by the given task
455  *
456  *  If the communication does not exist it will return 0.
457  *  So, if the communication has FINISHED or FAILED it returns zero.
458  */
459 double MSG_task_get_remaining_communication(msg_task_t task)
460 {
461   XBT_DEBUG("calling simcall_communication_get_remains(%p)", task->comm.get());
462   return task->comm->get_remaining();
463 }
464
465 /** @brief Returns the size of the data attached to the given task. */
466 double MSG_task_get_bytes_amount(msg_task_t task)
467 {
468   xbt_assert(task != nullptr, "Invalid parameter");
469   return task->bytes_amount;
470 }
471
472 /** @brief Changes the priority of a computation task.
473  *
474  * This priority doesn't affect the transfer rate. A priority of 2
475  * will make a task receive two times more cpu power than regular tasks.
476  */
477 void MSG_task_set_priority(msg_task_t task, double priority)
478 {
479   task->set_priority(priority);
480 }
481
482 /** @brief Changes the maximum CPU utilization of a computation task (in flops/s).
483  *
484  * For VMs, there is a pitfall. Please see MSG_vm_set_bound().
485  */
486 void MSG_task_set_bound(msg_task_t task, double bound)
487 {
488   if (bound < 1e-12) /* close enough to 0 without any floating precision surprise */
489     XBT_INFO("bound == 0 means no capping (i.e., unlimited).");
490   task->set_bound(bound);
491 }
492
493 /**
494  * @brief Sets the tracing category of a task.
495  *
496  * This function should be called after the creation of a MSG task, to define the category of that task. The
497  * first parameter task must contain a task that was  =created with the function #MSG_task_create. The second
498  * parameter category must contain a category that was previously declared with the function #TRACE_category
499  * (or with #TRACE_category_with_color).
500  *
501  * See @ref outcomes_vizu for details on how to trace the (categorized) resource utilization.
502  *
503  * @param task the task that is going to be categorized
504  * @param category the name of the category to be associated to the task
505  *
506  * @see MSG_task_get_category, TRACE_category, TRACE_category_with_color
507  */
508 void MSG_task_set_category(msg_task_t task, const char* category)
509 {
510   xbt_assert(not task->has_tracing_category(), "Task %p(%s) already has a category (%s).", task, task->get_cname(),
511              task->get_tracing_category().c_str());
512
513   // if user provides a nullptr category, task is no longer traced
514   if (category == nullptr) {
515     task->set_tracing_category("");
516     XBT_DEBUG("MSG task %p(%s), category removed", task, task->get_cname());
517   } else {
518     // set task category
519     task->set_tracing_category(category);
520     XBT_DEBUG("MSG task %p(%s), category %s", task, task->get_cname(), task->get_tracing_category().c_str());
521   }
522 }
523
524 /**
525  * @brief Gets the current tracing category of a task. (@see MSG_task_set_category)
526  * @param task the task to be considered
527  * @return Returns the name of the tracing category of the given task, "" otherwise
528  */
529 const char* MSG_task_get_category(msg_task_t task)
530 {
531   return task->get_tracing_category().c_str();
532 }