Logo AND Algorithmique Numérique Distribuée

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