Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge branch 'random_readwritestate' into 'master'
[simgrid.git] / examples / s4u / dht-kademlia / node.cpp
1 /* Copyright (c) 2010-2020. The SimGrid Team. All rights reserved.          */
2
3 /* This program is free software; you can redistribute it and/or modify it
4  * under the terms of the license (GNU LGPL) which comes with this package. */
5
6 #include "node.hpp"
7 #include "routing_table.hpp"
8
9 XBT_LOG_NEW_DEFAULT_CATEGORY(kademlia_node, "Messages specific for this example");
10
11 namespace kademlia {
12 static void destroy(void* message)
13 {
14   const Message* msg = static_cast<Message*>(message);
15   delete msg->answer_;
16   delete msg;
17 }
18
19 /**
20   * @brief Tries to join the network
21   * @param known_id id of the node I know in the network.
22   */
23 bool Node::join(unsigned int known_id)
24 {
25   const Answer* node_list;
26   unsigned int i;
27   bool got_answer = false;
28
29   /* Add the guy we know to our routing table and ourselves. */
30   routingTableUpdate(id_);
31   routingTableUpdate(known_id);
32
33   /* First step: Send a "FIND_NODE" request to the node we know */
34   sendFindNode(known_id, id_);
35
36   simgrid::s4u::Mailbox* mailbox = simgrid::s4u::Mailbox::by_name(std::to_string(id_));
37   do {
38     if (receive_comm == nullptr)
39       receive_comm = mailbox->get_async(&received_msg);
40     if (receive_comm->test()) {
41       XBT_DEBUG("Received an answer from the node I know.");
42       got_answer = true;
43       // retrieve the node list and ping them.
44       const Message* msg = static_cast<Message*>(received_msg);
45       node_list    = msg->answer_;
46       if (node_list) {
47         for (auto const& contact : node_list->getNodes())
48           routingTableUpdate(contact.first);
49       } else {
50         handleFindNode(msg);
51       }
52       delete msg->answer_;
53       delete msg;
54       receive_comm = nullptr;
55     } else
56       simgrid::s4u::this_actor::sleep_for(1);
57   } while (not got_answer);
58
59   /* Second step: Send a FIND_NODE to a a random node in buckets */
60   unsigned int bucket_id = table.findBucket(known_id)->getId();
61   xbt_assert(bucket_id <= IDENTIFIER_SIZE);
62   for (i = 0; ((bucket_id > i) || (bucket_id + i) <= IDENTIFIER_SIZE) && i < JOIN_BUCKETS_QUERIES; i++) {
63     if (bucket_id > i) {
64       unsigned int id_in_bucket = get_id_in_prefix(id_, bucket_id - i);
65       findNode(id_in_bucket, false);
66     }
67     if (bucket_id + i <= IDENTIFIER_SIZE) {
68       unsigned int id_in_bucket = get_id_in_prefix(id_, bucket_id + i);
69       findNode(id_in_bucket, false);
70     }
71   }
72   return got_answer;
73 }
74
75 /** @brief Send a "FIND_NODE" to a node
76   * @param id node we are querying
77   * @param destination node we are trying to find.
78   */
79 void Node::sendFindNode(unsigned int id, unsigned int destination)
80 {
81   /* Gets the mailbox to send to */
82   simgrid::s4u::Mailbox* mailbox = simgrid::s4u::Mailbox::by_name(std::to_string(id));
83   /* Build the task */
84
85   Message* msg = new Message(id_, destination, simgrid::s4u::Mailbox::by_name(std::to_string(id_)),
86                              simgrid::s4u::Host::current()->get_cname());
87
88   /* Send the task */
89   mailbox->put_init(msg, 1)->detach(kademlia::destroy);
90   XBT_VERB("Asking %u for its closest nodes", id);
91 }
92
93 /**
94   * Sends to the best "KADEMLIA_ALPHA" nodes in the "node_list" array a "FIND_NODE" request, to ask them for their best
95   * nodes
96   */
97 unsigned int Node::sendFindNodeToBest(const Answer* node_list)
98 {
99   unsigned int i           = 0;
100   unsigned int j           = 0;
101   unsigned int destination = node_list->getDestinationId();
102   for (auto const& node_to_query : node_list->getNodes()) {
103     /* We need to have at most "KADEMLIA_ALPHA" requests each time, according to the protocol */
104     /* Gets the node we want to send the query to */
105     if (node_to_query.first != id_) { /* No need to query ourselves */
106       sendFindNode(node_to_query.first, destination);
107       j++;
108     }
109     i++;
110     if (j == KADEMLIA_ALPHA)
111       break;
112   }
113   return i;
114 }
115
116 /** @brief Updates/Puts the node id unsigned into our routing table
117   * @param id The id of the node we need to add unsigned into our routing table
118   */
119 void Node::routingTableUpdate(unsigned int id)
120 {
121   // retrieval of the bucket in which the should be
122   Bucket* bucket = table.findBucket(id);
123
124   // check if the id is already in the bucket.
125   auto id_pos = std::find(bucket->nodes_.begin(), bucket->nodes_.end(), id);
126
127   if (id_pos == bucket->nodes_.end()) {
128     /* We check if the bucket is full or not. If it is, we evict an old element */
129     if (bucket->nodes_.size() >= BUCKET_SIZE) {
130       bucket->nodes_.pop_back();
131     }
132     bucket->nodes_.push_front(id);
133     XBT_VERB("I'm adding to my routing table %08x", id);
134   } else {
135     // We push the element to the front
136     bucket->nodes_.erase(id_pos);
137     bucket->nodes_.push_front(id);
138     XBT_VERB("I'm updating %08x", id);
139   }
140 }
141
142 /** @brief Finds the closest nodes to the node given.
143   * @param node : our node
144   * @param destination_id : the id of the guy we are trying to find
145   */
146 Answer* Node::findClosest(unsigned int destination_id)
147 {
148   Answer* answer = new Answer(destination_id);
149   /* We find the corresponding bucket for the id */
150   const Bucket* bucket = table.findBucket(destination_id);
151   int bucket_id  = bucket->getId();
152   xbt_assert((bucket_id <= IDENTIFIER_SIZE), "Bucket found has a wrong identifier");
153   /* So, we copy the contents of the bucket unsigned into our answer */
154   answer->addBucket(bucket);
155
156   /* However, if we don't have enough elements in our bucket, we NEED to include at least "BUCKET_SIZE" elements
157    * (if, of course, we know at least "BUCKET_SIZE" elements. So we're going to look unsigned into the other buckets.
158    */
159   for (int i = 1; answer->getSize() < BUCKET_SIZE && ((bucket_id - i > 0) || (bucket_id + i < IDENTIFIER_SIZE)); i++) {
160     /* We check the previous buckets */
161     if (bucket_id - i >= 0) {
162       const Bucket* bucket_p = &table.getBucketAt(bucket_id - i);
163       answer->addBucket(bucket_p);
164     }
165     /* We check the next buckets */
166     if (bucket_id + i <= IDENTIFIER_SIZE) {
167       const Bucket* bucket_n = &table.getBucketAt(bucket_id + i);
168       answer->addBucket(bucket_n);
169     }
170   }
171   /* We trim the array to have only BUCKET_SIZE or less elements */
172   answer->trim();
173
174   return answer;
175 }
176
177 /** @brief Send a request to find a node in the node routing table.
178   * @param id_to_find the id of the node we are trying to find
179   */
180 bool Node::findNode(unsigned int id_to_find, bool count_in_stats)
181 {
182   unsigned int queries;
183   unsigned int answers;
184   bool destination_found   = false;
185   unsigned int nodes_added = 0;
186   double global_timeout    = simgrid::s4u::Engine::get_clock() + FIND_NODE_GLOBAL_TIMEOUT;
187   unsigned int steps       = 0;
188
189   /* First we build a list of who we already know */
190   Answer* node_list = findClosest(id_to_find);
191   xbt_assert((node_list != nullptr), "node_list incorrect");
192   XBT_DEBUG("Doing a FIND_NODE on %08x", id_to_find);
193
194   /* Ask the nodes on our list if they have information about the node we are trying to find */
195   do {
196     answers        = 0;
197     queries        = sendFindNodeToBest(node_list);
198     nodes_added    = 0;
199     double timeout = simgrid::s4u::Engine::get_clock() + FIND_NODE_TIMEOUT;
200     steps++;
201     double time_beginreceive = simgrid::s4u::Engine::get_clock();
202
203     simgrid::s4u::Mailbox* mailbox = simgrid::s4u::Mailbox::by_name(std::to_string(id_));
204     do {
205       if (receive_comm == nullptr)
206         receive_comm = mailbox->get_async(&received_msg);
207
208       if (receive_comm->test()) {
209         const Message* msg = static_cast<Message*>(received_msg);
210         // Check if what we have received is what we are looking for.
211         if (msg->answer_ && msg->answer_->getDestinationId() == id_to_find) {
212           routingTableUpdate(msg->sender_id_);
213           // Handle the answer
214           for (auto const& contact : node_list->getNodes())
215             routingTableUpdate(contact.first);
216           answers++;
217
218           nodes_added = node_list->merge(msg->answer_);
219           XBT_DEBUG("Received an answer from %s (%s) with %zu nodes on it", msg->answer_to_->get_cname(),
220                     msg->issuer_host_name_.c_str(), msg->answer_->getSize());
221         } else {
222           if (msg->answer_) {
223             routingTableUpdate(msg->sender_id_);
224             XBT_DEBUG("Received a wrong answer for a FIND_NODE");
225           } else {
226             handleFindNode(msg);
227           }
228           // Update the timeout if we didn't have our answer
229           timeout += simgrid::s4u::Engine::get_clock() - time_beginreceive;
230           time_beginreceive = simgrid::s4u::Engine::get_clock();
231         }
232         delete msg->answer_;
233         delete msg;
234         receive_comm = nullptr;
235       } else {
236         simgrid::s4u::this_actor::sleep_for(1);
237       }
238     } while (simgrid::s4u::Engine::get_clock() < timeout && answers < queries);
239     destination_found = node_list->destinationFound();
240   } while (not destination_found && (nodes_added > 0 || answers == 0) &&
241            simgrid::s4u::Engine::get_clock() < global_timeout && steps < MAX_STEPS);
242
243   if (destination_found) {
244     if (count_in_stats)
245       find_node_success++;
246     if (queries > 4)
247       XBT_VERB("FIND_NODE on %08x success in %u steps", id_to_find, steps);
248     routingTableUpdate(id_to_find);
249   } else {
250     if (count_in_stats) {
251       find_node_failed++;
252       XBT_VERB("%08x not found in %u steps", id_to_find, steps);
253     }
254   }
255   delete node_list;
256   return destination_found;
257 }
258
259 /** @brief Does a pseudo-random lookup for someone in the system
260   * @param node caller node data
261   */
262 void Node::randomLookup()
263 {
264   unsigned int id_to_look = RANDOM_LOOKUP_NODE; // Totally random.
265   /* TODO: Use some pseudo-random generator. */
266   XBT_DEBUG("I'm doing a random lookup");
267   findNode(id_to_look, true);
268 }
269
270 /** @brief Handles the answer to an incoming "find_node" task */
271 void Node::handleFindNode(const Message* msg)
272 {
273   routingTableUpdate(msg->sender_id_);
274   XBT_VERB("Received a FIND_NODE from %s (%s), he's trying to find %08x", msg->answer_to_->get_cname(),
275            msg->issuer_host_name_.c_str(), msg->destination_id_);
276   // Building the answer to the request
277   Message* answer =
278       new Message(id_, msg->destination_id_, findClosest(msg->destination_id_),
279                   simgrid::s4u::Mailbox::by_name(std::to_string(id_)), simgrid::s4u::Host::current()->get_cname());
280   // Sending the answer
281   msg->answer_to_->put_init(answer, 1)->detach(kademlia::destroy);
282 }
283
284 void Node::displaySuccessRate()
285 {
286   XBT_INFO("%u/%u FIND_NODE have succeeded", find_node_success, find_node_success + find_node_failed);
287 }
288 } // namespace kademlia
289 /**@brief Returns an identifier which is in a specific bucket of a routing table
290  * @param id id of the routing table owner
291  * @param prefix id of the bucket where we want that identifier to be
292  */
293 unsigned int get_id_in_prefix(unsigned int id, unsigned int prefix)
294 {
295   if (prefix == 0) {
296     return 0;
297   } else {
298     return (1U << ((unsigned int)(prefix - 1))) ^ id;
299   }
300 }
301
302 /** @brief Returns the prefix of an identifier.
303   * The prefix is the id of the bucket in which the remote identifier xor our identifier should be stored.
304   * @param id : big unsigned int id to test
305   * @param nb_bits : key size
306   */
307 unsigned int get_node_prefix(unsigned int id, unsigned int nb_bits)
308 {
309   unsigned int size = sizeof(unsigned int) * 8;
310   for (unsigned int j = 0; j < size; j++) {
311     if (((id >> (size - 1 - j)) & 0x1) != 0) {
312       return nb_bits - (j);
313     }
314   }
315   return 0;
316 }