Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge branch 'master' into adrien
[simgrid.git] / examples / s4u / app-bittorrent / s4u-tracker.cpp
1 /* Copyright (c) 2012-2020. 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 #include "s4u-tracker.hpp"
8 #include <algorithm>
9
10 XBT_LOG_NEW_DEFAULT_CATEGORY(s4u_bt_tracker, "Messages specific for the tracker");
11
12 Tracker::Tracker(std::vector<std::string> args)
13 {
14   // Checking arguments
15   xbt_assert(args.size() == 2, "Wrong number of arguments for the tracker.");
16   // Retrieving end time
17   try {
18     deadline = std::stod(args[1]);
19   } catch (const std::invalid_argument&) {
20     throw std::invalid_argument("Invalid deadline:" + args[1]);
21   }
22   xbt_assert(deadline > 0, "Wrong deadline supplied");
23
24   mailbox = simgrid::s4u::Mailbox::by_name(TRACKER_MAILBOX);
25
26   XBT_INFO("Tracker launched.");
27 }
28
29 void Tracker::operator()()
30 {
31   simgrid::s4u::CommPtr comm = nullptr;
32   void* received             = nullptr;
33   while (simgrid::s4u::Engine::get_clock() < deadline) {
34     if (comm == nullptr)
35       comm = mailbox->get_async(&received);
36     if (comm->test()) {
37       // Retrieve the data sent by the peer.
38       xbt_assert(received != nullptr);
39       TrackerQuery* tq = static_cast<TrackerQuery*>(received);
40
41       // Add the peer to our peer list, if not already known.
42       if (known_peers.find(tq->getPeerId()) == known_peers.end()) {
43         known_peers.insert(tq->getPeerId());
44       }
45
46       // Sending back peers to the requesting peer
47       TrackerAnswer* ta = new TrackerAnswer(TRACKER_QUERY_INTERVAL);
48       std::set<int>::iterator next_peer;
49       int nb_known_peers = static_cast<int>(known_peers.size());
50       int max_tries      = std::min(MAXIMUM_PEERS, nb_known_peers);
51       int tried          = 0;
52       while (tried < max_tries) {
53         do {
54           next_peer = known_peers.begin();
55           std::advance(next_peer, random.uniform_int(0, nb_known_peers - 1));
56         } while (ta->getPeers().find(*next_peer) != ta->getPeers().end());
57         ta->addPeer(*next_peer);
58         tried++;
59       }
60       tq->getReturnMailbox()->put_init(ta, TRACKER_COMM_SIZE)->detach();
61
62       delete tq;
63       comm = nullptr;
64     } else {
65       simgrid::s4u::this_actor::sleep_for(1);
66     }
67   }
68   XBT_INFO("Tracker is leaving");
69 }