Logo AND Algorithmique Numérique Distribuée

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