Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Use std::function for Comm callbacks.
[simgrid.git] / src / kernel / activity / CommImpl.cpp
1 /* Copyright (c) 2007-2022. 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/kernel/routing/NetPoint.hpp>
8 #include <simgrid/modelchecker.h>
9 #include <simgrid/s4u/Host.hpp>
10
11 #define SIMIX_H_NO_DEPRECATED_WARNING // avoid deprecation warning on include (remove with XBT_ATTRIB_DEPRECATED_v333)
12 #include <simgrid/simix.h>
13
14 #include "src/kernel/activity/CommImpl.hpp"
15 #include "src/kernel/activity/MailboxImpl.hpp"
16 #include "src/kernel/actor/SimcallObserver.hpp"
17 #include "src/kernel/context/Context.hpp"
18 #include "src/kernel/resource/CpuImpl.hpp"
19 #include "src/kernel/resource/LinkImpl.hpp"
20 #include "src/kernel/resource/StandardLinkImpl.hpp"
21 #include "src/mc/mc_replay.hpp"
22
23 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(ker_network, kernel, "Kernel network-related synchronization");
24
25 /******************************************************************************/
26 /*                    SIMIX_comm_copy_data callbacks                       */
27 /******************************************************************************/
28 // XBT_ATTRIB_DEPRECATED_v333
29 void SIMIX_comm_set_copy_data_callback(void (*callback)(simgrid::kernel::activity::CommImpl*, void*, size_t))
30 {
31   simgrid::kernel::activity::CommImpl::set_copy_data_callback(callback);
32 }
33
34 // XBT_ATTRIB_DEPRECATED_v333
35 void SIMIX_comm_copy_buffer_callback(simgrid::kernel::activity::CommImpl* comm, void* buff, size_t buff_size)
36 {
37   simgrid::s4u::Comm::copy_buffer_callback(comm, buff, buff_size);
38 }
39
40 // XBT_ATTRIB_DEPRECATED_v333
41 void SIMIX_comm_copy_pointer_callback(simgrid::kernel::activity::CommImpl* comm, void* buff, size_t buff_size)
42 {
43   simgrid::s4u::Comm::copy_pointer_callback(comm, buff, buff_size);
44 }
45
46 namespace simgrid {
47 namespace kernel {
48 namespace activity {
49 xbt::signal<void(CommImpl const&)> CommImpl::on_start;
50 xbt::signal<void(CommImpl const&)> CommImpl::on_completion;
51
52 std::function<void(CommImpl*, void*, size_t)> CommImpl::copy_data_callback_ = &s4u::Comm::copy_pointer_callback;
53
54 void CommImpl::set_copy_data_callback(const std::function<void(CommImpl*, void*, size_t)>& callback)
55 {
56   copy_data_callback_ = callback;
57 }
58
59 CommImpl& CommImpl::set_type(CommImplType type)
60 {
61   type_ = type;
62   return *this;
63 }
64
65 CommImpl& CommImpl::set_source(s4u::Host* from)
66 {
67   from_ = from;
68   return *this;
69 }
70
71 CommImpl& CommImpl::set_destination(s4u::Host* to)
72 {
73   to_ = to;
74   return *this;
75 }
76
77 CommImpl& CommImpl::set_size(double size)
78 {
79   size_ = size;
80   return *this;
81 }
82
83 CommImpl& CommImpl::set_rate(double rate)
84 {
85   rate_ = rate;
86   return *this;
87 }
88 CommImpl& CommImpl::set_mailbox(MailboxImpl* mbox)
89 {
90   if (mbox != nullptr)
91     mbox_id_ = mbox->get_id();
92   mbox_ = mbox;
93   return *this;
94 }
95
96 CommImpl& CommImpl::set_src_buff(unsigned char* buff, size_t size)
97 {
98   src_buff_      = buff;
99   src_buff_size_ = size;
100   return *this;
101 }
102
103 CommImpl& CommImpl::set_dst_buff(unsigned char* buff, size_t* size)
104 {
105   dst_buff_      = buff;
106   dst_buff_size_ = size;
107   return *this;
108 }
109
110 CommImpl& CommImpl::detach()
111 {
112   detached_ = true;
113   return *this;
114 }
115
116 CommImpl::~CommImpl()
117 {
118   XBT_DEBUG("Really free communication %p in state %s (detached = %d)", this, get_state_str(), detached_);
119
120   cleanup_surf();
121
122   if (detached_ && get_state() != State::DONE) {
123     /* the communication has failed and was detached:
124      * we have to free the buffer */
125     if (clean_fun)
126       clean_fun(src_buff_);
127     src_buff_ = nullptr;
128   } else if (mbox_) {
129     mbox_->remove(this);
130   }
131 }
132
133 /**  @brief Starts the simulation of a communication synchro. */
134 CommImpl* CommImpl::start()
135 {
136   /* If both the sender and the receiver are already there, start the communication */
137   if (get_state() == State::READY) {
138     from_ = from_ != nullptr ? from_ : src_actor_->get_host();
139     xbt_assert(from_->is_on());
140     to_   = to_ != nullptr ? to_ : dst_actor_->get_host();
141     xbt_assert(to_->is_on());
142
143     /* Getting the network_model from the origin host
144      * Valid while we have a single network model, otherwise we would need to change this function to first get the
145      * routes and later create the respective surf actions */
146     auto net_model = from_->get_netpoint()->get_englobing_zone()->get_network_model();
147
148     surf_action_ = net_model->communicate(from_, to_, size_, rate_);
149     surf_action_->set_activity(this);
150     surf_action_->set_category(get_tracing_category());
151     set_start_time(surf_action_->get_start_time());
152     set_state(State::RUNNING);
153     on_start(*this);
154
155     XBT_DEBUG("Starting communication %p from '%s' to '%s' (surf_action: %p; state: %s)", this, from_->get_cname(),
156               to_->get_cname(), surf_action_, get_state_str());
157
158     /* If a link is failed, detect it immediately */
159     if (surf_action_->get_state() == resource::Action::State::FAILED) {
160       XBT_DEBUG("Communication from '%s' to '%s' failed to start because of a link failure", from_->get_cname(),
161                 to_->get_cname());
162       set_state(State::LINK_FAILURE);
163       post();
164
165     } else if ((src_actor_ != nullptr && src_actor_->is_suspended()) ||
166                (dst_actor_ != nullptr && dst_actor_->is_suspended())) {
167       /* If any of the actor is suspended, create the synchro but stop its execution,
168          it will be restarted when the sender actor resume */
169       if (src_actor_->is_suspended())
170         XBT_DEBUG("The communication is suspended on startup because src (%s@%s) was suspended since it initiated the "
171                   "communication",
172                   src_actor_->get_cname(), src_actor_->get_host()->get_cname());
173       else
174         XBT_DEBUG("The communication is suspended on startup because dst (%s@%s) was suspended since it initiated the "
175                   "communication",
176                   dst_actor_->get_cname(), dst_actor_->get_host()->get_cname());
177
178       surf_action_->suspend();
179     }
180   }
181
182   return this;
183 }
184
185 std::vector<s4u::Link*> CommImpl::get_traversed_links() const
186 {
187   xbt_assert(get_state() != State::WAITING, "You cannot use %s() if your communication is not ready (%s)", __FUNCTION__,
188              get_state_str());
189   std::vector<s4u::Link*> vlinks;
190   XBT_ATTRIB_UNUSED double res = 0;
191   from_->route_to(to_, vlinks, &res);
192   return vlinks;
193 }
194
195 /** @brief Copy the communication data from the sender's buffer to the receiver's one  */
196 void CommImpl::copy_data()
197 {
198   size_t buff_size = src_buff_size_;
199   /* If there is no data to copy then return */
200   if (not src_buff_ || not dst_buff_ || copied_)
201     return;
202
203   XBT_DEBUG("Copying comm %p data from %s (%p) -> %s (%p) (%zu bytes)", this,
204             src_actor_ ? src_actor_->get_host()->get_cname() : "a finished actor", src_buff_,
205             dst_actor_ ? dst_actor_->get_host()->get_cname() : "a finished actor", dst_buff_, buff_size);
206
207   /* Copy at most dst_buff_size bytes of the message to receiver's buffer */
208   if (dst_buff_size_) {
209     buff_size = std::min(buff_size, *dst_buff_size_);
210
211     /* Update the receiver's buffer size to the copied amount */
212     *dst_buff_size_ = buff_size;
213   }
214
215   if (buff_size > 0) {
216     if (copy_data_fun)
217       copy_data_fun(this, src_buff_, buff_size);
218     else
219       copy_data_callback_(this, src_buff_, buff_size);
220   }
221
222   /* Set the copied flag so we copy data only once */
223   /* (this function might be called from both communication ends) */
224   copied_ = true;
225 }
226
227 ActivityImplPtr CommImpl::isend(actor::CommIsendSimcall* observer)
228 {
229   auto* mbox = observer->get_mailbox();
230   XBT_DEBUG("send from mailbox %p", mbox);
231
232   /* Prepare a synchro describing us, so that it gets passed to the user-provided filter of other side */
233   CommImplPtr this_comm(new CommImpl());
234   this_comm->set_type(CommImplType::SEND);
235
236   /* Look for communication synchro matching our needs. We also provide a description of
237    * ourself so that the other side also gets a chance of choosing if it wants to match with us.
238    *
239    * If it is not found then push our communication into the rendez-vous point */
240   CommImplPtr other_comm =
241       mbox->find_matching_comm(CommImplType::RECEIVE, observer->get_match_fun(), observer->get_payload(), this_comm,
242                                /*done*/ false, /*remove_matching*/ true);
243
244   if (not other_comm) {
245     other_comm = std::move(this_comm);
246
247     if (mbox->is_permanent()) {
248       // this mailbox is for small messages, which have to be sent right now
249       other_comm->set_state(State::READY);
250       other_comm->dst_actor_ = mbox->get_permanent_receiver().get();
251       mbox->push_done(other_comm);
252       XBT_DEBUG("pushing a message into the permanent receive list %p, comm %p", mbox, other_comm.get());
253
254     } else {
255       mbox->push(other_comm);
256     }
257   } else {
258     XBT_DEBUG("Receive already pushed");
259
260     other_comm->set_state(State::READY);
261   }
262   observer->set_comm(other_comm.get());
263
264   if (observer->is_detached()) {
265     other_comm->detach();
266     other_comm->clean_fun = observer->get_clean_fun();
267   } else {
268     other_comm->clean_fun = nullptr;
269     observer->get_issuer()->activities_.emplace_back(other_comm);
270   }
271
272   /* Setup the communication synchro */
273   other_comm->src_actor_ = observer->get_issuer();
274   other_comm->src_data_  = observer->get_payload();
275   (*other_comm)
276       .set_src_buff(observer->get_src_buff(), observer->get_src_buff_size())
277       .set_size(observer->get_payload_size())
278       .set_rate(observer->get_rate());
279
280   other_comm->match_fun     = observer->get_match_fun();
281   other_comm->copy_data_fun = observer->get_copy_data_fun();
282
283   if (MC_is_active() || MC_record_replay_is_active())
284     other_comm->set_state(simgrid::kernel::activity::State::RUNNING);
285   else
286     other_comm->start();
287
288   return (observer->is_detached() ? nullptr : other_comm);
289 }
290
291 ActivityImplPtr CommImpl::irecv(actor::CommIrecvSimcall* observer)
292 {
293   CommImplPtr this_synchro(new CommImpl());
294   this_synchro->set_type(CommImplType::RECEIVE);
295
296   auto* mbox = observer->get_mailbox();
297   XBT_DEBUG("recv from mbox %p. this_synchro=%p", mbox, this_synchro.get());
298
299   CommImplPtr other_comm;
300   // communication already done, get it inside the list of completed comms
301   if (mbox->is_permanent() && mbox->has_some_done_comm()) {
302     XBT_DEBUG("We have a comm that has probably already been received, trying to match it, to skip the communication");
303     // find a match in the list of already received comms
304     other_comm = mbox->find_matching_comm(CommImplType::SEND, observer->get_match_fun(), observer->get_payload(),
305                                           this_synchro, /*done*/ true, /*remove_matching*/ true);
306     // if not found, assume the receiver came first, register it to the mailbox in the classical way
307     if (not other_comm) {
308       XBT_DEBUG("We have messages in the permanent receive list, but not the one we are looking for, pushing request "
309                 "into list");
310       other_comm = std::move(this_synchro);
311       mbox->push(other_comm);
312     } else {
313       if (other_comm->surf_action_ && other_comm->get_remaining() < 1e-12) {
314         XBT_DEBUG("comm %p has been already sent, and is finished, destroy it", other_comm.get());
315         other_comm->set_state(State::DONE);
316         other_comm->set_mailbox(nullptr);
317       }
318     }
319   } else {
320     /* Prepare a comm describing us, so that it gets passed to the user-provided filter of other side */
321
322     /* Look for communication activity matching our needs. We also provide a description of
323      * ourself so that the other side also gets a chance of choosing if it wants to match with us.
324      *
325      * If it is not found then push our communication into the rendez-vous point */
326     other_comm = mbox->find_matching_comm(CommImplType::SEND, observer->get_match_fun(), observer->get_payload(),
327                                           this_synchro, /*done*/ false, /*remove_matching*/ true);
328
329     if (other_comm == nullptr) {
330       XBT_DEBUG("Receive pushed first (%zu comm enqueued so far)", mbox->size());
331       other_comm = std::move(this_synchro);
332       mbox->push(other_comm);
333     } else {
334       XBT_DEBUG("Match my %p with the existing %p", this_synchro.get(), other_comm.get());
335
336       other_comm->set_state(simgrid::kernel::activity::State::READY);
337     }
338     observer->get_issuer()->activities_.emplace_back(other_comm);
339   }
340   observer->set_comm(other_comm.get());
341
342   /* Setup communication synchro */
343   other_comm->dst_actor_ = observer->get_issuer();
344   other_comm->dst_data_  = observer->get_payload();
345   other_comm->set_dst_buff(observer->get_dst_buff(), observer->get_dst_buff_size());
346
347   if (observer->get_rate() > -1.0 && (other_comm->get_rate() < 0.0 || observer->get_rate() < other_comm->get_rate()))
348     other_comm->set_rate(observer->get_rate());
349
350   other_comm->match_fun     = observer->get_match_fun();
351   other_comm->copy_data_fun = observer->get_copy_data_fun();
352
353   if (MC_is_active() || MC_record_replay_is_active()) {
354     other_comm->set_state(State::RUNNING);
355     return other_comm;
356   }
357   other_comm->start();
358
359   return other_comm;
360 }
361
362 bool CommImpl::test(actor::ActorImpl* issuer)
363 {
364   if ((MC_is_active() || MC_record_replay_is_active()) && src_actor_ && dst_actor_)
365     set_state(State::DONE);
366   return ActivityImpl::test(issuer);
367 }
368
369 void CommImpl::wait_for(actor::ActorImpl* issuer, double timeout)
370 {
371   XBT_DEBUG("CommImpl::wait_for(%g), %p, state %s", timeout, this, get_state_str());
372
373   /* Associate this simcall to the wait synchro */
374   register_simcall(&issuer->simcall_);
375   if (MC_is_active() || MC_record_replay_is_active()) {
376     // FIXME: what about timeouts?
377     set_state(State::DONE);
378     finish();
379     return;
380   }
381   ActivityImpl::wait_for(issuer, timeout);
382 }
383
384 void CommImpl::wait_any_for(actor::ActorImpl* issuer, const std::vector<CommImpl*>& comms, double timeout)
385 {
386   std::vector<ActivityImpl*> activities(comms.begin(), comms.end());
387   ActivityImpl::wait_any_for(issuer, activities, timeout);
388 }
389
390 void CommImpl::suspend()
391 {
392   /* FIXME: shall we suspend also the timeout synchro? */
393   if (surf_action_)
394     surf_action_->suspend();
395   /* if not created yet, the action will be suspended on creation, in CommImpl::start() */
396 }
397
398 void CommImpl::resume()
399 {
400   /*FIXME: check what happen with the timeouts */
401   if (surf_action_)
402     surf_action_->resume();
403   /* in the other case, the synchro were not really suspended yet, see CommImpl::suspend() and CommImpl::start() */
404 }
405
406 void CommImpl::cancel()
407 {
408   /* if the synchro is a waiting state means that it is still in a mbox so remove from it and delete it */
409   if (get_state() == State::WAITING) {
410     if (not detached_) {
411       mbox_->remove(this);
412       set_state(State::CANCELED);
413     }
414   } else if (not MC_is_active() /* when running the MC there are no surf actions */
415              && not MC_record_replay_is_active() && (get_state() == State::READY || get_state() == State::RUNNING)) {
416     surf_action_->cancel();
417   }
418 }
419
420 /** @brief This is part of the cleanup process, probably an internal command */
421 void CommImpl::cleanup_surf()
422 {
423   clean_action();
424
425   if (src_timeout_) {
426     src_timeout_->unref();
427     src_timeout_ = nullptr;
428   }
429
430   if (dst_timeout_) {
431     dst_timeout_->unref();
432     dst_timeout_ = nullptr;
433   }
434 }
435
436 void CommImpl::post()
437 {
438   on_completion(*this);
439
440   /* Update synchro state */
441   if (src_timeout_ && src_timeout_->get_state() == resource::Action::State::FINISHED)
442     set_state(State::SRC_TIMEOUT);
443   else if (dst_timeout_ && dst_timeout_->get_state() == resource::Action::State::FINISHED)
444     set_state(State::DST_TIMEOUT);
445   else if ((from_ && not from_->is_on()) || (src_timeout_ && src_timeout_->get_state() == resource::Action::State::FAILED))
446     set_state(State::SRC_HOST_FAILURE);
447   else if ((to_ && not to_->is_on()) || (dst_timeout_ && dst_timeout_->get_state() == resource::Action::State::FAILED))
448     set_state(State::DST_HOST_FAILURE);
449   else if (surf_action_ && surf_action_->get_state() == resource::Action::State::FAILED) {
450     set_state(State::LINK_FAILURE);
451   } else if (get_state() == State::RUNNING) {
452     xbt_assert(from_ && from_->is_on());
453     xbt_assert(to_ && to_->is_on());
454     set_state(State::DONE);
455   }
456
457   XBT_DEBUG("CommImpl::post(): comm %p, state %s, src_proc %p, dst_proc %p, detached: %d", this, get_state_str(),
458             src_actor_.get(), dst_actor_.get(), detached_);
459
460   /* destroy the surf actions associated with the Simix communication */
461   cleanup_surf();
462
463   /* Answer all simcalls associated with the synchro */
464   finish();
465 }
466 void CommImpl::set_exception(actor::ActorImpl* issuer)
467 {
468   switch (get_state()) {
469     case State::FAILED:
470       issuer->exception_ = std::make_exception_ptr(NetworkFailureException(XBT_THROW_POINT, "Remote peer failed"));
471       break;
472     case State::SRC_TIMEOUT:
473       issuer->exception_ =
474           std::make_exception_ptr(TimeoutException(XBT_THROW_POINT, "Communication timeouted because of the sender"));
475       break;
476
477     case State::DST_TIMEOUT:
478       issuer->exception_ =
479           std::make_exception_ptr(TimeoutException(XBT_THROW_POINT, "Communication timeouted because of the receiver"));
480       break;
481
482     case State::SRC_HOST_FAILURE:
483       if (issuer == src_actor_)
484         issuer->context_->set_wannadie();
485       else {
486         set_state(State::FAILED);
487         issuer->exception_ = std::make_exception_ptr(NetworkFailureException(XBT_THROW_POINT, "Remote peer failed"));
488       }
489       break;
490
491     case State::DST_HOST_FAILURE:
492       if (issuer == dst_actor_)
493         issuer->context_->set_wannadie();
494       else {
495         set_state(State::FAILED);
496         issuer->exception_ = std::make_exception_ptr(NetworkFailureException(XBT_THROW_POINT, "Remote peer failed"));
497       }
498       break;
499
500     case State::LINK_FAILURE:
501       XBT_DEBUG("Link failure in synchro %p between '%s' and '%s': posting an exception to the issuer: %s (%p) "
502                 "detached:%d",
503                 this, src_actor_ ? src_actor_->get_host()->get_cname() : nullptr,
504                 dst_actor_ ? dst_actor_->get_host()->get_cname() : nullptr, issuer->get_cname(), issuer, detached_);
505       if (src_actor_ == issuer) {
506         XBT_DEBUG("I'm source");
507       } else if (dst_actor_ == issuer) {
508         XBT_DEBUG("I'm dest");
509       } else {
510         XBT_DEBUG("I'm neither source nor dest");
511       }
512       set_state(State::FAILED);
513       issuer->throw_exception(std::make_exception_ptr(NetworkFailureException(XBT_THROW_POINT, "Link failure")));
514       break;
515
516     case State::CANCELED:
517       if (issuer == dst_actor_)
518         issuer->exception_ =
519             std::make_exception_ptr(CancelException(XBT_THROW_POINT, "Communication canceled by the sender"));
520       else
521         issuer->exception_ =
522             std::make_exception_ptr(CancelException(XBT_THROW_POINT, "Communication canceled by the receiver"));
523       break;
524
525     default:
526       xbt_assert(get_state() == State::DONE, "Internal error in CommImpl::finish(): unexpected synchro state %s",
527                  get_state_str());
528   }
529 }
530
531 void CommImpl::finish()
532 {
533   XBT_DEBUG("CommImpl::finish() in state %s", get_state_str());
534   /* If the synchro is still in a rendez-vous point then remove from it */
535   if (mbox_)
536     mbox_->remove(this);
537
538   if (get_state() == State::DONE)
539     copy_data();
540
541   while (not simcalls_.empty()) {
542     actor::Simcall* simcall = simcalls_.front();
543     simcalls_.pop_front();
544
545     /* If a waitany simcall is waiting for this synchro to finish, then remove it from the other synchros in the waitany
546      * list. Afterwards, get the position of the actual synchro in the waitany list and return it as the result of the
547      * simcall */
548
549     if (simcall->call_ == actor::Simcall::Type::NONE) // FIXME: maybe a better way to handle this case
550       continue;                                       // if actor handling comm is killed
551
552     handle_activity_waitany(simcall);
553
554     /* Check out for errors */
555
556     if (not simcall->issuer_->get_host()->is_on()) {
557       simcall->issuer_->context_->set_wannadie();
558     } else {
559       // Do not answer to dying actors
560       if (not simcall->issuer_->context_->wannadie()) {
561         set_exception(simcall->issuer_);
562         simcall->issuer_->simcall_answer();
563       }
564     }
565
566     simcall->issuer_->waiting_synchro_ = nullptr;
567     simcall->issuer_->activities_.remove(this);
568     if (detached_) {
569       if (simcall->issuer_ != dst_actor_ && dst_actor_ != nullptr)
570         dst_actor_->activities_.remove(this);
571       if (simcall->issuer_ != src_actor_ && src_actor_ != nullptr)
572         src_actor_->activities_.remove(this);
573     }
574   }
575 }
576
577 } // namespace activity
578 } // namespace kernel
579 } // namespace simgrid