Logo AND Algorithmique Numérique Distribuée

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