1 /* Copyright (c) 2006-2014, 2016. 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;
10 import org.simgrid.msg.Msg;
11 import org.simgrid.msg.Comm;
12 import org.simgrid.msg.Host;
13 import org.simgrid.msg.Task;
14 import org.simgrid.msg.Process;
15 import org.simgrid.msg.RngStream;
16 import org.simgrid.msg.MsgException;
18 public class Tracker extends Process {
19 protected RngStream stream;
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 //Build the RngStream object for randomness
35 stream = new RngStream("tracker");
36 //Retrieve the end time
37 deadline = Double.parseDouble(args[0]);
38 //Building peers array
39 peersList = new ArrayList<>();
41 Msg.info("Tracker launched.");
42 while (Msg.getClock() < deadline) {
43 if (commReceived == null) {
44 commReceived = Task.irecv(Common.TRACKER_MAILBOX);
47 if (commReceived.test()) {
48 Task task = commReceived.getTask();
49 if (task instanceof TrackerTask) {
50 TrackerTask tTask = (TrackerTask)task;
51 //Sending peers to the peer
53 while (nbPeers < Common.MAXIMUM_PEERS && nbPeers < peersList.size()) {
56 nextPeer = stream.randInt(0, peersList.size() - 1);
57 } while (tTask.peers.contains(peersList.get(nextPeer)));
58 tTask.peers.add(peersList.get(nextPeer));
61 //Adding the peer to our list
62 peersList.add(tTask.peerId);
63 tTask.type = TrackerTask.Type.ANSWER;
64 //Setting the interval
65 tTask.interval = Common.TRACKER_QUERY_INTERVAL;
66 //Sending the task back to the peer
67 tTask.dsend(tTask.mailbox);
74 catch (MsgException e) {
78 Msg.info("Tracker is leaving");