Logo AND Algorithmique Numérique Distribuée

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