Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
09c455f5a3fe08bd74629b8ff10c3db7ecc2ee8e
[simgrid.git] / examples / msg / chord / chord.c
1
2 /* Copyright (c) 2010. The SimGrid Team.
3  * All rights reserved.                                                     */
4
5 /* This program is free software; you can redistribute it and/or modify it
6  * under the terms of the license (GNU LGPL) which comes with this package. */
7
8 #include <stdio.h>
9 #include "msg/msg.h"
10 #include "xbt/log.h"
11 #include "xbt/asserts.h"
12 #include "simgrid/modelchecker.h"
13 #include <xbt/RngStream.h>
14
15 /** @addtogroup MSG_examples
16  *
17  *  - <b>chord/chord.c: Classical Chord P2P protocol</b>
18  *    This example implements the well known Chord P2P protocol. Its
19  *    main advantage is that it constitute a fully working non-trivial
20  *    example. In addition, its implementation is rather efficient, as 
21  *    demonstrated in http://hal.inria.fr/inria-00602216/
22  */
23
24  
25 XBT_LOG_NEW_DEFAULT_CATEGORY(msg_chord,
26                              "Messages specific for this msg example");
27
28 #define COMM_SIZE 10
29 #define COMP_SIZE 0
30 #define MAILBOX_NAME_SIZE 10
31
32 static int nb_bits = 24;
33 static int nb_keys = 0;
34 static int timeout = 50;
35 static int max_simulation_time = 1000;
36 static int periodic_stabilize_delay = 20;
37 static int periodic_fix_fingers_delay = 120;
38 static int periodic_check_predecessor_delay = 120;
39 static int periodic_lookup_delay = 10;
40
41 extern long int smx_total_comms;
42
43 /*
44  * Finger element.
45  */
46 typedef struct s_finger {
47   int id;
48   char mailbox[MAILBOX_NAME_SIZE]; // string representation of the id
49 } s_finger_t, *finger_t;
50
51 /*
52  * Node data.
53  */
54 typedef struct s_node {
55   int id;                                 // my id
56   char mailbox[MAILBOX_NAME_SIZE];        // my mailbox name (string representation of the id)
57   s_finger_t *fingers;                    // finger table, of size nb_bits (fingers[0] is my successor)
58   int pred_id;                            // predecessor id
59   char pred_mailbox[MAILBOX_NAME_SIZE];   // predecessor's mailbox name
60   int next_finger_to_fix;                 // index of the next finger to fix in fix_fingers()
61   msg_comm_t comm_receive;                // current communication to receive
62   double last_change_date;                // last time I changed a finger or my predecessor
63   RngStream stream;                       //RngStream for
64 } s_node_t, *node_t;
65
66 /**
67  * Types of tasks exchanged between nodes.
68  */
69 typedef enum {
70   TASK_FIND_SUCCESSOR,
71   TASK_FIND_SUCCESSOR_ANSWER,
72   TASK_GET_PREDECESSOR,
73   TASK_GET_PREDECESSOR_ANSWER,
74   TASK_NOTIFY,
75   TASK_SUCCESSOR_LEAVING,
76   TASK_PREDECESSOR_LEAVING,
77   TASK_PREDECESSOR_ALIVE,
78   TASK_PREDECESSOR_ALIVE_ANSWER  
79 } e_task_type_t;
80
81 /*
82  * Data attached with the tasks sent and received
83  */
84 typedef struct s_task_data {
85   e_task_type_t type;                     // type of task
86   int request_id;                         // id paramater (used by some types of tasks)
87   int request_finger;                     // finger parameter (used by some types of tasks)
88   int answer_id;                          // answer (used by some types of tasks)
89   char answer_to[MAILBOX_NAME_SIZE];      // mailbox to send an answer to (if any)
90   const char* issuer_host_name;           // used for logging
91 } s_task_data_t, *task_data_t;
92
93 static int *powers2;
94
95 // utility functions
96 static void chord_initialize(void);
97 static void chord_exit(void);
98 static int normalize(int id);
99 static int is_in_interval(int id, int start, int end);
100 static void get_mailbox(int host_id, char* mailbox);
101 static void task_free(void* task);
102 static void print_finger_table(node_t node);
103 static void set_finger(node_t node, int finger_index, int id);
104 static void set_predecessor(node_t node, int predecessor_id);
105
106 // process functions
107 static int node(int argc, char *argv[]);
108 static void handle_task(node_t node, msg_task_t task);
109
110 // Chord core
111 static void create(node_t node);
112 static int join(node_t node, int known_id);
113 static void leave(node_t node);
114 static int find_successor(node_t node, int id);
115 static int remote_find_successor(node_t node, int ask_to_id, int id);
116 static int remote_get_predecessor(node_t node, int ask_to_id);
117 static int closest_preceding_node(node_t node, int id);
118 static void stabilize(node_t node);
119 static void notify(node_t node, int predecessor_candidate_id);
120 static void remote_notify(node_t node, int notify_to, int predecessor_candidate_id);
121 static void fix_fingers(node_t node);
122 static void check_predecessor(node_t node);
123 static void random_lookup(node_t);
124 static void quit_notify(node_t node);
125
126 /**
127  * \brief Global initialization of the Chord simulation.
128  */
129 static void chord_initialize(void)
130 {
131   // compute the powers of 2 once for all
132   powers2 = xbt_new(int, nb_bits);
133   int pow = 1;
134   int i;
135   for (i = 0; i < nb_bits; i++) {
136     powers2[i] = pow;
137     pow = pow << 1;
138   }
139   nb_keys = pow;
140   XBT_DEBUG("Sets nb_keys to %d", nb_keys);
141 }
142
143 static void chord_exit(void)
144 {
145   xbt_free(powers2);
146 }
147
148 /**
149  * \brief Turns an id into an equivalent id in [0, nb_keys).
150  * \param id an id
151  * \return the corresponding normalized id
152  */
153 static int normalize(int id)
154 {
155   // like id % nb_keys, but works with negatives numbers (and faster)
156   return id & (nb_keys - 1);
157 }
158
159 /**
160  * \brief Returns whether an id belongs to the interval [start, end].
161  *
162  * The parameters are noramlized to make sure they are between 0 and nb_keys - 1).
163  * 1 belongs to [62, 3]
164  * 1 does not belong to [3, 62]
165  * 63 belongs to [62, 3]
166  * 63 does not belong to [3, 62]
167  * 24 belongs to [21, 29]
168  * 24 does not belong to [29, 21]
169  *
170  * \param id id to check
171  * \param start lower bound
172  * \param end upper bound
173  * \return a non-zero value if id in in [start, end]
174  */
175 static int is_in_interval(int id, int start, int end)
176 {
177   id = normalize(id);
178   start = normalize(start);
179   end = normalize(end);
180
181   // make sure end >= start and id >= start
182   if (end < start) {
183     end += nb_keys;
184   }
185
186   if (id < start) {
187     id += nb_keys;
188   }
189
190   return id <= end;
191 }
192
193 /**
194  * \brief Gets the mailbox name of a host given its chord id.
195  * \param node_id id of a node
196  * \param mailbox pointer to where the mailbox name should be written
197  * (there must be enough space)
198  */
199 static void get_mailbox(int node_id, char* mailbox)
200 {
201   snprintf(mailbox, MAILBOX_NAME_SIZE - 1, "%d", node_id);
202 }
203
204 /**
205  * \brief Frees the memory used by a task.
206  * \param task the MSG task to destroy
207  */
208 static void task_free(void* task)
209 {
210   // TODO add a parameter data_free_function to MSG_task_create?
211   if(task != NULL){
212     xbt_free(MSG_task_get_data(task));
213     MSG_task_destroy(task);
214   }
215 }
216
217 /**
218  * \brief Displays the finger table of a node.
219  * \param node a node
220  */
221 static void print_finger_table(node_t node)
222 {
223   if (XBT_LOG_ISENABLED(msg_chord, xbt_log_priority_verbose)) {
224     int i;
225     XBT_VERB("My finger table:");
226     XBT_VERB("Start | Succ ");
227     for (i = 0; i < nb_bits; i++) {
228       XBT_VERB(" %3d  | %3d ", (node->id + powers2[i]) % nb_keys, node->fingers[i].id);
229     }
230     XBT_VERB("Predecessor: %d", node->pred_id);
231   }
232 }
233
234 /**
235  * \brief Sets a finger of the current node.
236  * \param node the current node
237  * \param finger_index index of the finger to set (0 to nb_bits - 1)
238  * \param id the id to set for this finger
239  */
240 static void set_finger(node_t node, int finger_index, int id)
241 {
242   if (id != node->fingers[finger_index].id) {
243     node->fingers[finger_index].id = id;
244     get_mailbox(id, node->fingers[finger_index].mailbox);
245     node->last_change_date = MSG_get_clock();
246     XBT_DEBUG("My new finger #%d is %d", finger_index, id);
247   }
248 }
249
250 /**
251  * \brief Sets the predecessor of the current node.
252  * \param node the current node
253  * \param id the id to predecessor, or -1 to unset the predecessor
254  */
255 static void set_predecessor(node_t node, int predecessor_id)
256 {
257   if (predecessor_id != node->pred_id) {
258     node->pred_id = predecessor_id;
259
260     if (predecessor_id != -1) {
261       get_mailbox(predecessor_id, node->pred_mailbox);
262     }
263     node->last_change_date = MSG_get_clock();
264
265     XBT_DEBUG("My new predecessor is %d", predecessor_id);
266   }
267 }
268
269 /**
270  * \brief Node Function
271  * Arguments:
272  * - my id
273  * - the id of a guy I know in the system (except for the first node)
274  * - the time to sleep before I join (except for the first node)
275  */
276 int node(int argc, char *argv[])
277 {
278   
279   /* Reduce the run size for the MC */
280   if(MC_is_active()){
281     periodic_stabilize_delay = 8;
282     periodic_fix_fingers_delay = 8;
283     periodic_check_predecessor_delay = 8;
284   }
285
286   double init_time = MSG_get_clock();
287   msg_task_t task_received = NULL;
288   int i;
289   int join_success = 0;
290   double deadline;
291   double next_stabilize_date = init_time + periodic_stabilize_delay;
292   double next_fix_fingers_date = init_time + periodic_fix_fingers_delay;
293   double next_check_predecessor_date = init_time + periodic_check_predecessor_delay;
294   double next_lookup_date = init_time + periodic_lookup_delay;
295
296   xbt_assert(argc == 3 || argc == 5, "Wrong number of arguments for this node");
297
298   // initialize my node
299   s_node_t node = {0};
300   node.id = atoi(argv[1]);
301   get_mailbox(node.id, node.mailbox);
302   node.next_finger_to_fix = 0;
303   node.fingers = xbt_new0(s_finger_t, nb_bits);
304   node.last_change_date = init_time;
305
306   for (i = 0; i < nb_bits; i++) {
307     node.fingers[i].id = -1;
308     set_finger(&node, i, node.id);
309   }
310
311   if (argc == 3) { // first ring
312     deadline = atof(argv[2]);
313     create(&node);
314     join_success = 1;
315   }
316   else {
317     int known_id = atoi(argv[2]);
318     //double sleep_time = atof(argv[3]);
319     deadline = atof(argv[4]);
320
321     /*
322     // sleep before starting
323     XBT_DEBUG("Let's sleep during %f", sleep_time);
324     MSG_process_sleep(sleep_time);
325     */
326     XBT_DEBUG("Hey! Let's join the system.");
327
328     join_success = join(&node, known_id);
329   }
330
331   if (join_success) {
332     while (MSG_get_clock() < init_time + deadline
333 //      && MSG_get_clock() < node.last_change_date + 1000
334         && MSG_get_clock() < max_simulation_time) {
335
336       if (node.comm_receive == NULL) {
337         task_received = NULL;
338         node.comm_receive = MSG_task_irecv(&task_received, node.mailbox);
339         // FIXME: do not make MSG_task_irecv() calls from several functions
340       }
341
342       if (!MSG_comm_test(node.comm_receive)) {
343
344         // no task was received: make some periodic calls
345
346         #ifdef HAVE_MC
347           if(MC_is_active()){
348             if(MC_random()){
349               stabilize(&node);
350             }else if(MC_random()){
351               fix_fingers(&node);
352             }else if(MC_random()){
353               check_predecessor(&node);
354             }else if(MC_random()){
355               random_lookup(&node);
356             }else{
357               MSG_process_sleep(5);
358             }
359           }else{
360             if (MSG_get_clock() >= next_stabilize_date) {
361               stabilize(&node);
362               next_stabilize_date = MSG_get_clock() + periodic_stabilize_delay;
363             }
364             else if (MSG_get_clock() >= next_fix_fingers_date) {
365               fix_fingers(&node);
366               next_fix_fingers_date = MSG_get_clock() + periodic_fix_fingers_delay;
367             }
368             else if (MSG_get_clock() >= next_check_predecessor_date) {
369               check_predecessor(&node);
370               next_check_predecessor_date = MSG_get_clock() + periodic_check_predecessor_delay;
371             }
372             else if (MSG_get_clock() >= next_lookup_date) {
373               random_lookup(&node);
374               next_lookup_date = MSG_get_clock() + periodic_lookup_delay;
375             }
376             else {
377               // nothing to do: sleep for a while
378               MSG_process_sleep(5);
379             }
380           }
381         #else
382           if (MSG_get_clock() >= next_stabilize_date) {
383             stabilize(&node);
384             next_stabilize_date = MSG_get_clock() + periodic_stabilize_delay;
385           }
386           else if (MSG_get_clock() >= next_fix_fingers_date) {
387             fix_fingers(&node);
388             next_fix_fingers_date = MSG_get_clock() + periodic_fix_fingers_delay;
389           }
390           else if (MSG_get_clock() >= next_check_predecessor_date) {
391             check_predecessor(&node);
392             next_check_predecessor_date = MSG_get_clock() + periodic_check_predecessor_delay;
393           }
394           else if (MSG_get_clock() >= next_lookup_date) {
395             random_lookup(&node);
396             next_lookup_date = MSG_get_clock() + periodic_lookup_delay;
397           }
398           else {
399             // nothing to do: sleep for a while
400             MSG_process_sleep(5);
401           }
402         #endif
403
404       } else {
405         // a transfer has occurred
406
407         msg_error_t status = MSG_comm_get_status(node.comm_receive);
408
409         if (status != MSG_OK) {
410           XBT_DEBUG("Failed to receive a task. Nevermind.");
411           MSG_comm_destroy(node.comm_receive);
412           node.comm_receive = NULL;
413         }
414         else {
415           // the task was successfully received
416           MSG_comm_destroy(node.comm_receive);
417           node.comm_receive = NULL;
418           handle_task(&node, task_received);
419         }
420       }
421     }
422
423     if (node.comm_receive) {
424       MSG_comm_destroy(node.comm_receive);
425       node.comm_receive = NULL;
426     }
427
428     // leave the ring
429     leave(&node);
430   }
431
432   // stop the simulation
433   xbt_free(node.fingers);
434   return 0;
435 }
436
437 /**
438  * \brief This function is called when the current node receives a task.
439  * \param node the current node
440  * \param task the task to handle (don't touch it then:
441  * it will be destroyed, reused or forwarded)
442  */
443 static void handle_task(node_t node, msg_task_t task) {
444
445   XBT_DEBUG("Handling task %p", task);
446   char mailbox[MAILBOX_NAME_SIZE];
447   task_data_t task_data = (task_data_t) MSG_task_get_data(task);
448   e_task_type_t type = task_data->type;
449
450   switch (type) {
451
452   case TASK_FIND_SUCCESSOR:
453     XBT_DEBUG("Receiving a 'Find Successor' request from %s for id %d",
454               task_data->issuer_host_name, task_data->request_id);
455     // is my successor the successor?
456     if (is_in_interval(task_data->request_id, node->id + 1, node->fingers[0].id)) {
457       task_data->type = TASK_FIND_SUCCESSOR_ANSWER;
458       task_data->answer_id = node->fingers[0].id;
459       XBT_DEBUG("Sending back a 'Find Successor Answer' to %s (mailbox %s): the successor of %d is %d",
460                 task_data->issuer_host_name,
461                 task_data->answer_to,
462                 task_data->request_id, task_data->answer_id);
463       MSG_task_dsend(task, task_data->answer_to, task_free);
464     }
465     else {
466       // otherwise, forward the request to the closest preceding finger in my table
467       int closest = closest_preceding_node(node, task_data->request_id);
468       XBT_DEBUG("Forwarding the 'Find Successor' request for id %d to my closest preceding finger %d",
469                 task_data->request_id, closest);
470       get_mailbox(closest, mailbox);
471       MSG_task_dsend(task, mailbox, task_free);
472     }
473     break;
474
475   case TASK_GET_PREDECESSOR:
476     XBT_DEBUG("Receiving a 'Get Predecessor' request from %s", task_data->issuer_host_name);
477     task_data->type = TASK_GET_PREDECESSOR_ANSWER;
478     task_data->answer_id = node->pred_id;
479     XBT_DEBUG("Sending back a 'Get Predecessor Answer' to %s via mailbox '%s': my predecessor is %d",
480               task_data->issuer_host_name,
481               task_data->answer_to, task_data->answer_id);
482     MSG_task_dsend(task, task_data->answer_to, task_free);
483     break;
484
485   case TASK_NOTIFY:
486     // someone is telling me that he may be my new predecessor
487     XBT_DEBUG("Receiving a 'Notify' request from %s", task_data->issuer_host_name);
488     notify(node, task_data->request_id);
489     task_free(task);
490     break;
491
492   case TASK_PREDECESSOR_LEAVING:
493     // my predecessor is about to quit
494     XBT_DEBUG("Receiving a 'Predecessor Leaving' message from %s", task_data->issuer_host_name);
495     // modify my predecessor
496     set_predecessor(node, task_data->request_id);
497     task_free(task);
498     /*TODO :
499       >> notify my new predecessor
500       >> send a notify_predecessors !!
501     */
502     break;
503
504   case TASK_SUCCESSOR_LEAVING:
505     // my successor is about to quit
506     XBT_DEBUG("Receiving a 'Successor Leaving' message from %s", task_data->issuer_host_name);
507     // modify my successor FIXME : this should be implicit ?
508     set_finger(node, 0, task_data->request_id);
509     task_free(task);
510     /* TODO
511        >> notify my new successor
512        >> update my table & predecessors table */
513     break;
514
515   case TASK_FIND_SUCCESSOR_ANSWER:
516   case TASK_GET_PREDECESSOR_ANSWER:
517   case TASK_PREDECESSOR_ALIVE_ANSWER:
518     XBT_DEBUG("Ignoring unexpected task of type %d (%p)", (int)type, task);
519     task_free(task);
520     break;
521
522   case TASK_PREDECESSOR_ALIVE:
523     XBT_DEBUG("Receiving a 'Predecessor Alive' request from %s", task_data->issuer_host_name);
524     task_data->type = TASK_PREDECESSOR_ALIVE_ANSWER;
525     XBT_DEBUG("Sending back a 'Predecessor Alive Answer' to %s (mailbox %s)",
526               task_data->issuer_host_name,
527               task_data->answer_to);
528     MSG_task_dsend(task, task_data->answer_to, task_free);
529     break;
530
531   }
532 }
533
534 /**
535  * \brief Initializes the current node as the first one of the system.
536  * \param node the current node
537  */
538 static void create(node_t node)
539 {
540   XBT_DEBUG("Create a new Chord ring...");
541   set_predecessor(node, -1); // -1 means that I have no predecessor
542   print_finger_table(node);
543 }
544
545 /**
546  * \brief Makes the current node join the ring, knowing the id of a node
547  * already in the ring
548  * \param node the current node
549  * \param known_id id of a node already in the ring
550  * \return 1 if the join operation succeeded, 0 otherwise
551  */
552 static int join(node_t node, int known_id)
553 {
554   XBT_INFO("Joining the ring with id %d, knowing node %d", node->id, known_id);
555   set_predecessor(node, -1); // no predecessor (yet)
556
557   /*
558   int i;
559   for (i = 0; i < nb_bits; i++) {
560     set_finger(node, i, known_id);
561   }
562   */
563
564   int successor_id = remote_find_successor(node, known_id, node->id);
565   if (successor_id == -1) {
566     XBT_INFO("Cannot join the ring.");
567   }
568   else {
569     set_finger(node, 0, successor_id);
570     print_finger_table(node);
571   }
572
573   return successor_id != -1;
574 }
575
576 /**
577  * \brief Makes the current node quit the system
578  * \param node the current node
579  */
580 static void leave(node_t node)
581 {
582   XBT_DEBUG("Well Guys! I Think it's time for me to quit ;)");
583   quit_notify(node);
584   RngStream_DeleteStream(&node->stream);
585 }
586
587 /**
588  * \brief Notifies the successor and the predecessor of the current node
589  * of the departure
590  * \param node the current node
591  */
592 static void quit_notify(node_t node)
593 {
594   char mailbox[MAILBOX_NAME_SIZE];
595   //send the PREDECESSOR_LEAVING to our successor
596   task_data_t req_data = xbt_new0(s_task_data_t,1);
597   req_data->type = TASK_PREDECESSOR_LEAVING;
598   req_data->request_id = node->pred_id;
599   get_mailbox(node->id, req_data->answer_to);
600   req_data->issuer_host_name = MSG_host_get_name(MSG_host_self());
601
602   msg_task_t task_sent = MSG_task_create(NULL, COMP_SIZE, COMM_SIZE, req_data);
603   XBT_DEBUG("Sending a 'PREDECESSOR_LEAVING' to my successor %d",node->fingers[0].id);
604   MSG_task_send_with_timeout(task_sent, node->fingers[0].mailbox, timeout);
605
606   //send the SUCCESSOR_LEAVING to our predecessor
607   get_mailbox(node->pred_id, mailbox);
608   task_data_t req_data_s = xbt_new0(s_task_data_t,1);
609   req_data_s->type = TASK_SUCCESSOR_LEAVING;
610   req_data_s->request_id = node->fingers[0].id;
611   req_data_s->request_id = node->pred_id;
612   get_mailbox(node->id, req_data_s->answer_to);
613   req_data_s->issuer_host_name = MSG_host_get_name(MSG_host_self());
614
615   msg_task_t task_sent_s = MSG_task_create(NULL, COMP_SIZE, COMM_SIZE, req_data_s);
616   XBT_DEBUG("Sending a 'SUCCESSOR_LEAVING' to my predecessor %d",node->pred_id);
617   MSG_task_send_with_timeout(task_sent_s, mailbox, timeout);
618
619 }
620
621 /**
622  * \brief Makes the current node find the successor node of an id.
623  * \param node the current node
624  * \param id the id to find
625  * \return the id of the successor node, or -1 if the request failed
626  */
627 static int find_successor(node_t node, int id)
628 {
629   // is my successor the successor?
630   if (is_in_interval(id, node->id + 1, node->fingers[0].id)) {
631     return node->fingers[0].id;
632   }
633
634   // otherwise, ask the closest preceding finger in my table
635   int closest = closest_preceding_node(node, id);
636   return remote_find_successor(node, closest, id);
637 }
638
639 /**
640  * \brief Asks another node the successor node of an id.
641  * \param node the current node
642  * \param ask_to the node to ask to
643  * \param id the id to find
644  * \return the id of the successor node, or -1 if the request failed
645  */
646 static int remote_find_successor(node_t node, int ask_to, int id)
647 {
648   int successor = -1;
649   int stop = 0;
650   char mailbox[MAILBOX_NAME_SIZE];
651   get_mailbox(ask_to, mailbox);
652   task_data_t req_data = xbt_new0(s_task_data_t, 1);
653   req_data->type = TASK_FIND_SUCCESSOR;
654   req_data->request_id = id;
655   get_mailbox(node->id, req_data->answer_to);
656   req_data->issuer_host_name = MSG_host_get_name(MSG_host_self());
657
658   // send a "Find Successor" request to ask_to_id
659   msg_task_t task_sent = MSG_task_create(NULL, COMP_SIZE, COMM_SIZE, req_data);
660   XBT_DEBUG("Sending a 'Find Successor' request (task %p) to %d for id %d", task_sent, ask_to, id);
661   msg_error_t res = MSG_task_send_with_timeout(task_sent, mailbox, timeout);
662
663   if (res != MSG_OK) {
664     XBT_DEBUG("Failed to send the 'Find Successor' request (task %p) to %d for id %d",
665         task_sent, ask_to, id);
666     task_free(task_sent);
667   }
668   else {
669
670     // receive the answer
671     XBT_DEBUG("Sent a 'Find Successor' request (task %p) to %d for key %d, waiting for the answer",
672         task_sent, ask_to, id);
673
674     do {
675       if (node->comm_receive == NULL) {
676         msg_task_t task_received = NULL;
677         node->comm_receive = MSG_task_irecv(&task_received, node->mailbox);
678       }
679
680       res = MSG_comm_wait(node->comm_receive, timeout);
681
682       if (res != MSG_OK) {
683         XBT_DEBUG("Failed to receive the answer to my 'Find Successor' request (task %p): %d",
684                   task_sent, (int)res);
685         stop = 1;
686         MSG_comm_destroy(node->comm_receive);
687         node->comm_receive = NULL;
688       }
689       else {
690         msg_task_t task_received = MSG_comm_get_task(node->comm_receive);
691         XBT_DEBUG("Received a task (%p)", task_received);
692         task_data_t ans_data = MSG_task_get_data(task_received);
693
694         // Once upon a time, our code assumed that here, task_received != task_sent all the time
695         // 
696         // This assumption is wrong (as messages from differing round can interleave), leading to a bug in our code.
697         // We failed to find this bug directly, as it only occured on large platforms, leading to hardly usable traces.
698         // Instead, we used the model-checker to track down the issue by adding the following test here in the code:
699         //   if (MC_is_active()) {
700         //      MC_assert(task_received == task_sent);
701         //   }
702         // That explained the bug in a snap, with a very cool example and everything.
703         // 
704         // This MC_assert is now desactivated as the case is now properly handled in our code and we don't want the
705         //   MC to fail any further under that condition, but this comment is here to as a memorial for this first 
706         //   brillant victory of the model-checking in the SimGrid community :)
707
708         if (task_received != task_sent) {
709           // this is not the expected answer
710           MSG_comm_destroy(node->comm_receive);
711           node->comm_receive = NULL;
712           handle_task(node, task_received);
713         }
714         else {
715           // this is our answer
716           XBT_DEBUG("Received the answer to my 'Find Successor' request for id %d (task %p): the successor of key %d is %d",
717               ans_data->request_id, task_received, id, ans_data->answer_id);
718           successor = ans_data->answer_id;
719           stop = 1;
720           MSG_comm_destroy(node->comm_receive);
721           node->comm_receive = NULL;
722           task_free(task_received);
723         }
724       }
725     } while (!stop);
726   }
727
728   return successor;
729 }
730
731 /**
732  * \brief Asks another node its predecessor.
733  * \param node the current node
734  * \param ask_to the node to ask to
735  * \return the id of its predecessor node, or -1 if the request failed
736  * (or if the node does not know its predecessor)
737  */
738 static int remote_get_predecessor(node_t node, int ask_to)
739 {
740   int predecessor_id = -1;
741   int stop = 0;
742   char mailbox[MAILBOX_NAME_SIZE];
743   get_mailbox(ask_to, mailbox);
744   task_data_t req_data = xbt_new0(s_task_data_t, 1);
745   req_data->type = TASK_GET_PREDECESSOR;
746   get_mailbox(node->id, req_data->answer_to);
747   req_data->issuer_host_name = MSG_host_get_name(MSG_host_self());
748
749   // send a "Get Predecessor" request to ask_to_id
750   XBT_DEBUG("Sending a 'Get Predecessor' request to %d", ask_to);
751   msg_task_t task_sent = MSG_task_create(NULL, COMP_SIZE, COMM_SIZE, req_data);
752   msg_error_t res = MSG_task_send_with_timeout(task_sent, mailbox, timeout);
753
754   if (res != MSG_OK) {
755     XBT_DEBUG("Failed to send the 'Get Predecessor' request (task %p) to %d",
756         task_sent, ask_to);
757     task_free(task_sent);
758   }
759   else {
760
761     // receive the answer
762     XBT_DEBUG("Sent 'Get Predecessor' request (task %p) to %d, waiting for the answer on my mailbox '%s'",
763         task_sent, ask_to, req_data->answer_to);
764
765     do {
766       if (node->comm_receive == NULL) { // FIXME simplify this
767         msg_task_t task_received = NULL;
768         node->comm_receive = MSG_task_irecv(&task_received, node->mailbox);
769       }
770
771       res = MSG_comm_wait(node->comm_receive, timeout);
772
773       if (res != MSG_OK) {
774         XBT_DEBUG("Failed to receive the answer to my 'Get Predecessor' request (task %p): %d",
775             task_sent, (int)res);
776         stop = 1;
777         MSG_comm_destroy(node->comm_receive);
778         node->comm_receive = NULL;
779       }
780       else {
781         msg_task_t task_received = MSG_comm_get_task(node->comm_receive);
782         task_data_t ans_data = MSG_task_get_data(task_received);
783
784         if (MC_is_active()) {
785           MC_assert(task_received == task_sent);
786         }
787
788         if (task_received != task_sent) {
789           MSG_comm_destroy(node->comm_receive);
790           node->comm_receive = NULL;
791           handle_task(node, task_received);
792         }
793         else {
794           XBT_DEBUG("Received the answer to my 'Get Predecessor' request (task %p): the predecessor of node %d is %d",
795               task_received, ask_to, ans_data->answer_id);
796           predecessor_id = ans_data->answer_id;
797           stop = 1;
798           MSG_comm_destroy(node->comm_receive);
799           node->comm_receive = NULL;
800           task_free(task_received);
801         }
802       }
803     } while (!stop);
804   }
805
806   return predecessor_id;
807 }
808
809 /**
810  * \brief Returns the closest preceding finger of an id
811  * with respect to the finger table of the current node.
812  * \param node the current node
813  * \param id the id to find
814  * \return the closest preceding finger of that id
815  */
816 int closest_preceding_node(node_t node, int id)
817 {
818   int i;
819   for (i = nb_bits - 1; i >= 0; i--) {
820     if (is_in_interval(node->fingers[i].id, node->id + 1, id - 1)) {
821       return node->fingers[i].id;
822     }
823   }
824   return node->id;
825 }
826
827 /**
828  * \brief This function is called periodically. It checks the immediate
829  * successor of the current node.
830  * \param node the current node
831  */
832 static void stabilize(node_t node)
833 {
834   XBT_DEBUG("Stabilizing node");
835
836   // get the predecessor of my immediate successor
837   int candidate_id;
838   int successor_id = node->fingers[0].id;
839   if (successor_id != node->id) {
840     candidate_id = remote_get_predecessor(node, successor_id);
841   }
842   else {
843     candidate_id = node->pred_id;
844   }
845
846   // this node is a candidate to become my new successor
847   if (candidate_id != -1
848       && is_in_interval(candidate_id, node->id + 1, successor_id - 1)) {
849     set_finger(node, 0, candidate_id);
850   }
851   if (successor_id != node->id) {
852     remote_notify(node, successor_id, node->id);
853   }
854 }
855
856 /**
857  * \brief Notifies the current node that its predecessor may have changed.
858  * \param node the current node
859  * \param candidate_id the possible new predecessor
860  */
861 static void notify(node_t node, int predecessor_candidate_id) {
862
863   if (node->pred_id == -1
864     || is_in_interval(predecessor_candidate_id, node->pred_id + 1, node->id - 1)) {
865
866     set_predecessor(node, predecessor_candidate_id);
867     print_finger_table(node);
868   }
869   else {
870     XBT_DEBUG("I don't have to change my predecessor to %d", predecessor_candidate_id);
871   }
872 }
873
874 /**
875  * \brief Notifies a remote node that its predecessor may have changed.
876  * \param node the current node
877  * \param notify_id id of the node to notify
878  * \param candidate_id the possible new predecessor
879  */
880 static void remote_notify(node_t node, int notify_id, int predecessor_candidate_id) {
881
882       task_data_t req_data = xbt_new0(s_task_data_t, 1);
883       req_data->type = TASK_NOTIFY;
884       req_data->request_id = predecessor_candidate_id;
885       req_data->issuer_host_name = MSG_host_get_name(MSG_host_self());
886
887       // send a "Notify" request to notify_id
888       msg_task_t task = MSG_task_create(NULL, COMP_SIZE, COMM_SIZE, req_data);
889       XBT_DEBUG("Sending a 'Notify' request (task %p) to %d", task, notify_id);
890       char mailbox[MAILBOX_NAME_SIZE];
891       get_mailbox(notify_id, mailbox);
892       MSG_task_dsend(task, mailbox, task_free);
893     }
894
895 /**
896  * \brief This function is called periodically.
897  * It refreshes the finger table of the current node.
898  * \param node the current node
899  */
900 static void fix_fingers(node_t node) {
901
902   XBT_DEBUG("Fixing fingers");
903   int i = node->next_finger_to_fix;
904   int id = find_successor(node, node->id + powers2[i]);
905   if (id != -1) {
906
907     if (id != node->fingers[i].id) {
908       set_finger(node, i, id);
909       print_finger_table(node);
910     }
911     node->next_finger_to_fix = (i + 1) % nb_bits;
912   }
913 }
914
915 /**
916  * \brief This function is called periodically.
917  * It checks whether the predecessor has failed
918  * \param node the current node
919  */
920 static void check_predecessor(node_t node)
921 {
922   XBT_DEBUG("Checking whether my predecessor is alive");
923
924   if(node->pred_id == -1)
925     return;
926
927   int stop = 0;
928
929   char mailbox[MAILBOX_NAME_SIZE];
930   get_mailbox(node->pred_id, mailbox);
931   task_data_t req_data = xbt_new0(s_task_data_t,1);
932   req_data->type = TASK_PREDECESSOR_ALIVE;
933   req_data->request_id = node->pred_id;
934   get_mailbox(node->id, req_data->answer_to);
935   req_data->issuer_host_name = MSG_host_get_name(MSG_host_self());
936
937   msg_task_t task_sent = MSG_task_create(NULL, COMP_SIZE, COMM_SIZE, req_data);
938   XBT_DEBUG("Sending a 'Predecessor Alive' request to my predecessor %d", node->pred_id);
939   
940   msg_error_t res = MSG_task_send_with_timeout(task_sent, mailbox, timeout);
941   
942   if (res != MSG_OK) {
943     XBT_DEBUG("Failed to send the 'Predecessor Alive' request (task %p) to %d", task_sent, node->pred_id);
944     task_free(task_sent);
945   }else{
946
947     // receive the answer
948     XBT_DEBUG("Sent 'Predecessor Alive' request (task %p) to %d, waiting for the answer on my mailbox '%s'",
949               task_sent, node->pred_id, req_data->answer_to);
950
951     do {
952       if (node->comm_receive == NULL) { // FIXME simplify this
953         msg_task_t task_received = NULL;
954         node->comm_receive = MSG_task_irecv(&task_received, node->mailbox);
955       }
956
957       res = MSG_comm_wait(node->comm_receive, timeout);
958
959       if (res != MSG_OK) {
960         XBT_DEBUG("Failed to receive the answer to my 'Predecessor Alive' request (task %p): %d",
961                   task_sent, (int)res);
962         stop = 1;
963         MSG_comm_destroy(node->comm_receive);
964         node->comm_receive = NULL;
965         node->pred_id = -1;
966       }else {
967         msg_task_t task_received = MSG_comm_get_task(node->comm_receive);
968         if (task_received != task_sent) {
969           MSG_comm_destroy(node->comm_receive);
970           node->comm_receive = NULL;
971           handle_task(node, task_received);
972         }else{
973           XBT_DEBUG("Received the answer to my 'Predecessor Alive' request (task %p) : my predecessor %d is alive", task_received, node->pred_id);
974           stop = 1;
975           MSG_comm_destroy(node->comm_receive);
976           node->comm_receive = NULL;
977           task_free(task_received);
978         }
979       }
980     } while (!stop);
981   }
982 }
983
984 /**
985  * \brief Performs a find successor request to a random id.
986  * \param node the current node
987  */
988 static void random_lookup(node_t node)
989 {
990   
991   int id = 1337; 
992   find_successor(node, id);
993
994   /*** Random lookup disabled for tesh examples ***/
995   /*if(node->stream == NULL)
996     node->stream = RngStream_CreateStream("");
997   int random_index = RngStream_RandInt (node->stream, 0, nb_bits - 1);
998   int random_id = node->fingers[random_index].id;
999   XBT_DEBUG("Making a lookup request for id %d", random_id);
1000   int res = find_successor(node, random_id);
1001   XBT_DEBUG("The successor of node %d is %d", random_id, res);*/
1002
1003 }
1004
1005 /**
1006  * \brief Main function.
1007  */
1008 int main(int argc, char *argv[])
1009 {
1010   MSG_init(&argc, argv);
1011   if (argc < 3) {
1012     printf("Usage: %s [-nb_bits=n] [-timeout=t] platform_file deployment_file\n", argv[0]);
1013     printf("example: %s ../msg_platform.xml chord.xml\n", argv[0]);
1014     exit(1);
1015   }
1016
1017   char **options = &argv[1];
1018   while (!strncmp(options[0], "-", 1)) {
1019
1020     int length = strlen("-nb_bits=");
1021     if (!strncmp(options[0], "-nb_bits=", length) && strlen(options[0]) > length) {
1022       nb_bits = atoi(options[0] + length);
1023       XBT_DEBUG("Set nb_bits to %d", nb_bits);
1024     }
1025     else {
1026
1027       length = strlen("-timeout=");
1028       if (!strncmp(options[0], "-timeout=", length) && strlen(options[0]) > length) {
1029         timeout = atoi(options[0] + length);
1030         XBT_DEBUG("Set timeout to %d", timeout);
1031       }
1032       else {
1033         xbt_die("Invalid chord option '%s'", options[0]);
1034       }
1035     }
1036     options++;
1037   }
1038
1039   const char* platform_file = options[0];
1040   const char* application_file = options[1];
1041
1042   chord_initialize();
1043
1044   MSG_create_environment(platform_file);
1045
1046   MSG_function_register("node", node);
1047   MSG_launch_application(application_file);
1048
1049   msg_error_t res = MSG_main();
1050   XBT_CRITICAL("Messages created: %ld", smx_total_comms);
1051   XBT_INFO("Simulated time: %g", MSG_get_clock());
1052
1053   chord_exit();
1054
1055   if (res == MSG_OK)
1056     return 0;
1057   else
1058     return 1;
1059 }