Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
f613bb9ca922e8c936b5af8402b4868a8d48dd7a
[simgrid.git] / examples / java / app / bittorrent / Tracker.java
1 /* Copyright (c) 2006-2014, 2026. 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 import java.util.ArrayList;
9
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;
17
18 public class Tracker extends Process {
19   protected RngStream stream;
20   protected ArrayList<Integer> peersList;
21   protected double deadline;
22   protected Comm commReceived = null;
23
24   public Tracker(Host host, String name, String[]args) {
25     super(host,name,args);
26   }
27
28   @Override
29   public void main(String[] args) throws MsgException {
30     if (args.length != 1) {
31       Msg.info("Wrong number of arguments for the tracker.");
32       return;
33     }
34     //Build the RngStream object for randomness
35     stream = new RngStream("tracker");
36     //Retrieve the end time
37     deadline = Double.valueOf(args[0]);
38     //Building peers array
39     peersList = new ArrayList<>();
40
41     Msg.info("Tracker launched.");
42     while (Msg.getClock() < deadline) {
43       if (commReceived == null) {
44         commReceived = Task.irecv(Common.TRACKER_MAILBOX);
45       }
46       try {
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
52             int nbPeers = 0;
53             while (nbPeers < Common.MAXIMUM_PEERS && nbPeers < peersList.size()) {
54               int nextPeer;
55               do {
56                 nextPeer = stream.randInt(0, peersList.size() - 1);
57               } while (tTask.peers.contains(nextPeer));
58               tTask.peers.add(peersList.get(nextPeer));
59               nbPeers++;
60             }
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);
68           }
69           commReceived = null;
70         } else {
71           waitFor(1);
72         }
73       }
74       catch (MsgException e) {
75         commReceived = null;
76       }
77     }
78     Msg.info("Tracker is leaving");
79   }
80 }