Logo AND Algorithmique Numérique Distribuée

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