Logo AND Algorithmique Numérique Distribuée

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