3 import org.simgrid.msg.Comm;
4 import org.simgrid.msg.Host;
5 import org.simgrid.msg.Msg;
6 import org.simgrid.msg.MsgException;
7 import org.simgrid.msg.Process;
8 import org.simgrid.msg.Task;
9 import org.simgrid.msg.TimeoutException;
13 public class Node extends Process {
21 protected String mailbox;
29 protected String predMailbox;
31 * Index of the next finger to fix
33 protected int nextFingerToFix;
35 * Current communication
37 protected Comm commReceive;
39 * Last time I changed a finger or my predecessor
41 protected double lastChangeDate;
49 public Node(Host host, String name, String[] args) {
50 super(host,name,args);
53 public void main(String[] args) throws MsgException {
54 if (args.length != 2 && args.length != 4) {
55 Msg.info("You need to provide 2 or 4 arguments.");
58 double initTime = Msg.getClock();
60 boolean joinSuccess = false;
63 double nextStabilizeDate = initTime + Common.PERIODIC_STABILIZE_DELAY;
64 double nextFixFingersDate = initTime + Common.PERIODIC_FIX_FINGERS_DELAY;
65 double nextCheckPredecessorDate = initTime + Common.PERIODIC_CHECK_PREDECESSOR_DELAY;
66 double nextLookupDate = initTime + Common.PERIODIC_LOOKUP_DELAY;
68 id = Integer.valueOf(args[0]);
69 mailbox = Integer.toString(id);
71 fingers = new int[Common.NB_BITS];
72 for (i = 0; i < Common.NB_BITS; i++) {
78 if (args.length == 2) {
79 deadline = Integer.valueOf(args[1]);
84 int knownId = Integer.valueOf(args[1]);
85 deadline = Integer.valueOf(args[3]);
86 //Msg.info("Hey! Let's join the system with the id " + id + ".");
88 joinSuccess = join(knownId);
91 double currentClock = Msg.getClock();
92 while (currentClock < (initTime + deadline) && currentClock < Common.MAX_SIMULATION_TIME) {
93 if (commReceive == null) {
94 commReceive = Task.irecv(this.mailbox);
97 if (!commReceive.test()) {
98 if (currentClock >= nextStabilizeDate) {
100 nextStabilizeDate = Msg.getClock() + Common.PERIODIC_STABILIZE_DELAY;
102 else if (currentClock >= nextFixFingersDate) {
104 nextFixFingersDate = Msg.getClock() + Common.PERIODIC_FIX_FINGERS_DELAY;
106 else if (currentClock >= nextCheckPredecessorDate) {
107 this.checkPredecessor();
108 nextCheckPredecessorDate = Msg.getClock() + Common.PERIODIC_CHECK_PREDECESSOR_DELAY;
110 else if (currentClock >= nextLookupDate) {
112 nextLookupDate = Msg.getClock() + Common.PERIODIC_LOOKUP_DELAY;
117 currentClock = Msg.getClock();
120 handleTask(commReceive.getTask());
121 currentClock = Msg.getClock();
126 catch (Exception e) {
132 if (commReceive != null) {
137 Msg.info("I couldn't join the ring");
140 void handleTask(Task task) {
141 if (task instanceof FindSuccessorTask) {
142 FindSuccessorTask fTask = (FindSuccessorTask)task;
143 Msg.debug("Receiving a 'Find Successor' request from " + fTask.issuerHostName + " for id " + fTask.requestId);
144 // is my successor the successor?
145 if (isInInterval(fTask.requestId, this.id + 1, fingers[0])) {
146 //Msg.info("Send the request to " + fTask.answerTo + " with answer " + fingers[0]);
147 FindSuccessorAnswerTask answer = new FindSuccessorAnswerTask(host.getName(), mailbox, fingers[0]);
148 answer.dsend(fTask.answerTo);
151 // otherwise, forward the request to the closest preceding finger in my table
152 int closest = closestPrecedingNode(fTask.requestId);
153 //Msg.info("Forward the request to " + closest);
154 fTask.dsend(Integer.toString(closest));
157 else if (task instanceof GetPredecessorTask) {
158 GetPredecessorTask gTask = (GetPredecessorTask)(task);
159 Msg.debug("Receiving a 'Get Predecessor' request from " + gTask.issuerHostName);
160 GetPredecessorAnswerTask answer = new GetPredecessorAnswerTask(host.getName(), mailbox, predId);
161 answer.dsend(gTask.answerTo);
163 else if (task instanceof NotifyTask) {
164 NotifyTask nTask = (NotifyTask)task;
165 notify(nTask.requestId);
168 Msg.debug("Ignoring unexpected task of type:" + task);
172 * @brief Makes the current node quit the system
175 Msg.debug("Well Guys! I Think it's time for me to quit ;)");
176 quitNotify(1); //Notify my successor
177 quitNotify(-1); //Notify my predecessor.
181 * @brief Notifies the successor or the predecessor of the current node
183 * @param to 1 to notify the successor, -1 to notify the predecessor
185 static void quitNotify( int to) {
189 * @brief Initializes the current node as the first one of the system.
192 Msg.debug("Create a new Chord ring...");
197 * Makes the current node join the ring, knowing the id of a node
198 * already in the ring
200 boolean join(int knownId) {
201 Msg.info("Joining the ring with id " + this.id + " knowing node " + knownId);
203 int successorId = remoteFindSuccessor(knownId, this.id);
204 if (successorId == -1) {
205 Msg.info("Cannot join the ring.");
208 setFinger(0, successorId);
210 return successorId != -1;
214 * Sets the node predecessor
216 void setPredecessor(int predecessorId) {
217 if (predecessorId != predId) {
218 predId = predecessorId;
219 if (predecessorId != -1) {
220 predMailbox = Integer.toString(predId);
222 lastChangeDate = Msg.getClock();
226 * @brief Asks another node its predecessor.
227 * @param askTo the node to ask to
228 * @return the id of its predecessor node, or -1 if the request failed
229 * (or if the node does not know its predecessor)
231 int remoteGetPredecessor(int askTo) {
232 int predecessorId = -1;
233 boolean stop = false;
234 Msg.debug("Sending a 'Get Predecessor' request to " + askTo);
235 String mailboxTo = Integer.toString(askTo);
236 GetPredecessorTask sendTask = new GetPredecessorTask(host.getName(), this.mailbox);
238 sendTask.send(mailboxTo, Common.TIMEOUT);
241 if (commReceive == null) {
242 commReceive = Task.irecv(this.mailbox);
244 commReceive.waitCompletion(Common.TIMEOUT);
245 Task taskReceived = commReceive.getTask();
246 if (taskReceived instanceof GetPredecessorAnswerTask) {
247 predecessorId = ((GetPredecessorAnswerTask) taskReceived).answerId;
251 handleTask(taskReceived);
257 catch (MsgException e) {
262 catch (MsgException e) {
263 Msg.debug("Failed to send the Get Predecessor request");
267 return predecessorId;
270 * @brief Makes the current node find the successor node of an id.
271 * @param node the current node
272 * @param id the id to find
273 * @return the id of the successor node, or -1 if the request failed
275 int findSuccessor(int id) {
276 if (isInInterval(id, this.id + 1, fingers[0])) {
280 int closest = this.closestPrecedingNode(id);
281 return remoteFindSuccessor(closest, id);
284 * @brief Asks another node the successor node of an id.
286 int remoteFindSuccessor(int askTo, int id) {
288 boolean stop = false;
289 String mailbox = Integer.toString(askTo);
290 Task sendTask = new FindSuccessorTask(host.getName(), this.mailbox, id);
291 Msg.debug("Sending a 'Find Successor' request to " + mailbox + " for id " + id);
293 sendTask.send(mailbox, Common.TIMEOUT);
295 if (commReceive == null) {
296 commReceive = Task.irecv(this.mailbox);
299 commReceive.waitCompletion(Common.TIMEOUT);
300 Task task = commReceive.getTask();
301 if (task instanceof FindSuccessorAnswerTask) {
302 //TODO: Check if this this our answer.
303 FindSuccessorAnswerTask fTask = (FindSuccessorAnswerTask) task;
305 successor = fTask.answerId;
312 catch (TimeoutException e) {
318 catch (TimeoutException e) {
319 Msg.debug("Failed to send the 'Find Successor' request");
321 catch (MsgException e) {
322 Msg.debug("Failed to receive Find Successor");
329 * @brief This function is called periodically. It checks the immediate
330 * successor of the current node.
333 Msg.debug("Stabilizing node");
335 int successorId = fingers[0];
336 if (successorId != this.id){
337 candidateId = remoteGetPredecessor(successorId);
340 candidateId = predId;
342 //This node is a candidate to become my new successor
343 if (candidateId != -1 && isInInterval(candidateId, this.id + 1, successorId - 1)) {
344 setFinger(0, candidateId);
346 if (successorId != this.id) {
347 remoteNotify(successorId, this.id);
352 * \brief Notifies the current node that its predecessor may have changed.
353 * \param candidate_id the possible new predecessor
355 void notify(int predecessorCandidateId) {
356 if (predId == -1 || isInInterval(predecessorCandidateId, predId + 1, this.id - 1 )) {
357 setPredecessor(predecessorCandidateId);
360 //Don't have to change the predecessor.
364 * \brief Notifies a remote node that its predecessor may have changed.
365 * \param notify_id id of the node to notify
366 * \param candidate_id the possible new predecessor
368 void remoteNotify(int notifyId, int predecessorCandidateId) {
369 Msg.debug("Sending a 'Notify' request to " + notifyId);
370 Task sentTask = new NotifyTask(host.getName(), this.mailbox, predecessorCandidateId);
371 sentTask.dsend(Integer.toString(notifyId));
374 * \brief This function is called periodically.
375 * It refreshes the finger table of the current node.
378 Msg.debug("Fixing fingers");
379 int i = this.nextFingerToFix;
380 int id = this.findSuccessor(this.id + (int)Math.pow(2,i)); //FIXME: SLOW
382 if (id != fingers[i]) {
385 nextFingerToFix = (i + 1) % Common.NB_BITS;
389 * \brief This function is called periodically.
390 * It checks whether the predecessor has failed
392 void checkPredecessor() {
396 * \brief Performs a find successor request to a random id.
398 void randomLookup() {
400 //Msg.info("Making a lookup request for id " + id);
407 * @brief Returns the closest preceding finger of an id
408 * with respect to the finger table of the current node.
409 * @param id the id to find
410 * \return the closest preceding finger of that id
412 int closestPrecedingNode(int id) {
414 for (i = Common.NB_BITS - 1; i >= 0; i--) {
415 if (isInInterval(fingers[i], this.id + 1, id - 1)) {
422 * @brief Returns whether an id belongs to the interval [start, end].
424 * The parameters are noramlized to make sure they are between 0 and nb_keys - 1).
425 * 1 belongs to [62, 3]
426 * 1 does not belong to [3, 62]
427 * 63 belongs to [62, 3]
428 * 63 does not belong to [3, 62]
429 * 24 belongs to [21, 29]
430 * 24 does not belong to [29, 21]
432 * \param id id to check
433 * \param start lower bound
434 * \param end upper bound
435 * \return a non-zero value if id in in [start, end]
437 static boolean isInInterval(int id, int start, int end) {
439 start = normalize(start);
440 end = normalize(end);
442 // make sure end >= start and id >= start
444 end += Common.NB_KEYS;
447 id += Common.NB_KEYS;
453 * @brief Turns an id into an equivalent id in [0, nb_keys).
455 * @return the corresponding normalized id
457 static int normalize(int id) {
458 return id & (Common.NB_KEYS - 1);
461 * \brief Sets a finger of the current node.
462 * \param finger_index index of the finger to set (0 to nb_bits - 1)
463 * \param id the id to set for this finger
465 void setFinger(int fingerIndex, int id) {
466 if (id != fingers[fingerIndex]) {
467 fingers[fingerIndex] = id;
468 lastChangeDate = Msg.getClock();