Logo AND Algorithmique Numérique Distribuée

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