1 /* Copyright (c) 2006-2019. 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. */
7 package app.bittorrent;
9 import java.util.ArrayList;
10 import java.util.HashMap;
11 import java.util.Iterator;
12 import java.util.Map.Entry;
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;
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();
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;
42 public Peer(Host host, String name, String[]args) {
43 super(host,name,args);
47 public void main(String[] args) throws MsgException {
49 if (args.length != 3 && args.length != 2) {
50 Msg.info("Wrong number of arguments");
52 if (args.length == 3) {
53 init(Integer.parseInt(args[0]),true);
55 init(Integer.parseInt(args[0]),false);
57 //Retrieve the deadline
58 deadline = Double.parseDouble(args[1]);
60 Msg.info("Wrong deadline supplied");
63 Msg.info("Hi, I'm joining the network with id " + id);
64 //Getting peer data from the tracker
66 Msg.debug("Got " + peers.size() + " peers from the tracker");
67 Msg.debug("Here is my current status: " + getStatus());
68 beginReceiveTime = Msg.getClock();
70 pieces = Common.FILE_PIECES;
78 Msg.info("Couldn't contact the tracker.");
80 Msg.info("Here is my current status: " + getStatus());
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)
88 //Wait for at least one "bitfield" message.
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);
96 if (commReceived.test()) {
97 handleMessage(commReceived.getTask());
100 //If the user has a pending interesting
101 if (currentPiece != -1) {
102 sendInterestedToPeers();
104 if (currentPieces.size() < Common.MAX_PIECES) {
105 updateCurrentPiece();
108 //We don't execute the choke algorithm if we don't already have a piece
109 if (Msg.getClock() >= nextChokedUpdate && pieces > 0) {
111 nextChokedUpdate += Common.UPDATE_CHOKED_INTERVAL;
117 catch (MsgException e) {
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);
133 if (commReceived.test()) {
134 handleMessage(commReceived.getTask());
137 if (Msg.getClock() >= nextChokedUpdate) {
139 //TODO: Change the choked peer algorithm when seeding
140 nextChokedUpdate += Common.UPDATE_CHOKED_INTERVAL;
146 catch (MsgException e) {
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
157 private void init(int id, boolean seed) {
159 this.mailbox = Integer.toString(id);
160 this.mailboxTracker = "tracker_" + Integer.toString(id);
162 for (int i = 0; i < bitfield.length; i++) {
164 for (int j = 0; j < bitfieldBlocks[i].length; j++) {
165 bitfieldBlocks[i][j] = '1';
169 for (int i = 0; i < bitfield.length; i++) {
171 for (int j = 0; j < bitfieldBlocks[i].length; j++) {
172 bitfieldBlocks[i][j] = '0' ;
176 this.hostname = getHost().getName();
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);
185 while (Msg.getClock() < timeout) {
187 Msg.debug("Sending a peer request to the tracker.");
188 taskSend.send(Common.TRACKER_MAILBOX,Common.GET_PEERS_TIMEOUT);
191 catch (MsgException e) {
195 while (!success && Msg.getClock() < timeout) {
196 commReceived = Task.irecv(this.mailboxTracker);
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));
209 catch (MsgException e) {
217 private void handleMessage(Task task) {
218 MessageTask message = (MessageTask)task;
219 Connection remotePeer = peers.get(message.peerId);
220 switch (message.type) {
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);
228 //Send our bitfield to the pair
229 sendBitfield(message.mailbox);
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();
239 remotePeer.bitfield = message.bitfield.clone();
242 Msg.debug("Received an INTERESTED message from " + message.peerId + " (" + message.issuerHostname + ")");
243 assert remotePeer != null;
244 remotePeer.interested = true;
247 Msg.debug("Received a NOTINTERESTED message from " + message.peerId + " (" + message.issuerHostname + ")");
248 assert remotePeer != null;
249 remotePeer.interested = false;
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);
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);
265 if (remotePeer.bitfield == null) {
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);
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);
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 "
291 if (bitfield[message.index] == '1') {
292 sendPiece(message.mailbox,message.index,false,message.blockIndex,message.blockLength);
294 Msg.debug("Received a REQUEST from " + message.peerId + " (" + message.issuerHostname
295 + ") but he is choked" );
300 if (message.stalled) {
301 Msg.debug("The received piece " + message.index + " from " + message.peerId + " (" + message.issuerHostname
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)) {
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';
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();
322 Msg.debug("However, we already have it.");
327 Msg.error("Unexpected message type: " + message.type);
330 if (remotePeer != null) {
331 remotePeer.addSpeedValue(1 / (Msg.getClock() - beginReceiveTime));
333 beginReceiveTime = Msg.getClock();
336 private void waitForPieces() {
337 boolean finished = false;
338 while (Msg.getClock() < deadline && !finished) {
339 if (commReceived == null) {
340 commReceived = Task.irecv(mailbox);
343 commReceived.waitCompletion(Common.TIMEOUT_MESSAGE);
344 handleMessage(commReceived.getTask());
345 if (currentPiece != -1) {
350 catch (MsgException e) {
356 private boolean hasFinished() {
357 for (int i = 0; i < bitfield.length; i++) {
358 if (bitfield[i] == '1') {
366 * @brief Updates the list of who has a piece from a bitfield
367 * @param bitfield bitfield
369 private void updatePiecesCountFromBitfield(char[] bitfield) {
370 for (int i = 0; i < Common.FILE_PIECES; i++) {
371 if (bitfield[i] == '1') {
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
384 private void updateCurrentPiece() {
385 if (currentPieces.size() >= (Common.FILE_PIECES - pieces)) {
389 //TODO: trivial min algorithm when pieces >= 3
391 currentPiece = stream.randInt(0,Common.FILE_PIECES - 1);
392 } while (!(bitfield[currentPiece] == '0' && !currentPieces.contains(currentPiece)));
394 currentPieces.add(currentPiece);
395 Msg.debug("New interested piece: " + currentPiece);
396 assert currentPiece >= 0 && currentPiece < Common.FILE_PIECES;
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) {
405 //remove a peer from the list
406 Iterator<Entry<Integer, Connection>> it = activePeers.entrySet().iterator();
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());
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;
426 //Random optimistic unchoking
431 int idChosen = stream.randInt(0,peers.size() - 1);
432 for (Connection connection : peers.values()) {
434 peerChoosed = connection;
438 } //TODO: Not really the best way ever
439 if (peerChoosed != null && !peerChoosed.interested) {
443 } while (peerChoosed == null && j < Common.MAXIMUM_PEERS);
445 Connection fastest = null;
446 double fastestSpeed = 0;
447 for (Connection c : peers.values()) {
448 if (c.peerSpeed > fastestSpeed && c.interested && c.chokedUpload) {
450 fastestSpeed = c.peerSpeed;
453 peerChoosed = fastest;
456 if (peerChoosed != null) {
457 activePeers.put(peerChoosed.id,peerChoosed);
458 peerChoosed.chokedUpload = false;
459 peerChoosed.lastUnchoke = Msg.getClock();
460 sendUnchoked(peerChoosed.mailbox);
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() {
467 for (Connection connection : peers.values()) {
469 if (connection.amInterested) {
470 for (Integer piece : currentPieces) {
471 if (connection.bitfield[piece] == '1') {
477 connection.amInterested = false;
478 sendNotInterested(connection.mailbox);
484 private void updateBitfieldBlocks(int index, int blockIndex, int blockLength) {
485 for (int i = blockIndex; i < (blockIndex + blockLength); i++) {
486 bitfieldBlocks[index][i] = '1';
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') {
500 // Returns the first block of a piece that we don't have.
501 private int getFirstBlock(int piece) {
503 for (int i = 0; i < Common.PIECES_BLOCKS; i++) {
504 if (bitfieldBlocks[piece][i] == '0') {
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
516 private void sendRequestsToPeer(Connection remotePeer) {
517 if (remotePeer.bitfield == null) {
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);
531 // Find the peers that have the current interested piece and send them the "interested" message
532 private void sendInterestedToPeers() {
533 if (currentPiece == -1) {
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);
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);
554 * @brief Send a "not interested" message to a peer
555 * @param mailbox mailbox destination mailbox
557 private void sendNotInterested(String mailbox) {
558 MessageTask task = new MessageTask(MessageTask.Type.NOTINTERESTED, hostname, this.mailbox, this.id);
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);
571 * @brief Send a "handshake" message to an user
572 * @param mailbox mailbox where to we send the message
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);
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);
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);
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);
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);
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,
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);
625 private String getStatus() {
626 StringBuilder s = new StringBuilder("");
627 for (int i = 0; i < Common.FILE_PIECES; i++)
628 s.append(bitfield[i]);