1 /* Copyright (c) 2006-2014. The SimGrid Team.
2 * All rights reserved. */
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. */
9 import org.simgrid.msg.Msg;
10 import org.simgrid.msg.Comm;
11 import org.simgrid.msg.Host;
12 import org.simgrid.msg.Task;
13 import org.simgrid.msg.Process;
14 import org.simgrid.msg.MsgException;
15 import org.simgrid.msg.TimeoutException;
16 public class Node extends Process {
18 protected String mailbox;
20 protected String predMailbox;
21 protected int nextFingerToFix;
22 protected Comm commReceive;
23 ///Last time I changed a finger or my predecessor
24 protected double lastChangeDate;
27 public Node(Host host, String name, String[] args) {
28 super(host,name,args);
32 public void main(String[] args) throws MsgException {
33 if (args.length != 2 && args.length != 4) {
34 Msg.info("You need to provide 2 or 4 arguments.");
37 double initTime = Msg.getClock();
39 boolean joinSuccess = false;
42 double nextStabilizeDate = initTime + Common.PERIODIC_STABILIZE_DELAY;
43 double nextFixFingersDate = initTime + Common.PERIODIC_FIX_FINGERS_DELAY;
44 double nextCheckPredecessorDate = initTime + Common.PERIODIC_CHECK_PREDECESSOR_DELAY;
45 double nextLookupDate = initTime + Common.PERIODIC_LOOKUP_DELAY;
47 id = Integer.valueOf(args[0]);
48 mailbox = Integer.toString(id);
50 fingers = new int[Common.NB_BITS];
51 for (i = 0; i < Common.NB_BITS; i++) {
57 if (args.length == 2) {
58 deadline = Integer.valueOf(args[1]);
62 int knownId = Integer.valueOf(args[1]);
63 deadline = Integer.valueOf(args[3]);
64 //Msg.info("Hey! Let's join the system with the id " + id + ".");
66 joinSuccess = join(knownId);
69 double currentClock = Msg.getClock();
70 while (currentClock < (initTime + deadline) && currentClock < Common.MAX_SIMULATION_TIME) {
71 if (commReceive == null) {
72 commReceive = Task.irecv(this.mailbox);
75 if (!commReceive.test()) {
76 if (currentClock >= nextStabilizeDate) {
78 nextStabilizeDate = Msg.getClock() + Common.PERIODIC_STABILIZE_DELAY;
79 } else if (currentClock >= nextFixFingersDate) {
81 nextFixFingersDate = Msg.getClock() + Common.PERIODIC_FIX_FINGERS_DELAY;
82 } else if (currentClock >= nextCheckPredecessorDate) {
83 this.checkPredecessor();
84 nextCheckPredecessorDate = Msg.getClock() + Common.PERIODIC_CHECK_PREDECESSOR_DELAY;
85 } else if (currentClock >= nextLookupDate) {
87 nextLookupDate = Msg.getClock() + Common.PERIODIC_LOOKUP_DELAY;
91 currentClock = Msg.getClock();
93 handleTask(commReceive.getTask());
94 currentClock = Msg.getClock();
99 currentClock = Msg.getClock();
104 if (commReceive != null) {
108 Msg.info("I couldn't join the ring");
112 void handleTask(Task task) {
113 if (task instanceof FindSuccessorTask) {
114 FindSuccessorTask fTask = (FindSuccessorTask)task;
115 Msg.debug("Receiving a 'Find Successor' request from " + fTask.issuerHostName + " for id " + fTask.requestId);
116 // is my successor the successor?
117 if (isInInterval(fTask.requestId, this.id + 1, fingers[0])) {
118 //Msg.info("Send the request to " + fTask.answerTo + " with answer " + fingers[0]);
119 FindSuccessorAnswerTask answer = new FindSuccessorAnswerTask(getHost().getName(), mailbox, fingers[0]);
120 answer.dsend(fTask.answerTo);
122 // otherwise, forward the request to the closest preceding finger in my table
123 int closest = closestPrecedingNode(fTask.requestId);
124 //Msg.info("Forward the request to " + closest);
125 fTask.dsend(Integer.toString(closest));
127 } else if (task instanceof GetPredecessorTask) {
128 GetPredecessorTask gTask = (GetPredecessorTask)(task);
129 Msg.debug("Receiving a 'Get Predecessor' request from " + gTask.issuerHostName);
130 GetPredecessorAnswerTask answer = new GetPredecessorAnswerTask(getHost().getName(), mailbox, predId);
131 answer.dsend(gTask.answerTo);
132 } else if (task instanceof NotifyTask) {
133 NotifyTask nTask = (NotifyTask)task;
134 notify(nTask.requestId);
136 Msg.debug("Ignoring unexpected task of type:" + task);
141 Msg.debug("Well Guys! I Think it's time for me to quit ;)");
142 quitNotify(1); //Notify my successor
143 quitNotify(-1); //Notify my predecessor.
147 * @brief Notifies the successor or the predecessor of the current node of the departure
148 * @param to 1 to notify the successor, -1 to notify the predecessor
150 static void quitNotify( int to) {
155 * @brief Initializes the current node as the first one of the system.
158 Msg.debug("Create a new Chord ring...");
162 // Makes the current node join the ring, knowing the id of a node already in the ring
163 boolean join(int knownId) {
164 Msg.info("Joining the ring with id " + this.id + " knowing node " + knownId);
166 int successorId = remoteFindSuccessor(knownId, this.id);
167 if (successorId == -1) {
168 Msg.info("Cannot join the ring.");
170 setFinger(0, successorId);
172 return successorId != -1;
175 void setPredecessor(int predecessorId) {
176 if (predecessorId != predId) {
177 predId = predecessorId;
178 if (predecessorId != -1) {
179 predMailbox = Integer.toString(predId);
181 lastChangeDate = Msg.getClock();
186 * @brief Asks another node its predecessor.
187 * @param askTo the node to ask to
188 * @return the id of its predecessor node, or -1 if the request failed(or if the node does not know its predecessor)
190 int remoteGetPredecessor(int askTo) {
191 int predecessorId = -1;
192 boolean stop = false;
193 Msg.debug("Sending a 'Get Predecessor' request to " + askTo);
194 String mailboxTo = Integer.toString(askTo);
195 GetPredecessorTask sendTask = new GetPredecessorTask(getHost().getName(), this.mailbox);
197 sendTask.send(mailboxTo, Common.TIMEOUT);
200 if (commReceive == null) {
201 commReceive = Task.irecv(this.mailbox);
203 commReceive.waitCompletion(Common.TIMEOUT);
204 Task taskReceived = commReceive.getTask();
205 if (taskReceived instanceof GetPredecessorAnswerTask) {
206 predecessorId = ((GetPredecessorAnswerTask) taskReceived).answerId;
209 handleTask(taskReceived);
214 catch (MsgException e) {
219 catch (MsgException e) {
220 Msg.debug("Failed to send the Get Predecessor request");
222 return predecessorId;
226 * @brief Makes the current node find the successor node of an id.
227 * @param node the current node
228 * @param id the id to find
229 * @return the id of the successor node, or -1 if the request failed
231 int findSuccessor(int id) {
232 if (isInInterval(id, this.id + 1, fingers[0])) {
236 int closest = this.closestPrecedingNode(id);
237 return remoteFindSuccessor(closest, id);
240 // Asks another node the successor node of an id.
241 int remoteFindSuccessor(int askTo, int id) {
243 boolean stop = false;
244 String mailbox = Integer.toString(askTo);
245 Task sendTask = new FindSuccessorTask(getHost().getName(), this.mailbox, id);
246 Msg.debug("Sending a 'Find Successor' request to " + mailbox + " for id " + id);
248 sendTask.send(mailbox, Common.TIMEOUT);
250 if (commReceive == null) {
251 commReceive = Task.irecv(this.mailbox);
254 commReceive.waitCompletion(Common.TIMEOUT);
255 Task task = commReceive.getTask();
256 if (task instanceof FindSuccessorAnswerTask) {
257 //TODO: Check if this this our answer.
258 FindSuccessorAnswerTask fTask = (FindSuccessorAnswerTask) task;
260 successor = fTask.answerId;
266 catch (TimeoutException e) {
272 catch (TimeoutException e) {
273 Msg.debug("Failed to send the 'Find Successor' request");
275 catch (MsgException e) {
276 Msg.debug("Failed to receive Find Successor");
282 // This function is called periodically. It checks the immediate successor of the current node.
284 Msg.debug("Stabilizing node");
286 int successorId = fingers[0];
287 if (successorId != this.id){
288 candidateId = remoteGetPredecessor(successorId);
290 candidateId = predId;
292 //This node is a candidate to become my new successor
293 if (candidateId != -1 && isInInterval(candidateId, this.id + 1, successorId - 1)) {
294 setFinger(0, candidateId);
296 if (successorId != this.id) {
297 remoteNotify(successorId, this.id);
302 * @brief Notifies the current node that its predecessor may have changed.
303 * @param candidate_id the possible new predecessor
305 void notify(int predecessorCandidateId) {
306 if (predId == -1 || isInInterval(predecessorCandidateId, predId + 1, this.id - 1 )) {
307 setPredecessor(predecessorCandidateId);
312 * @brief Notifies a remote node that its predecessor may have changed.
313 * @param notify_id id of the node to notify
314 * @param candidate_id the possible new predecessor
316 void remoteNotify(int notifyId, int predecessorCandidateId) {
317 Msg.debug("Sending a 'Notify' request to " + notifyId);
318 Task sentTask = new NotifyTask(getHost().getName(), this.mailbox, predecessorCandidateId);
319 sentTask.dsend(Integer.toString(notifyId));
322 // This function is called periodically.
323 // It refreshes the finger table of the current node.
325 Msg.debug("Fixing fingers");
326 int i = this.nextFingerToFix;
327 int id = this.findSuccessor(this.id + (int)Math.pow(2,i)); //FIXME: SLOW
329 if (id != fingers[i]) {
332 nextFingerToFix = (i + 1) % Common.NB_BITS;
336 // This function is called periodically.
337 // It checks whether the predecessor has failed
338 void checkPredecessor() {
342 // Performs a find successor request to a random id.
343 void randomLookup() {
345 //Msg.info("Making a lookup request for id " + id);
350 * @brief Returns the closest preceding finger of an id with respect to the finger table of the current node.
351 * @param id the id to find
352 * @return the closest preceding finger of that id
354 int closestPrecedingNode(int id) {
356 for (i = Common.NB_BITS - 1; i >= 0; i--) {
357 if (isInInterval(fingers[i], this.id + 1, id - 1)) {
365 * @brief Returns whether an id belongs to the interval [start, end].
367 * The parameters are noramlized to make sure they are between 0 and nb_keys - 1).
368 * 1 belongs to [62, 3]
369 * 1 does not belong to [3, 62]
370 * 63 belongs to [62, 3]
371 * 63 does not belong to [3, 62]
372 * 24 belongs to [21, 29]
373 * 24 does not belong to [29, 21]
375 * @param id id to check
376 * @param start lower bound
377 * @param end upper bound
378 * @return a non-zero value if id in in [start, end]
380 static boolean isInInterval(int id, int start, int end) {
382 start = normalize(start);
383 end = normalize(end);
385 // make sure end >= start and id >= start
387 end += Common.NB_KEYS;
390 id += Common.NB_KEYS;
396 * @brief Turns an id into an equivalent id in [0, nb_keys).
398 * @return the corresponding normalized id
400 static int normalize(int id) {
401 return id & (Common.NB_KEYS - 1);
405 * @brief Sets a finger of the current node.
406 * @param finger_index index of the finger to set (0 to nb_bits - 1)
407 * @param id the id to set for this finger
409 void setFinger(int fingerIndex, int id) {
410 if (id != fingers[fingerIndex]) {
411 fingers[fingerIndex] = id;
412 lastChangeDate = Msg.getClock();