Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
9e92363269ec86afa0f2d5f01a141e4d1f3834cb
[simgrid.git] / examples / msg / chord / chord.c
1
2 /* Copyright (c) 2010-2013. 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   #ifdef HAVE_MC
297   int listen = 0;
298   int no_op = 0;
299   int sub_protocol = 0;
300   #endif
301
302   xbt_assert(argc == 3 || argc == 5, "Wrong number of arguments for this node");
303
304   // initialize my node
305   s_node_t node = {0};
306   node.id = atoi(argv[1]);
307   get_mailbox(node.id, node.mailbox);
308   node.next_finger_to_fix = 0;
309   node.fingers = xbt_new0(s_finger_t, nb_bits);
310   node.last_change_date = init_time;
311
312   for (i = 0; i < nb_bits; i++) {
313     node.fingers[i].id = -1;
314     set_finger(&node, i, node.id);
315   }
316
317   if (argc == 3) { // first ring
318     deadline = atof(argv[2]);
319     create(&node);
320     join_success = 1;
321   }
322   else {
323     int known_id = atoi(argv[2]);
324     //double sleep_time = atof(argv[3]);
325     deadline = atof(argv[4]);
326
327     /*
328     // sleep before starting
329     XBT_DEBUG("Let's sleep during %f", sleep_time);
330     MSG_process_sleep(sleep_time);
331     */
332     XBT_DEBUG("Hey! Let's join the system.");
333
334     join_success = join(&node, known_id);
335   }
336
337   if (join_success) {
338     while (MSG_get_clock() < init_time + deadline
339 //      && MSG_get_clock() < node.last_change_date + 1000
340         && MSG_get_clock() < max_simulation_time) {
341
342       if (node.comm_receive == NULL) {
343         task_received = NULL;
344         node.comm_receive = MSG_task_irecv(&task_received, node.mailbox);
345         // FIXME: do not make MSG_task_irecv() calls from several functions
346       }
347
348       //XBT_INFO("Node %d is ring member : %d", node.id, is_ring_member(known_id, node.id) != -1);
349
350       if (!MSG_comm_test(node.comm_receive)) {
351
352         // no task was received: make some periodic calls
353
354 #ifdef HAVE_MC
355         if(MC_is_active()){
356           if(!MC_visited_reduction() && no_op){
357               MC_cut();
358           }
359           if(listen == 0 && (sub_protocol = MC_random(0, 4)) > 0){
360             if(sub_protocol == 1)
361               stabilize(&node);
362             else if(sub_protocol == 2)
363               fix_fingers(&node);
364             else if(sub_protocol == 3)
365               check_predecessor(&node);
366             else
367               random_lookup(&node);
368             listen = 1;
369           }else{
370             MSG_process_sleep(5);
371             if(!MC_visited_reduction())
372               no_op = 1;
373           }
374         }else{
375           if (MSG_get_clock() >= next_stabilize_date) {
376             stabilize(&node);
377             next_stabilize_date = MSG_get_clock() + periodic_stabilize_delay;
378           }else if (MSG_get_clock() >= next_fix_fingers_date) {
379             fix_fingers(&node);
380             next_fix_fingers_date = MSG_get_clock() + periodic_fix_fingers_delay;
381           }else if (MSG_get_clock() >= next_check_predecessor_date) {
382             check_predecessor(&node);
383             next_check_predecessor_date = MSG_get_clock() + periodic_check_predecessor_delay;
384           }else if (MSG_get_clock() >= next_lookup_date) {
385             random_lookup(&node);
386             next_lookup_date = MSG_get_clock() + periodic_lookup_delay;
387           }else {
388             // nothing to do: sleep for a while
389             MSG_process_sleep(5);
390           }
391         }
392 #else
393         if (MSG_get_clock() >= next_stabilize_date) {
394           stabilize(&node);
395           next_stabilize_date = MSG_get_clock() + periodic_stabilize_delay;
396         }else if (MSG_get_clock() >= next_fix_fingers_date) {
397           fix_fingers(&node);
398           next_fix_fingers_date = MSG_get_clock() + periodic_fix_fingers_delay;
399         }else if (MSG_get_clock() >= next_check_predecessor_date) {
400           check_predecessor(&node);
401           next_check_predecessor_date = MSG_get_clock() + periodic_check_predecessor_delay;
402         }else if (MSG_get_clock() >= next_lookup_date) {
403           random_lookup(&node);
404           next_lookup_date = MSG_get_clock() + periodic_lookup_delay;
405         }else {
406           // nothing to do: sleep for a while
407           MSG_process_sleep(5);
408         }
409 #endif
410
411       } else {
412         // a transfer has occurred
413
414         msg_error_t status = MSG_comm_get_status(node.comm_receive);
415
416         if (status != MSG_OK) {
417           XBT_DEBUG("Failed to receive a task. Nevermind.");
418           MSG_comm_destroy(node.comm_receive);
419           node.comm_receive = NULL;
420         }
421         else {
422           // the task was successfully received
423           MSG_comm_destroy(node.comm_receive);
424           node.comm_receive = NULL;
425           handle_task(&node, task_received);
426         }
427       }
428     }
429
430     if (node.comm_receive) {
431       MSG_comm_destroy(node.comm_receive);
432       node.comm_receive = NULL;
433     }
434
435     // leave the ring
436     leave(&node);
437   }
438
439   // stop the simulation
440   xbt_free(node.fingers);
441   return 0;
442 }
443
444 /**
445  * \brief This function is called when the current node receives a task.
446  * \param node the current node
447  * \param task the task to handle (don't touch it then:
448  * it will be destroyed, reused or forwarded)
449  */
450 static void handle_task(node_t node, msg_task_t task) {
451
452   XBT_DEBUG("Handling task %p", task);
453   char mailbox[MAILBOX_NAME_SIZE];
454   task_data_t task_data = (task_data_t) MSG_task_get_data(task);
455   e_task_type_t type = task_data->type;
456
457   switch (type) {
458
459   case TASK_FIND_SUCCESSOR:
460     XBT_DEBUG("Receiving a 'Find Successor' request from %s for id %d",
461               task_data->issuer_host_name, task_data->request_id);
462     // is my successor the successor?
463     if (is_in_interval(task_data->request_id, node->id + 1, node->fingers[0].id)) {
464       task_data->type = TASK_FIND_SUCCESSOR_ANSWER;
465       task_data->answer_id = node->fingers[0].id;
466       XBT_DEBUG("Sending back a 'Find Successor Answer' to %s (mailbox %s): the successor of %d is %d",
467                 task_data->issuer_host_name,
468                 task_data->answer_to,
469                 task_data->request_id, task_data->answer_id);
470       MSG_task_dsend(task, task_data->answer_to, task_free);
471     }
472     else {
473       // otherwise, forward the request to the closest preceding finger in my table
474       int closest = closest_preceding_node(node, task_data->request_id);
475       XBT_DEBUG("Forwarding the 'Find Successor' request for id %d to my closest preceding finger %d",
476                 task_data->request_id, closest);
477       get_mailbox(closest, mailbox);
478       MSG_task_dsend(task, mailbox, task_free);
479     }
480     break;
481
482   case TASK_GET_PREDECESSOR:
483     XBT_DEBUG("Receiving a 'Get Predecessor' request from %s", task_data->issuer_host_name);
484     task_data->type = TASK_GET_PREDECESSOR_ANSWER;
485     task_data->answer_id = node->pred_id;
486     XBT_DEBUG("Sending back a 'Get Predecessor Answer' to %s via mailbox '%s': my predecessor is %d",
487               task_data->issuer_host_name,
488               task_data->answer_to, task_data->answer_id);
489     MSG_task_dsend(task, task_data->answer_to, task_free);
490     break;
491
492   case TASK_NOTIFY:
493     // someone is telling me that he may be my new predecessor
494     XBT_DEBUG("Receiving a 'Notify' request from %s", task_data->issuer_host_name);
495     notify(node, task_data->request_id);
496     task_free(task);
497     break;
498
499   case TASK_PREDECESSOR_LEAVING:
500     // my predecessor is about to quit
501     XBT_DEBUG("Receiving a 'Predecessor Leaving' message from %s", task_data->issuer_host_name);
502     // modify my predecessor
503     set_predecessor(node, task_data->request_id);
504     task_free(task);
505     /*TODO :
506       >> notify my new predecessor
507       >> send a notify_predecessors !!
508     */
509     break;
510
511   case TASK_SUCCESSOR_LEAVING:
512     // my successor is about to quit
513     XBT_DEBUG("Receiving a 'Successor Leaving' message from %s", task_data->issuer_host_name);
514     // modify my successor FIXME : this should be implicit ?
515     set_finger(node, 0, task_data->request_id);
516     task_free(task);
517     /* TODO
518        >> notify my new successor
519        >> update my table & predecessors table */
520     break;
521
522   case TASK_FIND_SUCCESSOR_ANSWER:
523   case TASK_GET_PREDECESSOR_ANSWER:
524   case TASK_PREDECESSOR_ALIVE_ANSWER:
525     XBT_DEBUG("Ignoring unexpected task of type %d (%p)", (int)type, task);
526     task_free(task);
527     break;
528
529   case TASK_PREDECESSOR_ALIVE:
530     XBT_DEBUG("Receiving a 'Predecessor Alive' request from %s", task_data->issuer_host_name);
531     task_data->type = TASK_PREDECESSOR_ALIVE_ANSWER;
532     XBT_DEBUG("Sending back a 'Predecessor Alive Answer' to %s (mailbox %s)",
533               task_data->issuer_host_name,
534               task_data->answer_to);
535     MSG_task_dsend(task, task_data->answer_to, task_free);
536     break;
537
538   }
539 }
540
541 /**
542  * \brief Initializes the current node as the first one of the system.
543  * \param node the current node
544  */
545 static void create(node_t node)
546 {
547   XBT_DEBUG("Create a new Chord ring...");
548   set_predecessor(node, -1); // -1 means that I have no predecessor
549   print_finger_table(node);
550 }
551
552 /**
553  * \brief Makes the current node join the ring, knowing the id of a node
554  * already in the ring
555  * \param node the current node
556  * \param known_id id of a node already in the ring
557  * \return 1 if the join operation succeeded, 0 otherwise
558  */
559 static int join(node_t node, int known_id)
560 {
561   XBT_INFO("Joining the ring with id %d, knowing node %d", node->id, known_id);
562   set_predecessor(node, -1); // no predecessor (yet)
563
564   /*
565   int i;
566   for (i = 0; i < nb_bits; i++) {
567     set_finger(node, i, known_id);
568   }
569   */
570
571   int successor_id = remote_find_successor(node, known_id, node->id);
572   if (successor_id == -1) {
573     XBT_INFO("Cannot join the ring.");
574   }
575   else {
576     set_finger(node, 0, successor_id);
577     print_finger_table(node);
578   }
579
580   return successor_id != -1;
581 }
582
583 /**
584  * \brief Makes the current node quit the system
585  * \param node the current node
586  */
587 static void leave(node_t node)
588 {
589   XBT_DEBUG("Well Guys! I Think it's time for me to quit ;)");
590   quit_notify(node);
591   RngStream_DeleteStream(&node->stream);
592 }
593
594 /**
595  * \brief Notifies the successor and the predecessor of the current node
596  * of the departure
597  * \param node the current node
598  */
599 static void quit_notify(node_t node)
600 {
601   char mailbox[MAILBOX_NAME_SIZE];
602   //send the PREDECESSOR_LEAVING to our successor
603   task_data_t req_data = xbt_new0(s_task_data_t,1);
604   req_data->type = TASK_PREDECESSOR_LEAVING;
605   req_data->request_id = node->pred_id;
606   get_mailbox(node->id, req_data->answer_to);
607   req_data->issuer_host_name = MSG_host_get_name(MSG_host_self());
608
609   msg_task_t task_sent = MSG_task_create(NULL, COMP_SIZE, COMM_SIZE, req_data);
610   XBT_DEBUG("Sending a 'PREDECESSOR_LEAVING' to my successor %d",node->fingers[0].id);
611   if (MSG_task_send_with_timeout(task_sent, node->fingers[0].mailbox, timeout)==
612       MSG_TIMEOUT) {
613     XBT_DEBUG("Timeout expired when sending a 'PREDECESSOR_LEAVING' to my successor %d",
614         node->fingers[0].id);
615     task_free(task_sent);
616   }
617
618   //send the SUCCESSOR_LEAVING to our predecessor
619   get_mailbox(node->pred_id, mailbox);
620   task_data_t req_data_s = xbt_new0(s_task_data_t,1);
621   req_data_s->type = TASK_SUCCESSOR_LEAVING;
622   req_data_s->request_id = node->fingers[0].id;
623   req_data_s->request_id = node->pred_id;
624   get_mailbox(node->id, req_data_s->answer_to);
625   req_data_s->issuer_host_name = MSG_host_get_name(MSG_host_self());
626
627   msg_task_t task_sent_s = MSG_task_create(NULL, COMP_SIZE, COMM_SIZE, req_data_s);
628   XBT_DEBUG("Sending a 'SUCCESSOR_LEAVING' to my predecessor %d",node->pred_id);
629   if (MSG_task_send_with_timeout(task_sent_s, mailbox, timeout)==
630       MSG_TIMEOUT) {
631     XBT_DEBUG("Timeout expired when sending a 'SUCCESSOR_LEAVING' to my predecessor %d",
632         node->pred_id);
633     task_free(task_sent_s);
634   }
635
636 }
637
638 /**
639  * \brief Makes the current node find the successor node of an id.
640  * \param node the current node
641  * \param id the id to find
642  * \return the id of the successor node, or -1 if the request failed
643  */
644 static int find_successor(node_t node, int id)
645 {
646   // is my successor the successor?
647   if (is_in_interval(id, node->id + 1, node->fingers[0].id)) {
648     return node->fingers[0].id;
649   }
650
651   // otherwise, ask the closest preceding finger in my table
652   int closest = closest_preceding_node(node, id);
653   return remote_find_successor(node, closest, id);
654 }
655
656 /**
657  * \brief Asks another node the successor node of an id.
658  * \param node the current node
659  * \param ask_to the node to ask to
660  * \param id the id to find
661  * \return the id of the successor node, or -1 if the request failed
662  */
663 static int remote_find_successor(node_t node, int ask_to, int id)
664 {
665   int successor = -1;
666   int stop = 0;
667   char mailbox[MAILBOX_NAME_SIZE];
668   get_mailbox(ask_to, mailbox);
669   task_data_t req_data = xbt_new0(s_task_data_t, 1);
670   req_data->type = TASK_FIND_SUCCESSOR;
671   req_data->request_id = id;
672   get_mailbox(node->id, req_data->answer_to);
673   req_data->issuer_host_name = MSG_host_get_name(MSG_host_self());
674
675   // send a "Find Successor" request to ask_to_id
676   msg_task_t task_sent = MSG_task_create(NULL, COMP_SIZE, COMM_SIZE, req_data);
677   XBT_DEBUG("Sending a 'Find Successor' request (task %p) to %d for id %d", task_sent, ask_to, id);
678   msg_error_t res = MSG_task_send_with_timeout(task_sent, mailbox, timeout);
679
680   if (res != MSG_OK) {
681     XBT_DEBUG("Failed to send the 'Find Successor' request (task %p) to %d for id %d",
682         task_sent, ask_to, id);
683     task_free(task_sent);
684   }
685   else {
686
687     // receive the answer
688     XBT_DEBUG("Sent a 'Find Successor' request (task %p) to %d for key %d, waiting for the answer",
689         task_sent, ask_to, id);
690
691     do {
692       if (node->comm_receive == NULL) {
693         msg_task_t task_received = NULL;
694         node->comm_receive = MSG_task_irecv(&task_received, node->mailbox);
695       }
696
697       res = MSG_comm_wait(node->comm_receive, timeout);
698
699       if (res != MSG_OK) {
700         XBT_DEBUG("Failed to receive the answer to my 'Find Successor' request (task %p): %d",
701                   task_sent, (int)res);
702         stop = 1;
703         MSG_comm_destroy(node->comm_receive);
704         node->comm_receive = NULL;
705       }
706       else {
707         msg_task_t task_received = MSG_comm_get_task(node->comm_receive);
708         XBT_DEBUG("Received a task (%p)", task_received);
709         task_data_t ans_data = MSG_task_get_data(task_received);
710
711         // Once upon a time, our code assumed that here, task_received != task_sent all the time
712         // 
713         // This assumption is wrong (as messages from differing round can interleave), leading to a bug in our code.
714         // We failed to find this bug directly, as it only occured on large platforms, leading to hardly usable traces.
715         // Instead, we used the model-checker to track down the issue by adding the following test here in the code:
716         //   if (MC_is_active()) {
717         //      MC_assert(task_received == task_sent);
718         //   }
719         // That explained the bug in a snap, with a very cool example and everything.
720         // 
721         // This MC_assert is now desactivated as the case is now properly handled in our code and we don't want the
722         //   MC to fail any further under that condition, but this comment is here to as a memorial for this first 
723         //   brillant victory of the model-checking in the SimGrid community :)
724
725         if (task_received != task_sent) {
726           // this is not the expected answer
727           MSG_comm_destroy(node->comm_receive);
728           node->comm_receive = NULL;
729           handle_task(node, task_received);
730         }
731         else {
732           // this is our answer
733           XBT_DEBUG("Received the answer to my 'Find Successor' request for id %d (task %p): the successor of key %d is %d",
734               ans_data->request_id, task_received, id, ans_data->answer_id);
735           successor = ans_data->answer_id;
736           stop = 1;
737           MSG_comm_destroy(node->comm_receive);
738           node->comm_receive = NULL;
739           task_free(task_received);
740         }
741       }
742     } while (!stop);
743   }
744
745   return successor;
746 }
747
748 /**
749  * \brief Asks another node its predecessor.
750  * \param node the current node
751  * \param ask_to the node to ask to
752  * \return the id of its predecessor node, or -1 if the request failed
753  * (or if the node does not know its predecessor)
754  */
755 static int remote_get_predecessor(node_t node, int ask_to)
756 {
757   int predecessor_id = -1;
758   int stop = 0;
759   char mailbox[MAILBOX_NAME_SIZE];
760   get_mailbox(ask_to, mailbox);
761   task_data_t req_data = xbt_new0(s_task_data_t, 1);
762   req_data->type = TASK_GET_PREDECESSOR;
763   get_mailbox(node->id, req_data->answer_to);
764   req_data->issuer_host_name = MSG_host_get_name(MSG_host_self());
765
766   // send a "Get Predecessor" request to ask_to_id
767   XBT_DEBUG("Sending a 'Get Predecessor' request to %d", ask_to);
768   msg_task_t task_sent = MSG_task_create(NULL, COMP_SIZE, COMM_SIZE, req_data);
769   msg_error_t res = MSG_task_send_with_timeout(task_sent, mailbox, timeout);
770
771   if (res != MSG_OK) {
772     XBT_DEBUG("Failed to send the 'Get Predecessor' request (task %p) to %d",
773         task_sent, ask_to);
774     task_free(task_sent);
775   }
776   else {
777
778     // receive the answer
779     XBT_DEBUG("Sent 'Get Predecessor' request (task %p) to %d, waiting for the answer on my mailbox '%s'",
780         task_sent, ask_to, req_data->answer_to);
781
782     do {
783       if (node->comm_receive == NULL) { // FIXME simplify this
784         msg_task_t task_received = NULL;
785         node->comm_receive = MSG_task_irecv(&task_received, node->mailbox);
786       }
787
788       res = MSG_comm_wait(node->comm_receive, timeout);
789
790       if (res != MSG_OK) {
791         XBT_DEBUG("Failed to receive the answer to my 'Get Predecessor' request (task %p): %d",
792             task_sent, (int)res);
793         stop = 1;
794         MSG_comm_destroy(node->comm_receive);
795         node->comm_receive = NULL;
796         task_free(task_sent);
797       }
798       else {
799         msg_task_t task_received = MSG_comm_get_task(node->comm_receive);
800         task_data_t ans_data = MSG_task_get_data(task_received);
801
802         /*if (MC_is_active()) {
803           MC_assert(task_received == task_sent);
804           }*/
805
806         if (task_received != task_sent) {
807           MSG_comm_destroy(node->comm_receive);
808           node->comm_receive = NULL;
809           handle_task(node, task_received);
810         }
811         else {
812           XBT_DEBUG("Received the answer to my 'Get Predecessor' request (task %p): the predecessor of node %d is %d",
813               task_received, ask_to, ans_data->answer_id);
814           predecessor_id = ans_data->answer_id;
815           stop = 1;
816           MSG_comm_destroy(node->comm_receive);
817           node->comm_receive = NULL;
818           task_free(task_received);
819         }
820       }
821     } while (!stop);
822   }
823
824   return predecessor_id;
825 }
826
827 /**
828  * \brief Returns the closest preceding finger of an id
829  * with respect to the finger table of the current node.
830  * \param node the current node
831  * \param id the id to find
832  * \return the closest preceding finger of that id
833  */
834 int closest_preceding_node(node_t node, int id)
835 {
836   int i;
837   for (i = nb_bits - 1; i >= 0; i--) {
838     if (is_in_interval(node->fingers[i].id, node->id + 1, id - 1)) {
839       return node->fingers[i].id;
840     }
841   }
842   return node->id;
843 }
844
845 /**
846  * \brief This function is called periodically. It checks the immediate
847  * successor of the current node.
848  * \param node the current node
849  */
850 static void stabilize(node_t node)
851 {
852   XBT_DEBUG("Stabilizing node");
853
854   // get the predecessor of my immediate successor
855   int candidate_id;
856   int successor_id = node->fingers[0].id;
857   if (successor_id != node->id) {
858     candidate_id = remote_get_predecessor(node, successor_id);
859   }
860   else {
861     candidate_id = node->pred_id;
862   }
863
864   // this node is a candidate to become my new successor
865   if (candidate_id != -1
866       && is_in_interval(candidate_id, node->id + 1, successor_id - 1)) {
867     set_finger(node, 0, candidate_id);
868   }
869   if (successor_id != node->id) {
870     remote_notify(node, successor_id, node->id);
871   }
872 }
873
874 /**
875  * \brief Notifies the current node that its predecessor may have changed.
876  * \param node the current node
877  * \param candidate_id the possible new predecessor
878  */
879 static void notify(node_t node, int predecessor_candidate_id) {
880
881   if (node->pred_id == -1
882     || is_in_interval(predecessor_candidate_id, node->pred_id + 1, node->id - 1)) {
883
884     set_predecessor(node, predecessor_candidate_id);
885     print_finger_table(node);
886   }
887   else {
888     XBT_DEBUG("I don't have to change my predecessor to %d", predecessor_candidate_id);
889   }
890 }
891
892 /**
893  * \brief Notifies a remote node that its predecessor may have changed.
894  * \param node the current node
895  * \param notify_id id of the node to notify
896  * \param candidate_id the possible new predecessor
897  */
898 static void remote_notify(node_t node, int notify_id, int predecessor_candidate_id) {
899
900       task_data_t req_data = xbt_new0(s_task_data_t, 1);
901       req_data->type = TASK_NOTIFY;
902       req_data->request_id = predecessor_candidate_id;
903       req_data->issuer_host_name = MSG_host_get_name(MSG_host_self());
904
905       // send a "Notify" request to notify_id
906       msg_task_t task = MSG_task_create(NULL, COMP_SIZE, COMM_SIZE, req_data);
907       XBT_DEBUG("Sending a 'Notify' request (task %p) to %d", task, notify_id);
908       char mailbox[MAILBOX_NAME_SIZE];
909       get_mailbox(notify_id, mailbox);
910       MSG_task_dsend(task, mailbox, task_free);
911     }
912
913 /**
914  * \brief This function is called periodically.
915  * It refreshes the finger table of the current node.
916  * \param node the current node
917  */
918 static void fix_fingers(node_t node) {
919
920   XBT_DEBUG("Fixing fingers");
921   int i = node->next_finger_to_fix;
922   int id = find_successor(node, node->id + powers2[i]);
923   if (id != -1) {
924
925     if (id != node->fingers[i].id) {
926       set_finger(node, i, id);
927       print_finger_table(node);
928     }
929     node->next_finger_to_fix = (i + 1) % nb_bits;
930   }
931 }
932
933 /**
934  * \brief This function is called periodically.
935  * It checks whether the predecessor has failed
936  * \param node the current node
937  */
938 static void check_predecessor(node_t node)
939 {
940   XBT_DEBUG("Checking whether my predecessor is alive");
941
942   if(node->pred_id == -1)
943     return;
944
945   int stop = 0;
946
947   char mailbox[MAILBOX_NAME_SIZE];
948   get_mailbox(node->pred_id, mailbox);
949   task_data_t req_data = xbt_new0(s_task_data_t,1);
950   req_data->type = TASK_PREDECESSOR_ALIVE;
951   req_data->request_id = node->pred_id;
952   get_mailbox(node->id, req_data->answer_to);
953   req_data->issuer_host_name = MSG_host_get_name(MSG_host_self());
954
955   msg_task_t task_sent = MSG_task_create(NULL, COMP_SIZE, COMM_SIZE, req_data);
956   XBT_DEBUG("Sending a 'Predecessor Alive' request to my predecessor %d", node->pred_id);
957   
958   msg_error_t res = MSG_task_send_with_timeout(task_sent, mailbox, timeout);
959   
960   if (res != MSG_OK) {
961     XBT_DEBUG("Failed to send the 'Predecessor Alive' request (task %p) to %d", task_sent, node->pred_id);
962     task_free(task_sent);
963   }else{
964
965     // receive the answer
966     XBT_DEBUG("Sent 'Predecessor Alive' request (task %p) to %d, waiting for the answer on my mailbox '%s'",
967               task_sent, node->pred_id, req_data->answer_to);
968
969     do {
970       if (node->comm_receive == NULL) { // FIXME simplify this
971         msg_task_t task_received = NULL;
972         node->comm_receive = MSG_task_irecv(&task_received, node->mailbox);
973       }
974
975       res = MSG_comm_wait(node->comm_receive, timeout);
976
977       if (res != MSG_OK) {
978         XBT_DEBUG("Failed to receive the answer to my 'Predecessor Alive' request (task %p): %d",
979                   task_sent, (int)res);
980         stop = 1;
981         MSG_comm_destroy(node->comm_receive);
982         node->comm_receive = NULL;
983         node->pred_id = -1;
984       }else {
985         msg_task_t task_received = MSG_comm_get_task(node->comm_receive);
986         if (task_received != task_sent) {
987           MSG_comm_destroy(node->comm_receive);
988           node->comm_receive = NULL;
989           handle_task(node, task_received);
990         }else{
991           XBT_DEBUG("Received the answer to my 'Predecessor Alive' request (task %p) : my predecessor %d is alive", task_received, node->pred_id);
992           stop = 1;
993           MSG_comm_destroy(node->comm_receive);
994           node->comm_receive = NULL;
995           task_free(task_received);
996         }
997       }
998     } while (!stop);
999   }
1000 }
1001
1002 /**
1003  * \brief Performs a find successor request to a random id.
1004  * \param node the current node
1005  */
1006 static void random_lookup(node_t node)
1007 {
1008   
1009   int id = 1337; 
1010   find_successor(node, id);
1011
1012   /*** Random lookup disabled for tesh examples ***/
1013   /*if(node->stream == NULL)
1014     node->stream = RngStream_CreateStream("");
1015   int random_index = RngStream_RandInt (node->stream, 0, nb_bits - 1);
1016   int random_id = node->fingers[random_index].id;
1017   XBT_DEBUG("Making a lookup request for id %d", random_id);
1018   int res = find_successor(node, random_id);
1019   XBT_DEBUG("The successor of node %d is %d", random_id, res);*/
1020
1021 }
1022
1023 /**
1024  * \brief Main function.
1025  */
1026 int main(int argc, char *argv[])
1027 {
1028   MSG_init(&argc, argv);
1029   if (argc < 3) {
1030     printf("Usage: %s [-nb_bits=n] [-timeout=t] platform_file deployment_file\n", argv[0]);
1031     printf("example: %s ../msg_platform.xml chord.xml\n", argv[0]);
1032     exit(1);
1033   }
1034
1035   char **options = &argv[1];
1036   while (!strncmp(options[0], "-", 1)) {
1037
1038     int length = strlen("-nb_bits=");
1039     if (!strncmp(options[0], "-nb_bits=", length) && strlen(options[0]) > length) {
1040       nb_bits = atoi(options[0] + length);
1041       XBT_DEBUG("Set nb_bits to %d", nb_bits);
1042     }
1043     else {
1044
1045       length = strlen("-timeout=");
1046       if (!strncmp(options[0], "-timeout=", length) && strlen(options[0]) > length) {
1047         timeout = atoi(options[0] + length);
1048         XBT_DEBUG("Set timeout to %d", timeout);
1049       }
1050       else {
1051         xbt_die("Invalid chord option '%s'", options[0]);
1052       }
1053     }
1054     options++;
1055   }
1056
1057   const char* platform_file = options[0];
1058   const char* application_file = options[1];
1059
1060   chord_initialize();
1061
1062   MSG_create_environment(platform_file);
1063
1064   MSG_function_register("node", node);
1065   MSG_launch_application(application_file);
1066
1067   msg_error_t res = MSG_main();
1068   XBT_CRITICAL("Messages created: %ld", smx_total_comms);
1069   XBT_INFO("Simulated time: %g", MSG_get_clock());
1070
1071   chord_exit();
1072
1073   if (res == MSG_OK)
1074     return 0;
1075   else
1076     return 1;
1077 }