Logo AND Algorithmique Numérique Distribuée

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