Logo AND Algorithmique Numérique Distribuée

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