Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
codacy
[simgrid.git] / examples / s4u / app-bittorrent / s4u_tracker.cpp
1 /* Copyright (c) 2012-2017. 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 <xbt/RngStream.h>
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 (std::invalid_argument& ia) {
20     throw std::invalid_argument(std::string("Invalid deadline:") + args[1].c_str());
21   }
22   xbt_assert(deadline > 0, "Wrong deadline supplied");
23
24   stream = simgrid::s4u::this_actor::getHost()->extension<HostBittorrent>()->getStream();
25
26   mailbox = simgrid::s4u::Mailbox::byName(TRACKER_MAILBOX);
27
28   XBT_INFO("Tracker launched.");
29 }
30
31 void Tracker::operator()()
32 {
33   simgrid::s4u::CommPtr comm = nullptr;
34   while (simgrid::s4u::Engine::getClock() < deadline) {
35     void* received;
36     if (comm == nullptr)
37       comm = mailbox->get_async(&received);
38     if (comm->test()) {
39       // Retrieve the data sent by the peer.
40       TrackerQuery* tq = static_cast<TrackerQuery*>(received);
41
42       // Add the peer to our peer list, if not already known.
43       if (known_peers.find(tq->getPeerId()) == known_peers.end()) {
44         known_peers.insert(tq->getPeerId());
45       }
46
47       // Sending back peers to the requesting peer
48       TrackerAnswer* ta = new TrackerAnswer(TRACKER_QUERY_INTERVAL);
49       std::set<int>::iterator next_peer;
50       int nb_known_peers = known_peers.size();
51       int max_tries      = MIN(MAXIMUM_PEERS, nb_known_peers);
52       int tried          = 0;
53       while (tried < max_tries) {
54         do {
55           next_peer = known_peers.begin();
56           std::advance(next_peer, RngStream_RandInt(stream, 0, nb_known_peers - 1));
57         } while (ta->getPeers()->find(*next_peer) != ta->getPeers()->end());
58         ta->addPeer(*next_peer);
59         tried++;
60       }
61       tq->getReturnMailbox()->put_init(ta, TRACKER_COMM_SIZE)->detach();
62
63       delete tq;
64       comm = nullptr;
65     } else {
66       simgrid::s4u::this_actor::sleep_for(1);
67     }
68   }
69   XBT_INFO("Tracker is leaving");
70 }