Logo AND Algorithmique Numérique Distribuée

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