Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Adding integration tests of async-waitall and waitany
[simgrid.git] / examples / s4u / dht-chord / node.cpp
1 /* Copyright (c) 2010-2016. 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 "s4u_dht-chord.hpp"
7
8 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(s4u_chord);
9
10 /* Returns whether an id belongs to the interval [start, end].
11  *
12  * The parameters are normalized to make sure they are between 0 and nb_keys - 1).
13  * 1 belongs to [62, 3]
14  * 1 does not belong to [3, 62]
15  * 63 belongs to [62, 3]
16  * 63 does not belong to [3, 62]
17  * 24 belongs to [21, 29]
18  * 24 does not belong to [29, 21]
19  *
20  * \param id id to check
21  * \param start lower bound
22  * \param end upper bound
23  * \return a non-zero value if id in in [start, end]
24  */
25 static int is_in_interval(int id, int start, int end)
26 {
27   int i = id % nb_keys;
28   int s = start % nb_keys;
29   int e = end % nb_keys;
30
31   // make sure end >= start and id >= start
32   if (e < s) {
33     e += nb_keys;
34   }
35
36   if (i < s) {
37     i += nb_keys;
38   }
39
40   return i <= e;
41 }
42
43 /* Initializes the current node as the first one of the system */
44 Node::Node(std::vector<std::string> args)
45 {
46   xbt_assert(args.size() == 3 || args.size() == 5, "Wrong number of arguments for this node");
47
48   // initialize my node
49   id_                = std::stoi(args[1]);
50   stream             = simgrid::s4u::this_actor::getHost()->extension<HostChord>()->getStream();
51   mailbox_           = simgrid::s4u::Mailbox::byName(std::to_string(id_));
52   next_finger_to_fix = 0;
53   fingers_           = new int[nb_bits];
54
55   for (int i = 0; i < nb_bits; i++) {
56     fingers_[i] = id_;
57   }
58
59   if (args.size() == 3) { // first ring
60     deadline_   = std::stod(args[2]);
61     start_time_ = simgrid::s4u::Engine::getClock();
62     XBT_DEBUG("Create a new Chord ring...");
63   } else {
64     known_id_   = std::stoi(args[2]);
65     start_time_ = std::stod(args[3]);
66     deadline_   = std::stod(args[4]);
67     XBT_DEBUG("Hey! Let's join the system in %f seconds (shall leave at time %f)", start_time_,
68               start_time_ + deadline_);
69   }
70 }
71
72 Node::~Node()
73 {
74   delete[] fingers_;
75 }
76 /* Makes the current node join the ring, knowing the id of a node already in the ring
77  *
78  * \param known_id id of a node already in the ring
79  * \return true if the join operation succeeded
80  *  */
81
82 void Node::join(int known_id)
83 {
84   XBT_INFO("Joining the ring with id %d, knowing node %d", id_, known_id);
85   setPredecessor(-1); // no predecessor (yet)
86
87   int successor_id = remoteFindSuccessor(known_id, id_);
88   if (successor_id == -1) {
89     XBT_INFO("Cannot join the ring.");
90   } else {
91     setFinger(0, successor_id);
92     printFingerTable();
93     joined = true;
94   }
95 }
96
97 /* Makes the current node quit the system */
98 void Node::leave()
99 {
100   XBT_INFO("Well Guys! I Think it's time for me to leave ;)");
101   notifyAndQuit();
102   joined = false;
103 }
104
105 /* Notifies the successor and the predecessor of the current node before leaving */
106 void Node::notifyAndQuit()
107 {
108   // send the PREDECESSOR_LEAVING to our successor
109   ChordMessage* pred_msg = new ChordMessage(PREDECESSOR_LEAVING);
110   pred_msg->request_id   = pred_id_;
111   pred_msg->answer_to    = mailbox_;
112
113   XBT_DEBUG("Sending a 'PREDECESSOR_LEAVING' to my successor %d", fingers_[0]);
114   try {
115     simgrid::s4u::Mailbox::byName(std::to_string(fingers_[0]))->put(pred_msg, 10, timeout);
116   } catch (xbt_ex& e) {
117     if (e.category == timeout_error) {
118       XBT_DEBUG("Timeout expired when sending a 'PREDECESSOR_LEAVING' to my successor %d", fingers_[0]);
119       delete pred_msg;
120     }
121   }
122
123   if (pred_id_ != -1 && pred_id_ != id_) {
124     // send the SUCCESSOR_LEAVING to our predecessor (only if I have one that is not me)
125     ChordMessage* succ_msg = new ChordMessage(SUCCESSOR_LEAVING);
126     succ_msg->request_id   = fingers_[0];
127     succ_msg->answer_to    = mailbox_;
128     XBT_DEBUG("Sending a 'SUCCESSOR_LEAVING' to my predecessor %d", pred_id_);
129
130     try {
131       simgrid::s4u::Mailbox::byName(std::to_string(pred_id_))->put(succ_msg, 10, timeout);
132     } catch (xbt_ex& e) {
133       if (e.category == timeout_error) {
134         XBT_DEBUG("Timeout expired when sending a 'SUCCESSOR_LEAVING' to my predecessor %d", pred_id_);
135         delete succ_msg;
136       }
137     }
138   }
139 }
140
141 /* Performs a find successor request to a random id */
142 void Node::randomLookup()
143 {
144   int res          = id_;
145   int random_index = RngStream_RandInt(stream, 0, nb_bits - 1);
146   int random_id    = fingers_[random_index];
147   XBT_DEBUG("Making a lookup request for id %d", random_id);
148   if (random_id != id_)
149     res = findSuccessor(random_id);
150   XBT_DEBUG("The successor of node %d is %d", random_id, res);
151 }
152
153 /* Sets a finger of the current node.
154  *
155  * \param node the current node
156  * \param finger_index index of the finger to set (0 to nb_bits - 1)
157  * \param id the id to set for this finger
158  */
159 void Node::setFinger(int finger_index, int id)
160 {
161   if (id != fingers_[finger_index]) {
162     fingers_[finger_index] = id;
163     XBT_VERB("My new finger #%d is %d", finger_index, id);
164   }
165 }
166
167 /* Sets the predecessor of the current node.
168  * \param id the id to predecessor, or -1 to unset the predecessor
169  */
170 void Node::setPredecessor(int predecessor_id)
171 {
172   if (predecessor_id != pred_id_) {
173     pred_id_ = predecessor_id;
174     XBT_VERB("My new predecessor is %d", predecessor_id);
175   }
176 }
177
178 /** refreshes the finger table of the current node (called periodically) */
179 void Node::fixFingers()
180 {
181   XBT_DEBUG("Fixing fingers");
182   int id = findSuccessor(id_ + powers2[next_finger_to_fix]);
183   if (id != -1) {
184     if (id != fingers_[next_finger_to_fix]) {
185       setFinger(next_finger_to_fix, id);
186       printFingerTable();
187     }
188     next_finger_to_fix = (next_finger_to_fix + 1) % nb_bits;
189   }
190 }
191
192 /** Displays the finger table of a node. */
193 void Node::printFingerTable()
194 {
195   if (XBT_LOG_ISENABLED(s4u_chord, xbt_log_priority_verbose)) {
196     XBT_VERB("My finger table:");
197     XBT_VERB("Start | Succ");
198     for (int i = 0; i < nb_bits; i++) {
199       XBT_VERB(" %3d  | %3d", (id_ + powers2[i]) % nb_keys, fingers_[i]);
200     }
201
202     XBT_VERB("Predecessor: %d", pred_id_);
203   }
204 }
205
206 /* checks whether the predecessor has failed (called periodically) */
207 void Node::checkPredecessor()
208 {
209   XBT_DEBUG("Checking whether my predecessor is alive");
210   void* data = nullptr;
211   if (pred_id_ == -1)
212     return;
213
214   simgrid::s4u::MailboxPtr mailbox        = simgrid::s4u::Mailbox::byName(std::to_string(pred_id_));
215   simgrid::s4u::MailboxPtr return_mailbox = simgrid::s4u::Mailbox::byName(std::to_string(id_) + "_is_alive");
216
217   ChordMessage* message = new ChordMessage(PREDECESSOR_ALIVE);
218   message->request_id   = pred_id_;
219   message->answer_to    = return_mailbox;
220
221   XBT_DEBUG("Sending a 'Predecessor Alive' request to my predecessor %d", pred_id_);
222   try {
223     mailbox->put(message, 10, timeout);
224   } catch (xbt_ex& e) {
225     if (e.category == timeout_error) {
226       XBT_DEBUG("Failed to send the 'Predecessor Alive' request to %d", pred_id_);
227       delete message;
228       return;
229     }
230   }
231   // receive the answer
232   XBT_DEBUG("Sent 'Predecessor Alive' request to %d, waiting for the answer on my mailbox '%s'", pred_id_,
233             message->answer_to->getName());
234   simgrid::s4u::CommPtr comm = return_mailbox->get_async(&data);
235
236   try {
237     comm->wait(timeout);
238     XBT_DEBUG("Received the answer to my 'Predecessor Alive': my predecessor %d is alive", pred_id_);
239   } catch (xbt_ex& e) {
240     if (e.category == timeout_error) {
241       XBT_DEBUG("Failed to receive the answer to my 'Predecessor Alive' request");
242       pred_id_ = -1;
243     }
244   }
245   delete message;
246 }
247
248 /* Asks its predecessor to a remote node
249  *
250  * \param ask_to the node to ask to
251  * \return the id of its predecessor node, or -1 if the request failed (or if the node does not know its predecessor)
252  */
253 int Node::remoteGetPredecessor(int ask_to)
254 {
255   int predecessor_id                      = -1;
256   void* data                              = nullptr;
257   simgrid::s4u::MailboxPtr mailbox        = simgrid::s4u::Mailbox::byName(std::to_string(ask_to));
258   simgrid::s4u::MailboxPtr return_mailbox = simgrid::s4u::Mailbox::byName(std::to_string(id_) + "_pred");
259
260   ChordMessage* message = new ChordMessage(GET_PREDECESSOR);
261   message->request_id   = id_;
262   message->answer_to    = return_mailbox;
263
264   // send a "Get Predecessor" request to ask_to_id
265   XBT_DEBUG("Sending a 'Get Predecessor' request to %d", ask_to);
266   try {
267     mailbox->put(message, 10, timeout);
268   } catch (xbt_ex& e) {
269     if (e.category == timeout_error) {
270       XBT_DEBUG("Failed to send the 'Get Predecessor' request to %d", ask_to);
271       delete message;
272       return predecessor_id;
273     }
274   }
275
276   // receive the answer
277   XBT_DEBUG("Sent 'Get Predecessor' request to %d, waiting for the answer on my mailbox '%s'", ask_to,
278             message->answer_to->getName());
279   simgrid::s4u::CommPtr comm = return_mailbox->get_async(&data);
280
281   try {
282     comm->wait(timeout);
283     ChordMessage* answer = static_cast<ChordMessage*>(data);
284     XBT_DEBUG("Received the answer to my 'Get Predecessor' request: the predecessor of node %d is %d", ask_to,
285               answer->answer_id);
286     predecessor_id = answer->answer_id;
287     delete answer;
288   } catch (xbt_ex& e) {
289     if (e.category == timeout_error) {
290       XBT_DEBUG("Failed to receive the answer to my 'Get Predecessor' request");
291       delete static_cast<ChordMessage*>(data);
292     }
293   }
294
295   return predecessor_id;
296 }
297
298 /* Returns the closest preceding finger of an id with respect to the finger table of the current node.
299  *
300  * \param id the id to find
301  * \return the closest preceding finger of that id
302  */
303 int Node::closestPrecedingFinger(int id)
304 {
305   for (int i = nb_bits - 1; i >= 0; i--) {
306     if (is_in_interval(fingers_[i], id_ + 1, id - 1)) {
307       return fingers_[i];
308     }
309   }
310   return id_;
311 }
312
313 /* Makes the current node find the successor node of an id.
314  *
315  * \param id the id to find
316  * \return the id of the successor node, or -1 if the request failed
317  */
318 int Node::findSuccessor(int id)
319 {
320   // is my successor the successor?
321   if (is_in_interval(id, id_ + 1, fingers_[0])) {
322     return fingers_[0];
323   }
324
325   // otherwise, ask the closest preceding finger in my table
326   return remoteFindSuccessor(closestPrecedingFinger(id), id);
327 }
328
329 int Node::remoteFindSuccessor(int ask_to, int id)
330 {
331   int successor                           = -1;
332   void* data                              = nullptr;
333   simgrid::s4u::MailboxPtr mailbox        = simgrid::s4u::Mailbox::byName(std::to_string(ask_to));
334   simgrid::s4u::MailboxPtr return_mailbox = simgrid::s4u::Mailbox::byName(std::to_string(id_) + "_succ");
335
336   ChordMessage* message = new ChordMessage(FIND_SUCCESSOR);
337   message->request_id   = id_;
338   message->answer_to    = return_mailbox;
339
340   // send a "Find Successor" request to ask_to_id
341   XBT_DEBUG("Sending a 'Find Successor' request to %d for id %d", ask_to, id);
342   try {
343     mailbox->put(message, 10, timeout);
344   } catch (xbt_ex& e) {
345     if (e.category == timeout_error) {
346       XBT_DEBUG("Failed to send the 'Find Successor' request to %d for id %d", ask_to, id_);
347       delete message;
348       return successor;
349     }
350   }
351   // receive the answer
352   XBT_DEBUG("Sent a 'Find Successor' request to %d for key %d, waiting for the answer", ask_to, id);
353   simgrid::s4u::CommPtr comm = return_mailbox->get_async(&data);
354
355   try {
356     comm->wait(timeout);
357     ChordMessage* answer = static_cast<ChordMessage*>(data);
358     XBT_DEBUG("Received the answer to my 'Find Successor' request for id %d: the successor of key %d is %d",
359               answer->request_id, id_, answer->answer_id);
360     successor = answer->answer_id;
361     delete answer;
362   } catch (xbt_ex& e) {
363     if (e.category == timeout_error) {
364       XBT_DEBUG("Failed to receive the answer to my 'Find Successor' request");
365       delete static_cast<ChordMessage*>(data);
366     }
367   }
368   return successor;
369 }
370
371 /* Notifies the current node that its predecessor may have changed. */
372 void Node::notify(int predecessor_candidate_id)
373 {
374   if (pred_id_ == -1 || is_in_interval(predecessor_candidate_id, pred_id_ + 1, id_ - 1)) {
375     setPredecessor(predecessor_candidate_id);
376     printFingerTable();
377   } else {
378     XBT_DEBUG("I don't have to change my predecessor to %d", predecessor_candidate_id);
379   }
380 }
381
382 /* Notifies a remote node that its predecessor may have changed. */
383 void Node::remoteNotify(int notify_id, int predecessor_candidate_id)
384 {
385   ChordMessage* message = new ChordMessage(NOTIFY);
386   message->request_id   = predecessor_candidate_id;
387   message->answer_to    = nullptr;
388
389   // send a "Notify" request to notify_id
390   XBT_DEBUG("Sending a 'Notify' request to %d", notify_id);
391   simgrid::s4u::MailboxPtr mailbox = simgrid::s4u::Mailbox::byName(std::to_string(notify_id));
392   mailbox->put_init(message, 10)->detach();
393 }
394
395 /* This function is called periodically. It checks the immediate successor of the current node. */
396 void Node::stabilize()
397 {
398   XBT_DEBUG("Stabilizing node");
399
400   // get the predecessor of my immediate successor
401   int candidate_id = pred_id_;
402   int successor_id = fingers_[0];
403   if (successor_id != id_)
404     candidate_id = remoteGetPredecessor(successor_id);
405
406   // this node is a candidate to become my new successor
407   if (candidate_id != -1 && is_in_interval(candidate_id, id_ + 1, successor_id - 1)) {
408     setFinger(0, candidate_id);
409   }
410   if (successor_id != id_) {
411     remoteNotify(successor_id, id_);
412   }
413 }
414
415 /* This function is called when a node receives a message.
416  *
417  * \param message the message to handle (don't touch it afterward: it will be destroyed, reused or forwarded)
418  */
419 void Node::handleMessage(ChordMessage* message)
420 {
421   switch (message->type) {
422   case FIND_SUCCESSOR:
423     XBT_DEBUG("Received a 'Find Successor' request from %s for id %d", message->issuer_host_name.c_str(),
424         message->request_id);
425     // is my successor the successor?
426     if (is_in_interval(message->request_id, id_ + 1, fingers_[0])) {
427       message->type = FIND_SUCCESSOR_ANSWER;
428       message->answer_id = fingers_[0];
429       XBT_DEBUG("Sending back a 'Find Successor Answer' to %s (mailbox %s): the successor of %d is %d",
430                 message->issuer_host_name.c_str(), message->answer_to->getName(), message->request_id,
431                 message->answer_id);
432       message->answer_to->put_init(message, 10)->detach();
433     } else {
434       // otherwise, forward the request to the closest preceding finger in my table
435       int closest = closestPrecedingFinger(message->request_id);
436       XBT_DEBUG("Forwarding the 'Find Successor' request for id %d to my closest preceding finger %d",
437           message->request_id, closest);
438       simgrid::s4u::MailboxPtr mailbox = simgrid::s4u::Mailbox::byName(std::to_string(closest));
439       mailbox->put_init(message, 10)->detach();
440     }
441     break;
442
443   case GET_PREDECESSOR:
444     XBT_DEBUG("Receiving a 'Get Predecessor' request from %s", message->issuer_host_name.c_str());
445     message->type = GET_PREDECESSOR_ANSWER;
446     message->answer_id = pred_id_;
447     XBT_DEBUG("Sending back a 'Get Predecessor Answer' to %s via mailbox '%s': my predecessor is %d",
448               message->issuer_host_name.c_str(), message->answer_to->getName(), message->answer_id);
449     message->answer_to->put_init(message, 10)->detach();
450     break;
451
452   case NOTIFY:
453     // someone is telling me that he may be my new predecessor
454     XBT_DEBUG("Receiving a 'Notify' request from %s", message->issuer_host_name.c_str());
455     notify(message->request_id);
456     delete message;
457     break;
458
459   case PREDECESSOR_LEAVING:
460     // my predecessor is about to quit
461     XBT_DEBUG("Receiving a 'Predecessor Leaving' message from %s", message->issuer_host_name.c_str());
462     // modify my predecessor
463     setPredecessor(message->request_id);
464     delete message;
465     /*TODO :
466       >> notify my new predecessor
467       >> send a notify_predecessors !!
468      */
469     break;
470
471   case SUCCESSOR_LEAVING:
472     // my successor is about to quit
473     XBT_DEBUG("Receiving a 'Successor Leaving' message from %s", message->issuer_host_name.c_str());
474     // modify my successor FIXME : this should be implicit ?
475     setFinger(0, message->request_id);
476     delete message;
477     /* TODO
478        >> notify my new successor
479        >> update my table & predecessors table */
480     break;
481
482   case PREDECESSOR_ALIVE:
483     XBT_DEBUG("Receiving a 'Predecessor Alive' request from %s", message->issuer_host_name.c_str());
484     message->type = PREDECESSOR_ALIVE_ANSWER;
485     XBT_DEBUG("Sending back a 'Predecessor Alive Answer' to %s (mailbox %s)", message->issuer_host_name.c_str(),
486               message->answer_to->getName());
487     message->answer_to->put_init(message, 10)->detach();
488     break;
489
490   default:
491     XBT_DEBUG("Ignoring unexpected message: %d from %s", message->type, message->issuer_host_name.c_str());
492     delete message;
493   }
494 }