Logo AND Algorithmique Numérique Distribuée

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