Logo AND Algorithmique Numérique Distribuée

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