Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Removing RngStream
[simgrid.git] / examples / deprecated / java / app / bittorrent / Tracker.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 import java.util.ArrayList;
9 import java.util.Random;
10
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;
17
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;
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     //Retrieve the end time
35     deadline = Double.parseDouble(args[0]);
36     //Building peers array
37     peersList = new ArrayList<>();
38
39     Msg.info("Tracker launched.");
40     while (Msg.getClock() < deadline) {
41       if (commReceived == null) {
42         commReceived = Task.irecv(Common.TRACKER_MAILBOX);
43       }
44       try {
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
50             int nbPeers = 0;
51             while (nbPeers < Common.MAXIMUM_PEERS && nbPeers < peersList.size()) {
52               int nextPeer;
53               do {
54                 nextPeer = rand.nextInt(peersList.size());
55               } while (tTask.peers.contains(peersList.get(nextPeer)));
56               tTask.peers.add(peersList.get(nextPeer));
57               nbPeers++;
58             }
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);
66           }
67           commReceived = null;
68         } else {
69           waitFor(1);
70         }
71       }
72       catch (MsgException e) {
73         commReceived = null;
74       }
75     }
76     Msg.info("Tracker is leaving");
77   }
78 }