Logo AND Algorithmique Numérique Distribuée

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