Logo AND Algorithmique Numérique Distribuée

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