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;
8 import java.util.ArrayList;
9 import java.util.Random;
11 import org.simgrid.msg.Msg;
12 import org.simgrid.msg.Comm;
13 import org.simgrid.msg.Host;
14 import org.simgrid.msg.Task;
15 import org.simgrid.msg.Process;
16 import org.simgrid.msg.MsgException;
18 public class Tracker extends Process {
19 Random rand = new Random();
20 protected ArrayList<Integer> peersList;
21 protected double deadline;
22 protected Comm commReceived = null;
24 public Tracker(Host host, String name, String[]args) {
25 super(host,name,args);
29 public void main(String[] args) throws MsgException {
30 if (args.length != 1) {
31 Msg.info("Wrong number of arguments for the tracker.");
34 //Retrieve the end time
35 deadline = Double.parseDouble(args[0]);
36 //Building peers array
37 peersList = new ArrayList<>();
39 Msg.info("Tracker launched.");
40 while (Msg.getClock() < deadline) {
41 if (commReceived == null) {
42 commReceived = Task.irecv(Common.TRACKER_MAILBOX);
45 if (commReceived.test()) {
46 Task task = commReceived.getTask();
47 if (task instanceof TrackerTask) {
48 TrackerTask tTask = (TrackerTask)task;
49 //Sending peers to the peer
51 while (nbPeers < Common.MAXIMUM_PEERS && nbPeers < peersList.size()) {
54 nextPeer = rand.nextInt(peersList.size());
55 } while (tTask.peers.contains(peersList.get(nextPeer)));
56 tTask.peers.add(peersList.get(nextPeer));
59 //Adding the peer to our list
60 peersList.add(tTask.peerId);
61 tTask.type = TrackerTask.Type.ANSWER;
62 //Setting the interval
63 tTask.interval = Common.TRACKER_QUERY_INTERVAL;
64 //Sending the task back to the peer
65 tTask.dsend(tTask.mailbox);
72 catch (MsgException e) {
76 Msg.info("Tracker is leaving");