Logo AND Algorithmique Numérique Distribuée

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