Logo AND Algorithmique Numérique Distribuée

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