Logo AND Algorithmique Numérique Distribuée

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