Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
fix example (bummer)
[simgrid.git] / examples / msg / dht-pastry / dht-pastry.c
1 /* Copyright (c) 2013-2015. The SimGrid Team.
2  * All rights reserved.                                                     */
3
4 /* This program is free software; you can redistribute it and/or modify it
5  * under the terms of the license (GNU LGPL) which comes with this package. */
6
7 #include "simgrid/msg.h"
8 #include "xbt/dynar.h"
9 #include <math.h>
10
11
12 XBT_LOG_NEW_DEFAULT_CATEGORY(msg_pastry, "Messages specific for this msg example");
13
14 /* TODO:                               *
15  *  - handle node departure            *
16  *  - handle objects on the network    *
17  *  - handle neighborhood in the update */
18
19 #define COMM_SIZE 10
20 #define COMP_SIZE 0
21 #define MAILBOX_NAME_SIZE 10
22
23 #define DOMAIN_SIZE 4
24 #define LEVELS_COUNT 8 // sizeof(int)*8/DOMAIN_SIZE
25 #define LEVEL_SIZE 16 // 2^DOMAIN_SIZE
26 #define NEIGHBORHOOD_SIZE 6
27 #define NAMESPACE_SIZE 6
28 #define MAILBOX_NAME_SIZE 10
29
30 static int nb_bits = 16;
31 static int timeout = 50;
32 static int max_simulation_time = 1000;
33
34 typedef struct s_node {
35   int id;                                 //128bits generated random(2^128 -1)
36   int known_id;
37   char mailbox[MAILBOX_NAME_SIZE];        // my mailbox name (string representation of the id)
38   int namespace_set[NAMESPACE_SIZE];
39   int neighborhood_set[NEIGHBORHOOD_SIZE];
40   int routing_table[LEVELS_COUNT][LEVEL_SIZE];
41   int ready;
42   msg_comm_t comm_receive;                // current communication to receive
43   xbt_dynar_t pending_tasks;
44 } s_node_t;
45 typedef s_node_t* node_t;
46
47 typedef struct s_state {
48   int id;
49   int namespace_set[NAMESPACE_SIZE];
50   int neighborhood_set[NEIGHBORHOOD_SIZE];
51   int routing_table[LEVELS_COUNT][LEVEL_SIZE];
52 } s_state_t;
53 typedef s_state_t* state_t;
54
55 /** Types of tasks exchanged between nodes. */
56 typedef enum {
57   TASK_JOIN,
58   TASK_JOIN_REPLY,
59   TASK_JOIN_LAST_REPLY,
60   TASK_UPDATE
61 } e_task_type_t;
62
63 typedef struct s_task_data {
64   e_task_type_t type;                     // type of task
65   int sender_id;                          // id parameter (used by some types of tasks)
66   //int request_finger;                     // finger parameter (used by some types of tasks)
67   int answer_id;                          // answer (used by some types of tasks)
68   char answer_to[MAILBOX_NAME_SIZE];      // mailbox to send an answer to (if any)
69   //const char* issuer_host_name;           // used for logging
70   int steps;
71   state_t state;
72 } s_task_data_t;
73 typedef s_task_data_t* task_data_t;
74
75 static int domain(unsigned int a, unsigned int level);
76 static int shl(int a, int b);
77 static int closest_in_namespace_set(node_t node, int dest);
78 static int routing_next(node_t node, int dest);
79
80 /**
81  * \brief Gets the mailbox name of a host given its chord id.
82  * \param node_id id of a node
83  * \param mailbox pointer to where the mailbox name should be written
84  * (there must be enough space)
85  */
86 static void get_mailbox(int node_id, char* mailbox)
87 {
88   snprintf(mailbox, MAILBOX_NAME_SIZE - 1, "%d", node_id);
89 }
90
91 /** Get the specific level of a node id */
92 unsigned int domain_mask = 0;
93 static int domain(unsigned int a, unsigned int level)
94 {
95   if (domain_mask == 0)
96     domain_mask = pow(2, DOMAIN_SIZE) - 1;
97   unsigned int shift = (LEVELS_COUNT-level-1)*DOMAIN_SIZE;
98   return (a >> shift) & domain_mask;
99 }
100
101 /* Get the shared domains between the two givens ids */
102 static int shl(int a, int b) {
103   int l = 0;
104   while(l<LEVELS_COUNT && domain(a,l) == domain(b,l))
105     l++;
106   return l;
107 }
108
109 /* Frees the memory used by a task and destroy it */
110 static void task_free(void* task)
111 {
112   if(task != NULL){
113     s_task_data_t* data = (s_task_data_t*)MSG_task_get_data(task);
114     xbt_free(data->state);
115     xbt_free(data);
116     MSG_task_destroy(task);
117   }
118 }
119
120 /* Get the closest id to the dest in the node namespace_set */
121 static int closest_in_namespace_set(node_t node, int dest) {
122   int res = -1;
123   if ((node->namespace_set[NAMESPACE_SIZE-1] <= dest) && (dest <= node->namespace_set[0])) {
124     int best_dist = abs(node->id - dest);
125     res = node->id;
126     for (int i=0; i<NAMESPACE_SIZE; i++) {
127       if (node->namespace_set[i]!=-1) {
128         int dist = abs(node->namespace_set[i] - dest);
129         if (dist<best_dist) {
130           best_dist = dist;
131           res = node->namespace_set[i];
132         }
133       }
134     }
135   }
136   return res;
137 }
138
139 /* Find the next node to forward a message to */
140 static int routing_next(node_t node, int dest) {
141   int closest = closest_in_namespace_set(node, dest);
142   if (closest!=-1)
143     return closest;
144
145   int l = shl(node->id, dest);
146   int res = node->routing_table[l][domain(dest, l)];
147   if (res != -1)
148     return res;
149
150   //rare case
151   int dist = abs(node->id - dest);
152   for (int i=l; i<LEVELS_COUNT; i++) {
153     for (int j=0; j<LEVEL_SIZE; j++) {
154       res = node->routing_table[i][j];
155       if (res!=-1 && abs(res - dest)<dist)
156         return res;
157     }
158   }
159
160   for (int i=0; i<NEIGHBORHOOD_SIZE; i++) {
161     res = node->neighborhood_set[i];
162     if (res!=-1 && shl(res, dest)>=l && abs(res - dest)<dist)
163         return res;
164   }
165
166   for (int i=0; i<NAMESPACE_SIZE; i++) {
167     res = node->namespace_set[i];
168     if (res!=-1 && shl(res, dest)>=l && abs(res - dest)<dist)
169         return res;
170   }
171
172   return node->id;
173 }
174
175 /* Get the corresponding state of a node */
176 static state_t node_get_state(node_t node) {
177   state_t state = xbt_new0(s_state_t,1);
178   state->id = node->id;
179   for (int i=0; i<NEIGHBORHOOD_SIZE; i++)
180     state->neighborhood_set[i] = node->neighborhood_set[i];
181
182   for (int i=0; i<LEVELS_COUNT; i++)
183     for (int j=0; j<LEVEL_SIZE; j++)
184       state->routing_table[i][j] = node->routing_table[i][j];
185
186   for (int i=0; i<NAMESPACE_SIZE; i++)
187     state->namespace_set[i] = node->namespace_set[i];
188
189   return state;
190 }
191
192 static void print_node_id(node_t node) {
193   XBT_INFO(" Id: %i '%08x' ", node->id, node->id);
194 }
195
196 static void print_node_neighborood_set(node_t node) {
197   XBT_INFO(" Neighborhood:");
198   for (int i=0; i<NEIGHBORHOOD_SIZE; i++)
199     XBT_INFO("  %08x", node->neighborhood_set[i]);
200 }
201
202 static void print_node_routing_table(node_t node) {
203   XBT_INFO(" Routing table:");
204   for (int i=0; i<LEVELS_COUNT; i++){
205     for (int j=0; j<LEVEL_SIZE; j++)
206       XBT_INFO("  %08x ", node->routing_table[i][j]);
207   }
208 }
209 /* Print the node namespace set */
210 static void print_node_namespace_set(node_t node) {
211   XBT_INFO(" Namespace:");
212   for (int i=0; i<NAMESPACE_SIZE; i++)
213     XBT_INFO("  %08x", node->namespace_set[i]);
214 }
215
216 /* Print the node information */
217 static void print_node(node_t node) {
218   XBT_INFO("Node:");
219   print_node_id(node);
220   print_node_neighborood_set(node);
221   print_node_routing_table(node);
222   print_node_namespace_set(node);
223 }
224
225 /** Handle a given task */
226 static void handle_task(node_t node, msg_task_t task) {
227   XBT_DEBUG("Handling task %p", task);
228   char mailbox[MAILBOX_NAME_SIZE];
229   int i;
230   int j;
231   int min;
232   int max;
233   int d;
234   int next;
235   msg_task_t task_sent;
236   task_data_t req_data;
237   task_data_t task_data = (task_data_t) MSG_task_get_data(task);
238   e_task_type_t type = task_data->type;
239   // If the node is not ready keep the task for later
240   if (node->ready != 0 && !(type==TASK_JOIN_LAST_REPLY || type==TASK_JOIN_REPLY)) {
241     XBT_DEBUG("Task pending %i", type);
242     xbt_dynar_push(node->pending_tasks, &task);
243     return;
244   }
245   switch (type) {
246     /* Try to join the ring */
247     case TASK_JOIN:
248       next = routing_next(node, task_data->answer_id);
249       XBT_DEBUG("Join request from %08x forwarding to %08x", task_data->answer_id, next);      
250       type = TASK_JOIN_LAST_REPLY;
251
252       req_data = xbt_new0(s_task_data_t,1);
253       req_data->answer_id = task_data->sender_id;
254       req_data->steps = task_data->steps + 1;
255       
256       // if next different from current node forward the join
257       if (next!=node->id) {
258         get_mailbox(next, mailbox);
259         task_data->sender_id = node->id;
260         task_data->steps++;
261         task_sent = MSG_task_create(NULL, COMP_SIZE, COMM_SIZE, task_data);
262         if (MSG_task_send_with_timeout(task_sent, mailbox, timeout)== MSG_TIMEOUT) {
263           XBT_DEBUG("Timeout expired when forwarding join to next %d", next);
264           task_free(task_sent);
265         }
266         type = TASK_JOIN_REPLY;
267       } 
268       
269       // send back the current node state to the joining node
270       req_data->type = type;
271       req_data->sender_id = node->id;
272       get_mailbox(node->id, req_data->answer_to);
273       req_data->state = node_get_state(node);
274       task_sent = MSG_task_create(NULL, COMP_SIZE, COMM_SIZE, req_data);
275       if (MSG_task_send_with_timeout(task_sent, task_data->answer_to, timeout)== MSG_TIMEOUT) {
276         XBT_DEBUG("Timeout expired when sending back the current node state to the joining node to %d", node->id);
277         task_free(task_sent);
278       }
279       break;
280     /* Join reply from all the node touched by the join  */
281     case TASK_JOIN_LAST_REPLY:
282       // if last node touched reply, copy its namespace set
283       // TODO: it works only if the two nodes are side to side (is it really the case ?)
284       j = (task_data->sender_id < node->id) ? -1 : 0;
285       for (i=0; i<NAMESPACE_SIZE/2; i++) {
286         node->namespace_set[i] = task_data->state->namespace_set[i-j];
287         node->namespace_set[NAMESPACE_SIZE-1-i] = task_data->state->namespace_set[NAMESPACE_SIZE-1-i-j-1];
288       }
289       node->namespace_set[NAMESPACE_SIZE/2+j] = task_data->sender_id;
290       node->ready += task_data->steps + 1;
291       /* no break */
292     case TASK_JOIN_REPLY:
293       XBT_DEBUG("Joining Reply");
294
295       // if first node touched reply, copy its neighborhood set
296       if (task_data->sender_id == node->known_id) {
297         node->neighborhood_set[0] = task_data->sender_id;
298         for (i=1; i<NEIGHBORHOOD_SIZE; i++)
299           node->neighborhood_set[i] = task_data->state->neighborhood_set[i-1];
300       }
301
302       // copy the corresponding routing table levels
303       min = (node->id==task_data->answer_id) ? 0 : shl(node->id, task_data->answer_id);
304       max = shl(node->id, task_data->sender_id)+1;
305       for (i=min;i<max;i++) {
306         d = domain(node->id, i); 
307         for (j=0; j<LEVEL_SIZE; j++)
308           if (d!=j)
309             node->routing_table[i][j] =  task_data->state->routing_table[i][j];
310           }
311
312       node->ready--;
313       // if the node is ready, do all the pending tasks and send update to known nodes
314       if (node->ready==0) {
315         XBT_DEBUG("Node %i is ready!!!", node->id);
316         while(xbt_dynar_length(node->pending_tasks)){
317           msg_task_t task;
318           xbt_dynar_shift(node->pending_tasks, &task);
319           handle_task(node, task);
320         }
321
322         for (i=0; i<NAMESPACE_SIZE; i++) {
323           j = node->namespace_set[i];
324           if (j!=-1) {
325             XBT_DEBUG("Send update to %i", j);
326             get_mailbox(j, mailbox);
327
328             req_data = xbt_new0(s_task_data_t,1);
329             req_data->answer_id = node->id;
330             req_data->steps = 0;
331             req_data->type = TASK_UPDATE;
332             req_data->sender_id = node->id;
333             get_mailbox(node->id, req_data->answer_to);
334             req_data->state = node_get_state(node);
335             task_sent = MSG_task_create(NULL, COMP_SIZE, COMM_SIZE, req_data);
336             if (MSG_task_send_with_timeout(task_sent, mailbox, timeout)== MSG_TIMEOUT) {
337               XBT_DEBUG("Timeout expired when sending update to %d", j);
338               task_free(task_sent);
339             }
340           }
341         }
342         }
343       break;
344     /* Received an update of state */
345     case TASK_UPDATE:
346       XBT_DEBUG("Task update %i !!!", node->id);
347
348       /* Update namespace ses */
349       XBT_INFO("Task update from %i !!!", task_data->sender_id);
350       XBT_INFO("Node:");
351       print_node_id(node);
352       print_node_namespace_set(node);
353       int curr_namespace_set[NAMESPACE_SIZE];
354       int task_namespace_set[NAMESPACE_SIZE+1];
355       
356       // Copy the current namespace and the task state namespace with state->id in the middle
357       i=0;
358       for (; i<NAMESPACE_SIZE/2; i++){
359         curr_namespace_set[i] = node->namespace_set[i];
360         task_namespace_set[i] = task_data->state->namespace_set[i];
361       }
362       task_namespace_set[i] = task_data->state->id;
363       for (; i<NAMESPACE_SIZE; i++){
364         curr_namespace_set[i] = node->namespace_set[i];  
365         task_namespace_set[i+1] = task_data->state->namespace_set[i];
366       }
367
368       // get the index of values before and after node->id in task_namespace
369       min = -1;
370       max = -1;
371       for (i=0; i<=NAMESPACE_SIZE; i++) {
372         j = task_namespace_set[i];
373         if (j != -1 && j < node->id)
374           min = i;
375         if (j != -1 && max == -1 && j > node->id)
376           max = i;
377       }
378
379       // add lower elements
380       j = NAMESPACE_SIZE/2-1;
381       for (i=NAMESPACE_SIZE/2-1; i>=0; i--) {
382         if (min<0) {
383           node->namespace_set[i] = curr_namespace_set[j];
384           j--;
385         } else if (curr_namespace_set[j] == task_namespace_set[min]) {
386           node->namespace_set[i] = curr_namespace_set[j];
387           j--;
388           min--;
389         } else if (curr_namespace_set[j] > task_namespace_set[min]) {
390           node->namespace_set[i] = curr_namespace_set[j];
391           j--;
392         } else {
393           node->namespace_set[i] = task_namespace_set[min];
394           min--;
395         }
396       }
397
398       // add greater elements
399       j = NAMESPACE_SIZE/2;
400       for (i=NAMESPACE_SIZE/2; i<NAMESPACE_SIZE; i++) {
401         if (min<0 || max>=NAMESPACE_SIZE) {
402          node->namespace_set[i] = curr_namespace_set[j];
403          j++;
404         } else if (max >= 0){
405           if (curr_namespace_set[j] == -1) {
406             node->namespace_set[i] = task_namespace_set[max];
407             max++;
408           } else if (curr_namespace_set[j] == task_namespace_set[max]) {
409             node->namespace_set[i] = curr_namespace_set[j];
410             j++;
411             max++;
412           } else if (curr_namespace_set[j] < task_namespace_set[max]) {
413             node->namespace_set[i] = curr_namespace_set[j];
414             j++;
415           } else {
416             node->namespace_set[i] = task_namespace_set[max];
417             max++;
418           }
419         }
420       }
421
422       /* Update routing table */
423       for (i=shl(node->id, task_data->state->id); i<LEVELS_COUNT; i++) {
424         for (j=0; j<LEVEL_SIZE; j++) {
425           if (node->routing_table[i][j]==-1 && task_data->state->routing_table[i][j]==-1)
426             node->routing_table[i][j] = task_data->state->routing_table[i][j];
427         }
428       }
429       break;
430     default:
431       THROW_IMPOSSIBLE;
432   }
433   task_free(task);
434 }
435
436 /* Join the ring */
437 static int join(node_t node){
438   task_data_t req_data = xbt_new0(s_task_data_t,1);
439   req_data->type = TASK_JOIN;
440   req_data->sender_id = node->id;
441   req_data->answer_id = node->id;
442   req_data->steps = 0;
443   get_mailbox(node->id, req_data->answer_to);
444
445   char mailbox[MAILBOX_NAME_SIZE];
446   get_mailbox(node->known_id, mailbox);
447
448   msg_task_t task_sent = MSG_task_create(NULL, COMP_SIZE, COMM_SIZE, req_data);
449   XBT_DEBUG("Trying to join Pastry ring... (with node %s)", mailbox);
450   if (MSG_task_send_with_timeout(task_sent, mailbox, timeout)== MSG_TIMEOUT) {
451     XBT_DEBUG("Timeout expired when joining ring with node %d", node->known_id);
452     task_free(task_sent);
453   }
454
455   return 1;
456 }
457
458 /**
459  * \brief Node Function
460  * Arguments:
461  * - my id
462  * - the id of a guy I know in the system (except for the first node)
463  * - the time to sleep before I join (except for the first node)
464  * - the deadline time
465  */
466 static int node(int argc, char *argv[])
467 {
468   double init_time = MSG_get_clock();
469   msg_task_t task_received = NULL;  
470   int join_success = 0;  
471   double deadline;
472   xbt_assert(argc == 3 || argc == 5, "Wrong number of arguments for this node");
473   s_node_t node = {0};
474   node.id = xbt_str_parse_int(argv[1], "Invalid ID: %s");
475   node.known_id = -1;
476   node.ready = -1;
477   node.pending_tasks = xbt_dynar_new(sizeof(msg_task_t), NULL);
478   get_mailbox(node.id, node.mailbox);
479   XBT_DEBUG("New node with id %s (%08x)", node.mailbox, node.id);
480
481   for (int i=0; i<LEVELS_COUNT; i++){
482     int d = domain(node.id, i);
483     for (int j=0; j<LEVEL_SIZE; j++)
484       node.routing_table[i][j] = (d==j) ? node.id : -1;
485   }
486
487   for (int i=0; i<NEIGHBORHOOD_SIZE; i++)
488     node.neighborhood_set[i] = -1;
489
490   for (int i=0; i<NAMESPACE_SIZE; i++)
491     node.namespace_set[i] = -1;
492
493   if (argc == 3) { // first ring
494     XBT_DEBUG("Hey! Let's create the system.");
495     deadline = xbt_str_parse_double(argv[2], "Invalid deadline: %s");
496     node.ready = 0;
497     XBT_DEBUG("Create a new Pastry ring...");
498     join_success = 1;
499   } else {
500     node.known_id = xbt_str_parse_int(argv[2], "Invalid known ID: %s");
501     double sleep_time = xbt_str_parse_double(argv[3], "Invalid sleep time: %s");
502     deadline = xbt_str_parse_double(argv[4], "Invalid deadline: %s");
503
504     // sleep before starting
505     XBT_DEBUG("Let's sleep during %f", sleep_time);
506     MSG_process_sleep(sleep_time);
507     XBT_DEBUG("Hey! Let's join the system.");
508
509     join_success = join(&node);
510   }
511
512   if (join_success) {
513     XBT_DEBUG("Waiting ….");
514
515     while (MSG_get_clock() < init_time + deadline
516 //      && MSG_get_clock() < node.last_change_date + 1000
517         && MSG_get_clock() < max_simulation_time) {
518       if (node.comm_receive == NULL) {
519         task_received = NULL;
520         node.comm_receive = MSG_task_irecv(&task_received, node.mailbox);
521         // FIXME: do not make MSG_task_irecv() calls from several functions
522       }
523       if (!MSG_comm_test(node.comm_receive)) {
524         MSG_process_sleep(5);
525       } else {
526         // a transfer has occurred
527
528         msg_error_t status = MSG_comm_get_status(node.comm_receive);
529
530         if (status != MSG_OK) {
531           XBT_DEBUG("Failed to receive a task. Nevermind.");
532           MSG_comm_destroy(node.comm_receive);
533           node.comm_receive = NULL;
534         } else {
535           // the task was successfully received
536           MSG_comm_destroy(node.comm_receive);
537           node.comm_receive = NULL;
538           handle_task(&node, task_received);
539         }
540       }
541
542     }
543   //Cleanup the receiving communication.
544   if (node.comm_receive != NULL) {
545     if (MSG_comm_test(node.comm_receive) && MSG_comm_get_status(node.comm_receive) == MSG_OK) {
546       task_free(MSG_comm_get_task(node.comm_receive));
547     }
548     MSG_comm_destroy(node.comm_receive);
549   }
550
551   }
552   xbt_dynar_free(&node.pending_tasks);
553   return 1;
554 }
555
556 /** \brief Main function. */
557 int main(int argc, char *argv[])
558 {
559   MSG_init(&argc, argv);
560   xbt_assert(argc > 2, 
561        "Usage: %s [-nb_bits=n] [-timeout=t] platform_file deployment_file\n"
562        "\tExample: %s ../msg_platform.xml pastry10.xml\n", 
563        argv[0], argv[0]);
564
565   char **options = &argv[1];
566   while (!strncmp(options[0], "-", 1)) {
567     int length = strlen("-nb_bits=");
568     if (!strncmp(options[0], "-nb_bits=", length) && strlen(options[0]) > length) {
569       nb_bits = xbt_str_parse_int(options[0] + length, "Invalid nb_bits parameter: %s");
570       XBT_DEBUG("Set nb_bits to %d", nb_bits);
571     } else {
572       length = strlen("-timeout=");
573       if (!strncmp(options[0], "-timeout=", length) && strlen(options[0]) > length) {
574         timeout = xbt_str_parse_int(options[0] + length, "Invalid timeout parameter: %s");
575         XBT_DEBUG("Set timeout to %d", timeout);
576       } else {
577         xbt_die("Invalid pastry option '%s'", options[0]);
578       }
579     }
580     options++;
581   }
582
583   MSG_create_environment(options[0]);
584
585   MSG_function_register("node", node);
586   MSG_launch_application(options[1]);
587
588   msg_error_t res = MSG_main();
589   XBT_INFO("Simulated time: %g", MSG_get_clock());
590
591   return res != MSG_OK;
592 }