Logo AND Algorithmique Numérique Distribuée

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