Logo AND Algorithmique Numérique Distribuée

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