Logo AND Algorithmique Numérique Distribuée

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