Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
ad73ec14778aa5448ca2bcea071bb2631d220615
[simgrid.git] / examples / msg / dht-kademlia / dht-kademlia.c
1 /* Copyright (c) 2012, 2014-2016. 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 "dht-kademlia.h"
8 #include "node.h"
9 #include "task.h"
10
11 #include "simgrid/msg.h"
12 /** @addtogroup MSG_examples
13   * <b>kademlia/kademlia.c: Kademlia protocol</b>
14   * Implements the Kademlia protocol, using 32 bits identifiers.
15   */
16 XBT_LOG_NEW_DEFAULT_CATEGORY(msg_kademlia, "Messages specific for this msg example");
17
18 /* Main loop for the process */
19 static void main_loop(node_t node, double deadline)
20 {
21   double next_lookup_time = MSG_get_clock() + random_lookup_interval;
22   XBT_VERB("Main loop start");
23   while (MSG_get_clock() < deadline) {
24
25     if (node->receive_comm == NULL) {
26       node->task_received = NULL;
27       node->receive_comm = MSG_task_irecv(&node->task_received, node->mailbox);
28     }
29     if (node->receive_comm) {
30       if (!MSG_comm_test(node->receive_comm)) {
31         /* We search for a pseudo random node */
32         if (MSG_get_clock() >= next_lookup_time) {
33           random_lookup(node);
34           next_lookup_time += random_lookup_interval;
35         } else {
36           //Didn't get a task: sleep for a while...
37           MSG_process_sleep(1);
38         }
39       } else {
40         //There has been a transfer, we need to handle it !
41         msg_error_t status = MSG_comm_get_status(node->receive_comm);
42         MSG_comm_destroy(node->receive_comm);
43         node->receive_comm = NULL;
44
45         if (status == MSG_OK) {
46           xbt_assert((node->task_received != NULL), "We received an incorrect task");
47           handle_task(node, node->task_received);
48         } else {
49           xbt_assert((MSG_comm_get_task(node->receive_comm) == NULL), "Comm failed but received a task.");
50           XBT_DEBUG("Nevermind, the communication has failed.");
51         }
52       }
53     } else {
54       //Didn't get a comm: sleep.
55       MSG_process_sleep(1);
56     }
57   }
58   //Cleanup the receiving communication.
59   if (node->receive_comm != NULL) {
60     if (MSG_comm_test(node->receive_comm) && MSG_comm_get_status(node->receive_comm) == MSG_OK) {
61       task_free(MSG_comm_get_task(node->receive_comm));
62     }
63     MSG_comm_destroy(node->receive_comm);
64   }
65 }
66
67 /** @brief Node function
68   * @param my node ID
69   * @param the ID of the person I know in the system (or not)
70   * @param Time before I leave the system because I'm bored
71   */
72 static int node(int argc, char *argv[])
73 {
74   unsigned int join_sucess = 1;
75   double deadline;
76   xbt_assert(argc == 3 || argc == 4, "Wrong number of arguments");
77   /* Node initialization */
78   unsigned int id = strtoul(argv[1], NULL, 0);
79   node_t node = node_init(id);
80
81   if (argc == 4) {
82     XBT_INFO("Hi, I'm going to join the network with id %s", node->mailbox);
83     unsigned int id_known = strtoul(argv[2], NULL, 0);
84     join_sucess = join(node, id_known);
85     deadline = strtod(argv[3], NULL);
86   } else {
87     deadline = strtod(argv[2], NULL);
88     XBT_INFO("Hi, I'm going to create the network with id %s", node->mailbox);
89     node_routing_table_update(node, node->id);
90   }
91   if (join_sucess) {
92     XBT_VERB("Ok, I'm joining the network with id %s", node->mailbox);
93     //We start the main loop
94     main_loop(node, deadline);
95   } else {
96     XBT_INFO("I couldn't join the network :(");
97   }
98   XBT_DEBUG("I'm leaving the network");
99   XBT_INFO("%d/%d FIND_NODE have succeeded", node->find_node_success, node->find_node_success + node->find_node_failed);
100   node_free(node);
101
102   return 0;
103 }
104
105 /**
106   * @brief Tries to join the network
107   * @param node node data
108   * @param id_known id of the node I know in the network.
109   */
110 unsigned int join(node_t node, unsigned int id_known)
111 {
112   answer_t node_list;
113   msg_error_t status;
114   unsigned int trial = 0;
115   unsigned int i;
116   unsigned int answer_got = 0;
117
118   /* Add the guy we know to our routing table and ourselves. */
119   node_routing_table_update(node, node->id);
120   node_routing_table_update(node, id_known);
121
122   /* First step: Send a "FIND_NODE" request to the node we know */
123   send_find_node(node, id_known, node->id);
124   do {
125     if (node->receive_comm == NULL) {
126       node->task_received = NULL;
127       node->receive_comm = MSG_task_irecv(&node->task_received, node->mailbox);
128     }
129     if (node->receive_comm) {
130       if (MSG_comm_test(node->receive_comm)) {
131         status = MSG_comm_get_status(node->receive_comm);
132         MSG_comm_destroy(node->receive_comm);
133         node->receive_comm = NULL;
134         if (status == MSG_OK) {
135           XBT_DEBUG("Received an answer from the node I know.");
136           answer_got = 1;
137           //retrieve the node list and ping them.
138           task_data_t data = MSG_task_get_data(node->task_received);
139           xbt_assert((data != NULL), "Null data received");
140           if (data->type == TASK_FIND_NODE_ANSWER) {
141             node_contact_t contact;
142             node_list = data->answer;
143             xbt_dynar_foreach(node_list->nodes, i, contact) {
144               node_routing_table_update(node, contact->id);
145             }
146             task_free(node->task_received);
147           } else {
148             handle_task(node, node->task_received);
149           }
150         } else {
151           trial++;
152         }
153       } else {
154         MSG_process_sleep(1);
155       }
156     } else {
157       MSG_process_sleep(1);
158     }
159   } while (answer_got == 0 && trial < max_join_trials);
160   /* Second step: Send a FIND_NODE to a a random node in buckets */
161   unsigned int bucket_id = routing_table_find_bucket(node->table, id_known)->id;
162   for (i = 0; ((bucket_id - i) > 0 || (bucket_id + i) <= identifier_size) && i < JOIN_BUCKETS_QUERIES; i++) {
163     if (bucket_id - i > 0) {
164       unsigned int id_in_bucket = get_id_in_prefix(node->id, bucket_id - i);
165       find_node(node, id_in_bucket, 0);
166     }
167     if (bucket_id + i <= identifier_size) {
168       unsigned int id_in_bucket = get_id_in_prefix(node->id, bucket_id + i);
169       find_node(node, id_in_bucket, 0);
170     }
171   }
172   return answer_got;
173 }
174
175 /** @brief Send a request to find a node in the node routing table.
176   * @param node our node data
177   * @param id_to_find the id of the node we are trying to find
178   */
179 unsigned int find_node(node_t node, unsigned int id_to_find, unsigned int count_in_stats)
180 {
181   unsigned int i = 0;
182   unsigned int queries;
183   unsigned int answers;
184   unsigned int destination_found = 0;
185   unsigned int nodes_added = 0;
186   double time_beginreceive;
187   double timeout;
188   double global_timeout = MSG_get_clock() + find_node_global_timeout;
189   unsigned int steps = 0;
190
191   xbt_assert((id_to_find >= 0), "Id supplied incorrect");
192
193   /* First we build a list of who we already know */
194   answer_t node_list = node_find_closest(node, id_to_find);
195   xbt_assert((node_list != NULL), "node_list incorrect");
196
197   XBT_DEBUG("Doing a FIND_NODE on %08x", id_to_find);
198
199   msg_error_t status;
200
201   /* Ask the nodes on our list if they   have information about the node we are trying to find */
202   do {
203     answers = 0;
204     queries = send_find_node_to_best(node, node_list);
205     nodes_added = 0;
206     timeout = MSG_get_clock() + find_node_timeout;
207     steps++;
208     time_beginreceive = MSG_get_clock();
209     do {
210       if (node->receive_comm == NULL) {
211         node->task_received = NULL;
212         node->receive_comm = MSG_task_irecv(&node->task_received, node->mailbox);
213       }
214       if (node->receive_comm) {
215         if (MSG_comm_test(node->receive_comm)) {
216           status = MSG_comm_get_status(node->receive_comm);
217           MSG_comm_destroy(node->receive_comm);
218           node->receive_comm = NULL;
219           if (status == MSG_OK) {
220             xbt_assert((node->task_received != NULL), "Invalid task received");
221             //Figure out if we received an answer or something else
222             task_data_t data = MSG_task_get_data(node->task_received);
223             xbt_assert((data != NULL), "No data in the task");
224
225             //Check if what we have received is what we are looking for.
226             if (data->type == TASK_FIND_NODE_ANSWER && data->answer->destination_id == id_to_find) {
227               //Handle the answer
228               node_routing_table_update(node, data->sender_id);
229               node_contact_t contact;
230               xbt_dynar_foreach(node_list->nodes, i, contact) {
231                 node_routing_table_update(node, contact->id);
232               }
233               answers++;
234
235               nodes_added = answer_merge(node_list, data->answer);
236               XBT_DEBUG("Received an answer from %s (%s) with %ld nodes on it",
237                         data->answer_to, data->issuer_host_name, xbt_dynar_length(data->answer->nodes));
238
239               task_free(node->task_received);
240             } else {
241               handle_task(node, node->task_received);
242               //Update the timeout if we didn't have our answer
243               timeout += MSG_get_clock() - time_beginreceive;
244               time_beginreceive = MSG_get_clock();
245             }
246           }
247         } else {
248           MSG_process_sleep(1);
249         }
250       } else {
251         MSG_process_sleep(1);
252       }
253     } while (MSG_get_clock() < timeout && answers < queries);
254     destination_found = answer_destination_found(node_list);
255   } while (!destination_found && (nodes_added > 0 || answers == 0) && MSG_get_clock() < global_timeout
256             && steps < MAX_STEPS);
257   if (destination_found) {
258     if (count_in_stats)
259       node->find_node_success++;
260     if (queries > 4)
261       XBT_VERB("FIND_NODE on %08x success in %d steps", id_to_find, steps);
262     node_routing_table_update(node, id_to_find);
263   } else {
264     if (count_in_stats) {
265       node->find_node_failed++;
266       XBT_VERB("%08x not found in %d steps", id_to_find, steps);
267     }
268   }
269   answer_free(node_list);
270   return destination_found;
271 }
272
273 /** @brief Pings a node in the system to see if it is online.
274   * @param node Our node data
275   * @param id_to_ping the id of a node we want to see if it is online.
276   * @return if the ping succeded or not.
277   */
278 unsigned int ping(node_t node, unsigned int id_to_ping)
279 {
280   char mailbox[MAILBOX_NAME_SIZE];
281   snprintf(mailbox,MAILBOX_NAME_SIZE, "%d", id_to_ping);
282
283   unsigned int destination_found = 0;
284   double timeout = MSG_get_clock() + ping_timeout;
285
286   msg_task_t ping_task = task_new_ping(node->id, node->mailbox, MSG_host_get_name(MSG_host_self()));
287   msg_task_t task_received = NULL;
288
289   XBT_VERB("PING %08x", id_to_ping);
290
291   //Check that we aren't trying to ping ourselves
292   if (id_to_ping == node->id) {
293     return 1;
294   }
295
296   /* Sending the ping task */
297   MSG_task_dsend(ping_task, mailbox, task_free_v);
298   do {
299     task_received = NULL;
300     msg_error_t status =
301         MSG_task_receive_with_timeout(&task_received, node->mailbox, ping_timeout);
302     if (status == MSG_OK) {
303       xbt_assert((task_received != NULL), "Invalid task received");
304       //Checking if it's what we are waiting for or not.
305       task_data_t data = MSG_task_get_data(task_received);
306       xbt_assert((data != NULL), "didn't receive any data...");
307       if (data->type == TASK_PING_ANSWER && id_to_ping == data->sender_id) {
308         XBT_VERB("Ping to %s succeeded", mailbox);
309         node_routing_table_update(node, data->sender_id);
310         destination_found = 1;
311         task_free(task_received);
312       } else {
313         //If it's not our answer, we answer the query anyway.
314         handle_task(node, task_received);
315       }
316     }
317   } while (destination_found == 0 && MSG_get_clock() < timeout);
318
319   if (MSG_get_clock() >= timeout) {
320     XBT_DEBUG("Ping to %s has timeout.", mailbox);
321     return 0;
322   }
323   if (destination_found == -1) {
324     XBT_DEBUG("It seems that %s is offline...", mailbox);
325     return 0;
326   }
327   return 1;
328 }
329
330 /** @brief Does a pseudo-random lookup for someone in the system
331   * @param node caller node data
332   */
333 void random_lookup(node_t node)
334 {
335   unsigned int id_to_look = RANDOM_LOOKUP_NODE; //Totally random.
336   /* TODO: Use some pseudorandom generator like RngStream. */
337   XBT_DEBUG("I'm doing a random lookup");
338   find_node(node, id_to_look, 1);
339 }
340
341 /** @brief Send a "FIND_NODE" to a node
342   * @param node sender node data
343   * @param id node we are querying
344   * @param destination node we are trying to find.
345   */
346 void send_find_node(node_t node, unsigned int id, unsigned int destination)
347 {
348   char mailbox[MAILBOX_NAME_SIZE];
349   /* Gets the mailbox to send to */
350   get_node_mailbox(id, mailbox);
351   /* Build the task */
352   msg_task_t task = task_new_find_node(node->id, destination, node->mailbox, MSG_host_get_name(MSG_host_self()));
353   /* Send the task */
354   xbt_assert((task != NULL), "Trying to send a NULL task.");
355   MSG_task_dsend(task, mailbox, task_free_v);
356   XBT_VERB("Asking %s for its closest nodes", mailbox);
357 }
358
359 /**
360   * Sends to the best "kademlia_alpha" nodes in the "node_list" array a "FIND_NODE" request, to ask them for their best nodes
361   */
362 unsigned int send_find_node_to_best(node_t node, answer_t node_list)
363 {
364   unsigned int i = 0;
365   unsigned int j = 0;
366   unsigned int destination = node_list->destination_id;
367   node_contact_t node_to_query;
368   while (j < kademlia_alpha && i < node_list->size) {
369     /* We need to have at most "kademlia_alpha" requests each time, according to the protocol */
370     /* Gets the node we want to send the query to */
371     node_to_query = xbt_dynar_get_as(node_list->nodes, i, node_contact_t);
372     if (node_to_query->id != node->id) {        /* No need to query ourselves */
373       send_find_node(node, node_to_query->id, destination);
374       j++;
375     }
376     i++;
377   }
378   return i;
379 }
380
381 /** @brief Handles an incoming received task */
382 void handle_task(node_t node, msg_task_t task)
383 {
384   task_data_t data = MSG_task_get_data(task);
385   xbt_assert((data != NULL), "Received NULL data");
386   //Adding/updating the guy to our routing table
387   node_routing_table_update(node, data->sender_id);
388   switch (data->type) {
389   case TASK_FIND_NODE:
390     handle_find_node(node, data);
391     break;
392   case TASK_FIND_NODE_ANSWER:
393     XBT_DEBUG("Received a wrong answer for a FIND_NODE");
394     break;
395   case TASK_PING:
396     handle_ping(node, data);
397     break;
398   default:
399     break;
400   }
401   task_free(task);
402 }
403
404 /** @brief Handles the answer to an incoming "find_node" task */
405 void handle_find_node(node_t node, task_data_t data)
406 {
407   XBT_VERB("Received a FIND_NODE from %s (%s), he's trying to find %08x",
408            data->answer_to, data->issuer_host_name, data->destination_id);
409   //Building the answer to the request
410   answer_t answer = node_find_closest(node, data->destination_id);
411   //Building the task to send
412   msg_task_t task = task_new_find_node_answer(node->id, data->destination_id, answer, node->mailbox,
413                                               MSG_host_get_name(MSG_host_self()));
414   //Sending the task
415   MSG_task_dsend(task, data->answer_to, task_free_v);
416 }
417
418 /** @brief handles the answer to a ping */
419 void handle_ping(node_t node, task_data_t data)
420 {
421   XBT_VERB("Received a PING request from %s (%s)", data->answer_to, data->issuer_host_name);
422   //Building the answer to the request
423   msg_task_t task = task_new_ping_answer(node->id, data->answer_to, MSG_host_get_name(MSG_host_self()));
424
425   MSG_task_dsend(task, data->answer_to, task_free_v);
426 }
427
428 /** @brief Main function */
429 int main(int argc, char *argv[])
430 {
431   MSG_init(&argc, argv);
432
433   /* Check the arguments */
434   xbt_assert(argc > 2, "Usage: %s platform_file deployment_file\n\tExample: %s msg_platform.xml msg_deployment.xml\n",
435              argv[0], argv[0]);
436
437   const char *platform_file = argv[1];
438   const char *deployment_file = argv[2];
439
440   MSG_create_environment(platform_file);
441   MSG_function_register("node", node);
442   MSG_launch_application(deployment_file);
443
444   msg_error_t res = MSG_main();
445
446   XBT_INFO("Simulated time: %g", MSG_get_clock());
447
448   return res != MSG_OK;
449 }