Logo AND Algorithmique Numérique Distribuée

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