Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
6491bd65686b9dad13816aebcd26958819457d8e
[simgrid.git] / examples / java / app / bittorrent / Peer.java
1 /* Copyright (c) 2006-2019. 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 package app.bittorrent;
8
9 import java.util.ArrayList;
10 import java.util.HashMap;
11 import java.util.Iterator;
12 import java.util.Map.Entry;
13
14 import org.simgrid.msg.Msg;
15 import org.simgrid.msg.Comm;
16 import org.simgrid.msg.Host;
17 import org.simgrid.msg.Task;
18 import org.simgrid.msg.Process;
19 import org.simgrid.msg.RngStream;
20 import org.simgrid.msg.MsgException;
21
22 public class Peer extends Process {
23   protected int round = 0;
24   protected double beginReceiveTime;
25   protected double deadline;
26   protected static RngStream stream = new RngStream();
27   protected int id;
28   protected String mailbox;
29   protected String mailboxTracker;
30   protected String hostname;
31   protected int pieces = 0;
32   protected char[] bitfield = new char[Common.FILE_PIECES];
33   protected char[][] bitfieldBlocks = new char[Common.FILE_PIECES][Common.PIECES_BLOCKS];
34   protected short[] piecesCount = new short[Common.FILE_PIECES];
35   protected int piecesRequested = 0;
36   protected ArrayList<Integer> currentPieces = new ArrayList<>();
37   protected int currentPiece = -1;
38   protected HashMap<Integer, Connection> activePeers = new HashMap<>();
39   protected HashMap<Integer, Connection> peers = new HashMap<>();
40   protected Comm commReceived = null;
41
42   public Peer(Host host, String name, String[]args) {
43     super(host,name,args);
44   }
45
46   @Override
47   public void main(String[] args) throws MsgException {
48     //Check arguments
49     if (args.length != 3 && args.length != 2) {
50       Msg.info("Wrong number of arguments");
51     }
52     if (args.length == 3) {
53       init(Integer.parseInt(args[0]),true);
54     } else {
55       init(Integer.parseInt(args[0]),false);
56     }
57     //Retrieve the deadline
58     deadline = Double.parseDouble(args[1]);
59     if (deadline < 0) {
60       Msg.info("Wrong deadline supplied");
61       return;
62     }
63     Msg.info("Hi, I'm joining the network with id " + id);
64     //Getting peer data from the tracker
65     if (getPeersData()) {
66       Msg.debug("Got " + peers.size() + " peers from the tracker");
67       Msg.debug("Here is my current status: " + getStatus());
68       beginReceiveTime = Msg.getClock();      
69       if (hasFinished()) {
70         pieces = Common.FILE_PIECES;
71         sendHandshakeAll();
72         seedLoop();
73       } else {
74         leechLoop();
75         seedLoop();
76       }
77     } else {
78       Msg.info("Couldn't contact the tracker.");
79     }
80     Msg.info("Here is my current status: " + getStatus());
81   }
82
83   private void leechLoop() {
84     double nextChokedUpdate = Msg.getClock() + Common.UPDATE_CHOKED_INTERVAL;
85     Msg.debug("Start downloading.");
86     // Send a "handshake" message to all the peers it got(it couldn't have gotten more than 50 peers anyway)
87     sendHandshakeAll();
88     //Wait for at least one "bitfield" message.
89     waitForPieces();
90     Msg.debug("Starting main leech loop");
91     while (Msg.getClock() < deadline && pieces < Common.FILE_PIECES) {
92       if (commReceived == null) {
93         commReceived = Task.irecv(mailbox);
94       }
95       try {
96         if (commReceived.test()) {
97           handleMessage(commReceived.getTask());
98           commReceived = null;
99         } else {
100           //If the user has a pending interesting
101           if (currentPiece != -1) {
102             sendInterestedToPeers();
103           } else {
104             if (currentPieces.size() < Common.MAX_PIECES) {
105               updateCurrentPiece();
106             }
107           }
108           //We don't execute the choke algorithm if we don't already have a piece
109           if (Msg.getClock() >= nextChokedUpdate && pieces > 0) {
110             updateChokedPeers();
111             nextChokedUpdate += Common.UPDATE_CHOKED_INTERVAL;
112           } else {
113             waitFor(1);
114           }
115         }
116       }
117       catch (MsgException e) {
118         e.printStackTrace();
119         commReceived = null;
120       }
121     }
122   }
123
124   private void seedLoop() {
125     double nextChokedUpdate = Msg.getClock() + Common.UPDATE_CHOKED_INTERVAL;
126     Msg.debug("Start seeding.");
127     //start the main seed loop
128     while (Msg.getClock() < deadline) {
129       if (commReceived == null) {
130         commReceived = Task.irecv(mailbox);
131       }
132       try {
133         if (commReceived.test()) {
134           handleMessage(commReceived.getTask());
135           commReceived = null;
136         } else {
137           if (Msg.getClock() >= nextChokedUpdate) {
138             updateChokedPeers();
139             //TODO: Change the choked peer algorithm when seeding
140             nextChokedUpdate += Common.UPDATE_CHOKED_INTERVAL;
141           } else {
142             waitFor(1);
143           }
144         }
145       }
146       catch (MsgException e) {
147         commReceived = null;
148       }
149     }
150   }
151
152   /**
153    * @brief Initialize the various peer data
154    * @param id id of the peer to take in the network
155    * @param seed indicates if the peer is a seed
156    */
157   private void init(int id, boolean seed) {
158     this.id = id;
159     this.mailbox = Integer.toString(id);
160     this.mailboxTracker = "tracker_" + Integer.toString(id);
161     if (seed) {
162       for (int i = 0; i < bitfield.length; i++) {
163         bitfield[i] = '1';
164         for (int j = 0; j < bitfieldBlocks[i].length; j++) {
165           bitfieldBlocks[i][j] = '1';
166         }
167       }
168     } else {
169       for (int i = 0; i < bitfield.length; i++) {
170         bitfield[i] = '0';
171         for (int j = 0; j < bitfieldBlocks[i].length; j++) {
172           bitfieldBlocks[i][j] = '0'  ;
173         }
174       }
175     }
176     this.hostname = getHost().getName();
177   }
178
179   private boolean getPeersData() {
180     boolean success = false;
181     double timeout = Msg.getClock() + Common.GET_PEERS_TIMEOUT;
182     //Build the task to send to the tracker
183     TrackerTask taskSend = new TrackerTask(hostname, mailboxTracker, id);
184
185     while (Msg.getClock() < timeout) {
186       try {
187         Msg.debug("Sending a peer request to the tracker.");
188         taskSend.send(Common.TRACKER_MAILBOX,Common.GET_PEERS_TIMEOUT);
189         break;
190       }
191       catch (MsgException e) {
192         e.printStackTrace();
193       }
194     }
195     while (!success && Msg.getClock() < timeout) {
196       commReceived = Task.irecv(this.mailboxTracker);
197       try {
198         commReceived.waitCompletion(Common.GET_PEERS_TIMEOUT);
199         if (commReceived.getTask() instanceof TrackerTask) {
200           TrackerTask task = (TrackerTask)commReceived.getTask();
201           for (Integer peerId: task.peers) {
202             if (peerId != this.id) {
203               peers.put(peerId, new Connection(peerId));
204             }
205           }
206           success = true;
207         }
208       }
209       catch (MsgException e) {
210         e.printStackTrace();
211       }
212       commReceived = null;
213     }
214     return success;
215   }
216
217   private void handleMessage(Task task) {
218     MessageTask message = (MessageTask)task;
219     Connection remotePeer = peers.get(message.peerId);
220     switch (message.type) {
221       case HANDSHAKE:
222         Msg.debug("Received a HANDSHAKE message from " + message.mailbox);
223         //Check if the peer is in our connection list
224         if (remotePeer == null) {
225           peers.put(message.peerId, new Connection(message.peerId));
226           sendHandshake(message.mailbox);
227         }
228         //Send our bitfield to the pair
229         sendBitfield(message.mailbox);
230       break;
231       case BITFIELD:
232         Msg.debug("Received a BITFIELD message from " + message.peerId + " (" + message.issuerHostname + ")");
233         //update the pieces list
234         updatePiecesCountFromBitfield(message.bitfield);
235         //Update the current piece
236         if (currentPiece == -1 && pieces < Common.FILE_PIECES && currentPieces.size() < Common.MAX_PIECES) {
237           updateCurrentPiece();
238         }
239         remotePeer.bitfield  = message.bitfield.clone();
240       break;
241       case INTERESTED:
242         Msg.debug("Received an INTERESTED message from " + message.peerId + " (" + message.issuerHostname + ")");
243         assert remotePeer != null;
244         remotePeer.interested = true;
245       break;
246       case NOTINTERESTED:
247         Msg.debug("Received a NOTINTERESTED message from " + message.peerId + " (" + message.issuerHostname + ")");
248         assert remotePeer != null;
249         remotePeer.interested = false;
250       break;
251       case UNCHOKE:
252         Msg.debug("Received an UNCHOKE message from " + message.peerId + "(" + message.issuerHostname + ")");
253         assert remotePeer != null;
254         remotePeer.chokedDownload = false;
255         activePeers.put(remotePeer.id,remotePeer);
256         sendRequestsToPeer(remotePeer);
257       break;
258       case CHOKE:
259         Msg.debug("Received a CHOKE message from " + message.peerId + " (" + message.issuerHostname + ")");
260         assert remotePeer != null;
261         remotePeer.chokedDownload = true;
262         activePeers.remove(remotePeer.id);
263       break;
264       case HAVE:
265         if (remotePeer.bitfield == null) {
266           return;
267         }
268         Msg.debug("Received a HAVE message from " + message.peerId + " (" + message.issuerHostname + ")");
269         assert message.index >= 0 && message.index < Common.FILE_PIECES;
270         assert remotePeer.bitfield != null;
271         remotePeer.bitfield[message.index] = '1';
272         piecesCount[message.index]++; 
273         //Send interested message to the peer if he has what we want
274         if (!remotePeer.amInterested && currentPieces.contains(message.index) ) {
275           remotePeer.amInterested = true;
276           sendInterested(remotePeer.mailbox);
277         }
278         
279         if (currentPieces.contains(message.index)) {
280           int blockIndex = getFirstBlock(message.index);      
281           int blockLength = Common.PIECES_BLOCKS - blockIndex ;
282           blockLength = blockLength > Common.BLOCKS_REQUESTED ? Common.BLOCKS_REQUESTED : blockLength;    
283           sendRequest(message.mailbox,message.index,blockIndex,blockLength);
284         }
285       break;
286       case REQUEST:
287         assert message.index >= 0 && message.index < Common.FILE_PIECES;
288         if (!remotePeer.chokedUpload) {
289           Msg.debug("Received a REQUEST from " + message.peerId + "(" + message.issuerHostname + ") for " 
290                     + message.peerId);
291           if (bitfield[message.index] == '1') {
292             sendPiece(message.mailbox,message.index,false,message.blockIndex,message.blockLength);  
293           } else {
294             Msg.debug("Received a REQUEST from " + message.peerId + " (" + message.issuerHostname 
295                       + ") but he is choked" );
296           }
297         }
298       break;
299       case PIECE:
300         if (message.stalled) {
301           Msg.debug("The received piece " + message.index + " from " + message.peerId + " (" + message.issuerHostname 
302                     + ") is stalled");
303         } else {
304           Msg.debug("Received piece " + message.index + " from " + message.peerId + " (" 
305                     + message.issuerHostname + ")");
306           if (bitfield[message.index] == '0') {
307             updateBitfieldBlocks(message.index,message.blockIndex,message.blockLength);
308             if (pieceComplete(message.index)) {
309               piecesRequested--;
310               //Removing the piece from our piece list.
311               currentPieces.remove((Object)Integer.valueOf(message.index));
312               //Setting the fact that we have the piece
313               bitfield[message.index] = '1';
314               pieces++;
315               Msg.debug("My status is now " + getStatus());
316               //Sending the information to all the peers we are connected to
317               sendHave(message.index);
318               //sending UNINTERESTED to peers that doesn't have what we want.
319               updateInterestedAfterReceive();
320             }
321           } else {
322             Msg.debug("However, we already have it.");
323           }
324         }
325       break;
326       default:
327         Msg.error("Unexpected message type: " + message.type);
328         break;
329     }
330     if (remotePeer != null) {
331       remotePeer.addSpeedValue(1 / (Msg.getClock() - beginReceiveTime));
332     }
333     beginReceiveTime = Msg.getClock();
334   }
335
336   private void waitForPieces() {
337     boolean finished = false;
338     while (Msg.getClock() < deadline && !finished) {
339       if (commReceived == null) {
340         commReceived = Task.irecv(mailbox);
341       }
342       try {
343         commReceived.waitCompletion(Common.TIMEOUT_MESSAGE);
344         handleMessage(commReceived.getTask());
345         if (currentPiece != -1) {
346           finished = true;
347         }
348         commReceived = null;
349       }
350       catch (MsgException e) {
351         commReceived = null;
352       }
353     }
354   }
355
356   private boolean hasFinished() {
357     for (int i = 0; i < bitfield.length; i++) {
358       if (bitfield[i] == '1') {
359         return true;
360       }
361     }
362     return false;
363   }
364
365   /**
366    * @brief Updates the list of who has a piece from a bitfield
367    * @param bitfield bitfield
368    */
369   private void updatePiecesCountFromBitfield(char[] bitfield) {
370     for (int i = 0; i < Common.FILE_PIECES; i++) {
371       if (bitfield[i] == '1') {
372         piecesCount[i]++;
373       }
374     }
375   }
376
377   /**
378    * Update the piece the peer is currently interested in.
379    * There is two cases (as described in "Bittorrent Architecture Protocol", Ryan Toole :
380    * If the peer has less than 3 pieces, he chooses a piece at random.
381    * If the peer has more than pieces, he downloads the pieces that are the less
382    * replicated
383    */
384   private void updateCurrentPiece() {
385     if (currentPieces.size() >= (Common.FILE_PIECES - pieces)) {
386       return;
387     }
388
389     //TODO: trivial min algorithm when pieces >= 3
390     do {
391       currentPiece = stream.randInt(0,Common.FILE_PIECES - 1);
392     } while (!(bitfield[currentPiece] == '0' && !currentPieces.contains(currentPiece)));
393
394     currentPieces.add(currentPiece);
395     Msg.debug("New interested piece: " + currentPiece);
396     assert currentPiece >= 0 && currentPiece < Common.FILE_PIECES;
397   }
398
399   // Update the list of current choked and unchoked peers, using the choke algorithm
400   private void updateChokedPeers() {
401     round = (round + 1) % 3;
402     if (peers.size() == 0) {
403       return;
404     }
405     //remove a peer from the list
406     Iterator<Entry<Integer, Connection>> it = activePeers.entrySet().iterator();
407     if (it.hasNext()) {
408       Entry<Integer,Connection> e = it.next();
409       Connection peerChoked = e.getValue();
410       peerChoked.chokedUpload = true;
411       sendChoked(peerChoked.mailbox);
412       activePeers.remove(e.getKey());
413     }
414     Connection peerChoosed = null;
415     //Separate the case from when the peer is seeding.
416     if (pieces == Common.FILE_PIECES) {
417       //Find the last unchoked peer.
418       double unchokeTime = deadline + 1;
419       for (Connection connection : peers.values()) {
420         if (connection.lastUnchoke < unchokeTime && connection.interested) {
421           peerChoosed = connection;
422           unchokeTime = connection.lastUnchoke;
423         }
424       }
425     } else {
426       //Random optimistic unchoking
427       if (round == 0) {
428         int j = 0;
429         do {
430           int i = 0;
431           int idChosen = stream.randInt(0,peers.size() - 1);
432           for (Connection connection : peers.values()) {
433             if (i == idChosen) {
434               peerChoosed = connection;
435               break;
436             }
437             i++;
438           } //TODO: Not really the best way ever
439           if (peerChoosed != null && !peerChoosed.interested) {
440             peerChoosed = null;
441           }
442           j++;
443         } while (peerChoosed == null && j < Common.MAXIMUM_PEERS);
444       } else {
445         Connection fastest = null;
446         double fastestSpeed = 0;
447         for (Connection c : peers.values()) {
448           if (c.peerSpeed > fastestSpeed && c.interested && c.chokedUpload) {
449             fastest = c;
450             fastestSpeed = c.peerSpeed;
451           }
452         }
453         peerChoosed = fastest;
454       }
455     }
456     if (peerChoosed != null) {
457       activePeers.put(peerChoosed.id,peerChoosed);
458       peerChoosed.chokedUpload = false;
459       peerChoosed.lastUnchoke = Msg.getClock();
460       sendUnchoked(peerChoosed.mailbox);
461     }
462   }
463
464   // Updates our "interested" state about peers: send "not interested" to peers that don't have any more pieces we want.
465   private void updateInterestedAfterReceive() {
466     boolean interested;
467     for (Connection connection : peers.values()) {
468       interested = false;
469       if (connection.amInterested) {
470         for (Integer piece : currentPieces) {
471           if (connection.bitfield[piece] == '1') {
472             interested = true;
473             break;
474           }
475         }
476         if (!interested) {
477           connection.amInterested = false;
478           sendNotInterested(connection.mailbox);
479         }
480       }
481     }
482   }
483
484   private void updateBitfieldBlocks(int index, int blockIndex, int blockLength) {
485     for (int i = blockIndex; i < (blockIndex + blockLength); i++) {
486       bitfieldBlocks[index][i] = '1';
487     }
488   }
489
490   // Returns if a piece is complete in the peer's bitfield.
491   private boolean pieceComplete(int index) {
492     for (int i = 0; i < bitfieldBlocks[index].length; i++) {
493       if (bitfieldBlocks[index][i] == '0') {
494         return false;
495       }
496     }
497     return true;
498   }
499
500   // Returns the first block of a piece that we don't have. 
501   private int getFirstBlock(int piece) {
502     int blockIndex = -1;
503     for (int i = 0; i < Common.PIECES_BLOCKS; i++) {
504       if (bitfieldBlocks[piece][i] == '0') {
505         blockIndex = i;
506         break;
507       }
508     }
509     return blockIndex;
510   }
511
512   /**
513    * @brief Send request messages to a peer that have unchoked us
514    * @param remotePeer peer data to the peer we want to send the request
515    */
516   private void sendRequestsToPeer(Connection remotePeer) {
517     if (remotePeer.bitfield == null) {
518       return;
519     }
520     for (Integer piece : currentPieces) {
521       //Getting the block to send.
522       int blockIndex = getFirstBlock(piece);
523       int blockLength = Common.PIECES_BLOCKS - blockIndex ;
524       blockLength = blockLength > Common.BLOCKS_REQUESTED ? Common.BLOCKS_REQUESTED : blockLength;    
525       if (remotePeer.bitfield[piece] == '1') {
526         sendRequest(remotePeer.mailbox, piece, blockIndex, blockLength);
527       }
528     }
529   }
530
531   // Find the peers that have the current interested piece and send them the "interested" message
532   private void sendInterestedToPeers() {
533     if (currentPiece == -1) {
534       return;
535     }
536     for (Connection connection : peers.values()) {
537       if (connection.bitfield != null && connection.bitfield[currentPiece] == '1' && !connection.amInterested) {
538         connection.amInterested = true;        
539         MessageTask task = new MessageTask(MessageTask.Type.INTERESTED, hostname, this.mailbox, this.id);
540         task.dsend(connection.mailbox);        
541       }
542     }
543     currentPiece = -1;
544     piecesRequested++;
545   }
546
547   // Send a "interested" message to a peer.
548   private void sendInterested(String mailbox) {
549     MessageTask task = new MessageTask(MessageTask.Type.INTERESTED, hostname, this.mailbox, this.id);
550     task.dsend(mailbox);
551   }
552
553   /**
554    * @brief Send a "not interested" message to a peer
555    * @param mailbox mailbox destination mailbox
556    */
557   private void sendNotInterested(String mailbox) {
558     MessageTask task = new MessageTask(MessageTask.Type.NOTINTERESTED, hostname, this.mailbox, this.id);
559     task.dsend(mailbox);
560   }
561
562   // Send a handshake message to all the peers the peer has.
563   private void sendHandshakeAll() {
564     for (Connection remotePeer : peers.values()) {
565       MessageTask task = new MessageTask(MessageTask.Type.HANDSHAKE, hostname, mailbox, id);
566       task.dsend(remotePeer.mailbox);
567     }
568   }
569
570   /**
571    * @brief Send a "handshake" message to an user
572    * @param mailbox mailbox where to we send the message
573    */
574   private void sendHandshake(String mailbox) {
575     Msg.debug("Sending a HANDSHAKE to " + mailbox);
576     MessageTask task = new MessageTask(MessageTask.Type.HANDSHAKE, hostname, this.mailbox, this.id);
577     task.dsend(mailbox);
578   }
579
580   // Send a "choked" message to a peer
581   private void sendChoked(String mailbox) {
582     Msg.debug("Sending a CHOKE to " + mailbox);
583     MessageTask task = new MessageTask(MessageTask.Type.CHOKE, hostname, this.mailbox, this.id);
584     task.dsend(mailbox);
585   }
586
587   // Send a "unchoked" message to a peer
588   private void sendUnchoked(String mailbox) {
589     Msg.debug("Sending a UNCHOKE to " + mailbox);
590     MessageTask task = new MessageTask(MessageTask.Type.UNCHOKE, hostname, this.mailbox, this.id);
591     task.dsend(mailbox);
592   }
593
594   // Send a "HAVE" message to all peers we are connected to
595   private void sendHave(int piece) {
596     Msg.debug("Sending HAVE message to all my peers");
597     for (Connection remotePeer : peers.values()) {
598       MessageTask task = new MessageTask(MessageTask.Type.HAVE, hostname, this.mailbox, this.id, piece);
599       task.dsend(remotePeer.mailbox);
600     }
601   }
602   // Send a bitfield message to all the peers the peer has.
603   private void sendBitfield(String mailbox) {
604     Msg.debug("Sending a BITFIELD to " + mailbox);
605     MessageTask task = new MessageTask(MessageTask.Type.BITFIELD, hostname, this.mailbox, this.id, this.bitfield);
606     task.dsend(mailbox);
607   }
608   // Send a "request" message to a peer, containing a request for a piece
609   private void sendRequest(String mailbox, int piece, int blockIndex, int blockLength) {
610     Msg.debug("Sending a REQUEST to " + mailbox + " for piece " + piece + " and blocks " + blockIndex + ","
611               + (blockIndex + blockLength));
612     MessageTask task = new MessageTask(MessageTask.Type.REQUEST, hostname, this.mailbox, this.id, piece, blockIndex, 
613                                        blockLength);
614     task.dsend(mailbox);
615   }
616
617   // Send a "piece" message to a peer, containing a piece of the file
618   private void sendPiece(String mailbox, int piece, boolean stalled, int blockIndex, int blockLength) {
619     Msg.debug("Sending the PIECE " + piece + " to " + mailbox);
620     MessageTask task = new MessageTask(MessageTask.Type.PIECE, hostname, this.mailbox, this.id, piece, stalled,
621                                        blockIndex, blockLength);
622     task.dsend(mailbox);
623   }
624
625   private String getStatus() {
626     StringBuilder s = new StringBuilder("");
627     for (int i = 0; i < Common.FILE_PIECES; i++)
628       s.append(bitfield[i]);
629     return s.toString();
630   }
631 }