Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge pull request #107 from adfaure/master
[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 unsigned 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   unsigned 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 res = -1;
119   if ((node->namespace_set[NAMESPACE_SIZE-1] <= dest) && (dest <= node->namespace_set[0])) {
120     int best_dist = abs(node->id - dest);
121     res = node->id;
122     for (int i=0; i<NAMESPACE_SIZE; i++) {
123       if (node->namespace_set[i]!=-1) {
124         int dist = abs(node->namespace_set[i] - dest);
125         if (dist<best_dist) {
126           best_dist = dist;
127           res = node->namespace_set[i];
128         }
129       }
130     }
131   }
132   return res;
133 }
134
135 /* Find the next node to forward a message to */
136 static int routing_next(node_t node, int dest) {
137   int closest = closest_in_namespace_set(node, dest);
138   int res = -1;
139   if (closest!=-1)
140     return closest;
141
142   int l = shl(node->id, dest);
143   res = node->routing_table[l][domain(dest, l)];
144   if (res!=-1)
145     return res;
146
147   //rare case
148   int dist = abs(node->id - dest);
149   int i;
150   for (i=l; i<LEVELS_COUNT; i++) {
151     for (int j=0; j<LEVEL_SIZE; j++) {
152       res = node->routing_table[i][j];
153       if (res!=-1 && abs(res - dest)<dist)
154         return res;
155     }
156   }
157
158   for (i=0; i<NEIGHBORHOOD_SIZE; i++) {
159     res = node->neighborhood_set[i];
160     if (res!=-1 && shl(res, dest)>=l && abs(res - dest)<dist)
161         return res;
162   }
163
164   for (i=0; i<NAMESPACE_SIZE; i++) {
165     res = node->namespace_set[i];
166     if (res!=-1 && shl(res, dest)>=l && abs(res - dest)<dist)
167         return res;
168   }
169
170   return node->id;
171 }
172
173 /* Get the corresponding state of a node */
174 static state_t node_get_state(node_t node) {
175   int i;
176   state_t state = xbt_new0(s_state_t,1);
177   state->id = node->id;
178   for (i=0; i<NEIGHBORHOOD_SIZE; i++)
179     state->neighborhood_set[i] = node->neighborhood_set[i];
180
181   for (i=0; i<LEVELS_COUNT; i++)
182     for (int j=0; j<LEVEL_SIZE; j++)
183       state->routing_table[i][j] = node->routing_table[i][j];
184
185   for (i=0; i<NAMESPACE_SIZE; i++)
186     state->namespace_set[i] = node->namespace_set[i];
187
188   return state;
189 }
190
191 /* Print the node id */
192 static void print_node_id(node_t node) {
193   XBT_INFO(" Id: %i '%08x' ", node->id, node->id);
194 }
195
196 /* * Print the node neighborhood set */
197 static void print_node_neighborood_set(node_t node) {
198   XBT_INFO(" Neighborhood:");
199   for (int i=0; i<NEIGHBORHOOD_SIZE; i++)
200     XBT_INFO("  %08x", node->neighborhood_set[i]);
201 }
202
203 /* Print the routing table */
204 static void print_node_routing_table(node_t node) {
205   XBT_INFO(" Routing table:");
206   for (int i=0; i<LEVELS_COUNT; i++){
207     for (int j=0; j<LEVEL_SIZE; j++)
208       XBT_INFO("  %08x ", node->routing_table[i][j]);
209   }
210 }
211
212 /* Print the node namespace set */
213 static void print_node_namespace_set(node_t node) {
214   XBT_INFO(" Namespace:");
215   for (int i=0; i<NAMESPACE_SIZE; i++)
216     XBT_INFO("  %08x", node->namespace_set[i]);
217 }
218
219 /* Print the node information */
220 static void print_node(node_t node) {
221   XBT_INFO("Node:");
222   print_node_id(node);
223   print_node_neighborood_set(node);
224   print_node_routing_table(node);
225   print_node_namespace_set(node);
226 }
227
228 /** Handle a given task */
229 static void handle_task(node_t node, msg_task_t task) {
230   XBT_DEBUG("Handling task %p", task);
231   char mailbox[MAILBOX_NAME_SIZE];
232   int i;
233   int j;
234   int min;
235   int max;
236   int d;
237   msg_task_t task_sent;
238   task_data_t req_data;
239   task_data_t task_data = (task_data_t) MSG_task_get_data(task);
240   e_task_type_t type = task_data->type;
241   // If the node is not ready keep the task for later
242   if (node->ready != 0 && !(type==TASK_JOIN_LAST_REPLY || type==TASK_JOIN_REPLY)) {
243     XBT_DEBUG("Task pending %i", type);
244     xbt_fifo_push(node->pending_tasks, task);
245     return;
246   }
247   switch (type) {
248     /* Try to join the ring */
249     case TASK_JOIN: {
250       int next = routing_next(node, task_data->answer_id);
251       XBT_DEBUG("Join request from %08x forwarding to %08x", task_data->answer_id, next);      
252       type = TASK_JOIN_LAST_REPLY;
253
254       req_data = xbt_new0(s_task_data_t,1);
255       req_data->answer_id = task_data->sender_id;
256       req_data->steps = task_data->steps + 1;
257       
258       // if next different from current node forward the join
259       if (next!=node->id) {
260         get_mailbox(next, mailbox);
261         task_data->sender_id = node->id;
262         task_data->steps++;
263         task_sent = MSG_task_create(NULL, COMP_SIZE, COMM_SIZE, task_data);
264         if (MSG_task_send_with_timeout(task_sent, mailbox, timeout)== MSG_TIMEOUT) {
265           XBT_DEBUG("Timeout expired when forwarding join to next %d", next);
266           task_free(task_sent);
267         }
268         type = TASK_JOIN_REPLY;
269       } 
270       
271       // send back the current node state to the joining node
272       req_data->type = type;
273       req_data->sender_id = node->id;
274       get_mailbox(node->id, req_data->answer_to);
275       req_data->state = node_get_state(node);
276       task_sent = MSG_task_create(NULL, COMP_SIZE, COMM_SIZE, req_data);
277       if (MSG_task_send_with_timeout(task_sent, task_data->answer_to, timeout)== MSG_TIMEOUT) {
278         XBT_DEBUG("Timeout expired when sending back the current node state to the joining node to %d", node->id);
279         task_free(task_sent);
280       }
281       break;
282     }
283     /* Join reply from all the node touched by the join  */
284     case TASK_JOIN_LAST_REPLY:
285       // if last node touched reply, copy its namespace set
286       // TODO: it's work only if the two nodes are side to side (is it really the case ?)
287       j = (task_data->sender_id < node->id) ? -1 : 0;
288       for (i=0; i<NAMESPACE_SIZE/2; i++) {
289         node->namespace_set[i] = task_data->state->namespace_set[i-j];
290         node->namespace_set[NAMESPACE_SIZE-1-i] = task_data->state->namespace_set[NAMESPACE_SIZE-1-i-j-1];
291       }
292       node->namespace_set[NAMESPACE_SIZE/2+j] = task_data->sender_id;
293       node->ready += task_data->steps + 1;
294       /* no break */
295     case TASK_JOIN_REPLY:
296       XBT_DEBUG("Joining Reply");
297
298       // if first node touched reply, copy its neighborhood set
299       if (task_data->sender_id == node->known_id) {
300         node->neighborhood_set[0] = task_data->sender_id;
301         for (i=1; i<NEIGHBORHOOD_SIZE; i++)
302           node->neighborhood_set[i] = task_data->state->neighborhood_set[i-1];
303       }
304
305       // copy the corresponding routing table levels
306       min = (node->id==task_data->answer_id) ? 0 : shl(node->id, task_data->answer_id);
307       max = shl(node->id, task_data->sender_id)+1;
308       for (i=min;i<max;i++) {
309         d = domain(node->id, i); 
310         for (j=0; j<LEVEL_SIZE; j++)
311           if (d!=j)
312             node->routing_table[i][j] =  task_data->state->routing_table[i][j];
313           }
314
315       node->ready--;
316       // if the node is ready, do all the pending tasks and send update to known nodes
317       if (node->ready==0) {
318         XBT_DEBUG("Node %i is ready!!!", node->id);
319
320         while(xbt_fifo_size(node->pending_tasks))
321           handle_task(node, xbt_fifo_pop(node->pending_tasks));
322
323         for (i=0; i<NAMESPACE_SIZE; i++) {
324           j = node->namespace_set[i];
325           if (j!=-1) {
326             XBT_DEBUG("Send update to %i", j);
327             get_mailbox(j, mailbox);
328
329             req_data = xbt_new0(s_task_data_t,1);
330             req_data->answer_id = node->id;
331             req_data->steps = 0;
332             req_data->type = TASK_UPDATE;
333             req_data->sender_id = node->id;
334             get_mailbox(node->id, req_data->answer_to);
335             req_data->state = node_get_state(node);
336             task_sent = MSG_task_create(NULL, COMP_SIZE, COMM_SIZE, req_data);
337             if (MSG_task_send_with_timeout(task_sent, mailbox, timeout)== MSG_TIMEOUT) {
338               XBT_DEBUG("Timeout expired when sending update to %d", j);
339               task_free(task_sent);
340             }
341           }
342         }
343         }
344       break;
345     /* Received an update of state */
346     case TASK_UPDATE:
347       XBT_DEBUG("Task update %i !!!", node->id);
348
349       /* Update namespace ses */
350       XBT_INFO("Task update from %i !!!", task_data->sender_id);
351       XBT_INFO("Node:");
352       print_node_id(node);
353       print_node_namespace_set(node);
354       int curr_namespace_set[NAMESPACE_SIZE];
355       int task_namespace_set[NAMESPACE_SIZE+1];
356       
357       // Copy the current namespace and the task state namespace with state->id in the middle
358       i=0;
359       for (; i<NAMESPACE_SIZE/2; i++){
360         curr_namespace_set[i] = node->namespace_set[i];
361         task_namespace_set[i] = task_data->state->namespace_set[i];
362       }
363       task_namespace_set[i] = task_data->state->id;
364       for (; i<NAMESPACE_SIZE; i++){
365         curr_namespace_set[i] = node->namespace_set[i];  
366         task_namespace_set[i+1] = task_data->state->namespace_set[i];
367       }
368
369       // get the index of values before and after node->id in task_namespace
370       min = -1;
371       max = -1;
372       for (i=0; i<=NAMESPACE_SIZE; i++) {
373         j = task_namespace_set[i];
374         if (j != -1 && j < node->id)
375           min = i;
376         if (j != -1 && max == -1 && j > node->id)
377           max = i;
378       }
379
380       // add lower elements
381       j = NAMESPACE_SIZE/2-1;
382       for (i=NAMESPACE_SIZE/2-1; i>=0; i--) {
383         if (min<0) {
384           node->namespace_set[i] = curr_namespace_set[j];
385           j--;
386         } else if (curr_namespace_set[j] == task_namespace_set[min]) {
387           node->namespace_set[i] = curr_namespace_set[j];
388           j--;
389           min--;
390         } else if (curr_namespace_set[j] > task_namespace_set[min]) {
391           node->namespace_set[i] = curr_namespace_set[j];
392           j--;
393         } else {
394           node->namespace_set[i] = task_namespace_set[min];
395           min--;
396         }
397       }
398
399       // add greater elements
400       j = NAMESPACE_SIZE/2;
401       for (i=NAMESPACE_SIZE/2; i<NAMESPACE_SIZE; i++) {
402         if (min<0 || max>=NAMESPACE_SIZE) {
403          node->namespace_set[i] = curr_namespace_set[j];
404          j++;
405         } else 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       /* Update routing table */
422       for (i=shl(node->id, task_data->state->id); i<LEVELS_COUNT; i++) {
423         for (j=0; j<LEVEL_SIZE; j++) {
424           if (node->routing_table[i][j]==-1 && task_data->state->routing_table[i][j]==-1)
425             node->routing_table[i][j] = task_data->state->routing_table[i][j];
426         }
427       }
428       break;
429     default:
430       THROW_IMPOSSIBLE;
431   }
432   task_free(task);
433 }
434
435 /** \brief Initializes the current node as the first one of the system.
436  *  \param node the current node
437  */
438 static void create(node_t node){
439   node->ready = 0;
440   XBT_DEBUG("Create a new Pastry ring...");
441 }
442
443 /* Join the ring */
444 static int join(node_t node){
445   task_data_t req_data = xbt_new0(s_task_data_t,1);
446   req_data->type = TASK_JOIN;
447   req_data->sender_id = node->id;
448   req_data->answer_id = node->id;
449   req_data->steps = 0;
450   get_mailbox(node->id, req_data->answer_to);
451
452   char mailbox[MAILBOX_NAME_SIZE];
453   get_mailbox(node->known_id, mailbox);
454
455   msg_task_t task_sent = MSG_task_create(NULL, COMP_SIZE, COMM_SIZE, req_data);
456   XBT_DEBUG("Trying to join Pastry ring... (with node %s)", mailbox);
457   if (MSG_task_send_with_timeout(task_sent, mailbox, timeout)== MSG_TIMEOUT) {
458     XBT_DEBUG("Timeout expired when joining ring with node %d", node->known_id);
459     task_free(task_sent);
460   }
461
462   return 1;
463 }
464
465 /**
466  * \brief Node Function
467  * Arguments:
468  * - my id
469  * - the id of a guy I know in the system (except for the first node)
470  * - the time to sleep before I join (except for the first node)
471  * - the deadline time
472  */
473 static int node(int argc, char *argv[])
474 {
475   double init_time = MSG_get_clock();
476   msg_task_t task_received = NULL;  
477   int join_success = 0;  
478   double deadline;
479   xbt_assert(argc == 3 || argc == 5, "Wrong number of arguments for this node");
480   s_node_t node = {0};
481   node.id = xbt_str_parse_int(argv[1], "Invalid ID: %s");
482   node.known_id = -1;
483   node.ready = -1;
484   node.pending_tasks = xbt_fifo_new();
485   get_mailbox(node.id, node.mailbox);
486   XBT_DEBUG("New node with id %s (%08x)", node.mailbox, node.id);
487   
488   int i;
489   for (i=0; i<LEVELS_COUNT; i++){
490     int d = domain(node.id, i);
491     for (int j=0; j<LEVEL_SIZE; j++)
492       node.routing_table[i][j] = (d==j) ? node.id : -1;
493   }
494
495   for (i=0; i<NEIGHBORHOOD_SIZE; i++)
496     node.neighborhood_set[i] = -1;
497
498   for (i=0; i<NAMESPACE_SIZE; i++)
499     node.namespace_set[i] = -1;
500
501   if (argc == 3) { // first ring
502     XBT_DEBUG("Hey! Let's create the system.");
503     deadline = xbt_str_parse_double(argv[2], "Invalid deadline: %s");
504     create(&node);
505     join_success = 1;
506   }
507   else {
508     node.known_id = xbt_str_parse_int(argv[2], "Invalid known ID: %s");
509     double sleep_time = xbt_str_parse_double(argv[3], "Invalid sleep time: %s");
510     deadline = xbt_str_parse_double(argv[4], "Invalid deadline: %s");
511
512     // sleep before starting
513     XBT_DEBUG("Let's sleep during %f", sleep_time);
514     MSG_process_sleep(sleep_time);
515     XBT_DEBUG("Hey! Let's join the system.");
516
517     join_success = join(&node);
518   }
519
520   if (join_success) {
521     XBT_DEBUG("Waiting ….");
522
523     while (MSG_get_clock() < init_time + deadline
524 //      && MSG_get_clock() < node.last_change_date + 1000
525         && MSG_get_clock() < max_simulation_time) {
526       if (node.comm_receive == NULL) {
527         task_received = NULL;
528         node.comm_receive = MSG_task_irecv(&task_received, node.mailbox);
529         // FIXME: do not make MSG_task_irecv() calls from several functions
530       }
531       if (!MSG_comm_test(node.comm_receive)) {
532         MSG_process_sleep(5);
533       } else {
534         // a transfer has occurred
535
536         msg_error_t status = MSG_comm_get_status(node.comm_receive);
537
538         if (status != MSG_OK) {
539           XBT_DEBUG("Failed to receive a task. Nevermind.");
540           MSG_comm_destroy(node.comm_receive);
541           node.comm_receive = NULL;
542         }
543         else {
544           // the task was successfully received
545           MSG_comm_destroy(node.comm_receive);
546           node.comm_receive = NULL;
547           handle_task(&node, task_received);
548         }
549       }
550
551     }
552   //Cleanup the receiving communication.
553   if (node.comm_receive != NULL) {
554     if (MSG_comm_test(node.comm_receive) && MSG_comm_get_status(node.comm_receive) == MSG_OK) {
555       task_free(MSG_comm_get_task(node.comm_receive));
556     }
557     MSG_comm_destroy(node.comm_receive);
558   }
559
560   }
561   xbt_free(node.pending_tasks);
562   return 1;
563 }
564
565 /** \brief Main function. */
566 int main(int argc, char *argv[])
567 {
568   MSG_init(&argc, argv);
569   xbt_assert(argc > 2, 
570        "Usage: %s [-nb_bits=n] [-timeout=t] platform_file deployment_file\n"
571        "\tExample: %s ../msg_platform.xml pastry10.xml\n", 
572        argv[0], argv[0]);
573
574   char **options = &argv[1];
575   while (!strncmp(options[0], "-", 1)) {
576     int length = strlen("-nb_bits=");
577     if (!strncmp(options[0], "-nb_bits=", length) && strlen(options[0]) > length) {
578       nb_bits = xbt_str_parse_int(options[0] + length, "Invalid nb_bits parameter: %s");
579       XBT_DEBUG("Set nb_bits to %d", nb_bits);
580     } else {
581       length = strlen("-timeout=");
582       if (!strncmp(options[0], "-timeout=", length) && strlen(options[0]) > length) {
583         timeout = xbt_str_parse_int(options[0] + length, "Invalid timeout parameter: %s");
584         XBT_DEBUG("Set timeout to %d", timeout);
585       } else {
586         xbt_die("Invalid pastry option '%s'", options[0]);
587       }
588     }
589     options++;
590   }
591
592   MSG_create_environment(options[0]);
593
594   MSG_function_register("node", node);
595   MSG_launch_application(options[1]);
596
597   msg_error_t res = MSG_main();
598   XBT_INFO("Simulated time: %g", MSG_get_clock());
599
600   return res != MSG_OK;
601 }