Logo AND Algorithmique Numérique Distribuée

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