summaryrefslogtreecommitdiffstats
path: root/filedistribution/src/vespa/filedistribution/distributor/filedistributortrackerimpl.cpp
blob: 9906074afc598260071418495f10a56cb926ec40 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "filedistributortrackerimpl.h"
#include "filedownloader.h"
#include <vespa/filedistribution/model/zkfacade.h>

#include <vespa/log/log.h>
LOG_SETUP(".filedistributiontrackerimpl");

using namespace filedistribution;

typedef FileDistributionModel::PeerEntries PeerEntries;

namespace asio = boost::asio;

namespace {

void
filterSelf(FileDistributionModel::PeerEntries& peers,
           const std::string& hostName,
           int port)
{
    FileDistributionModel::PeerEntries::iterator
        i = peers.begin(),
        currEnd = peers.end();

    while ( i != currEnd ) {
        //hostName is currently used in the ip field
        if (i->ip == hostName && i->port == port) {
            --currEnd;
            std::swap(*i, *currEnd);
        } else {
            ++i;
        }
    }

    peers.erase(currEnd, peers.end());
}

void resolveIPAddresses(PeerEntries& peers) {
    for (auto& p: peers) {
        try {
            p.ip = filedistribution::lookupIPAddress(p.ip);
        } catch (filedistribution::FailedResolvingHostName& e) {
            LOG(info, "Failed resolving address %s", p.ip.c_str());
        }
    }
}

struct TrackingTask : public Scheduler::Task {
    int _numTimesRescheduled;

    libtorrent::tracker_request _trackerRequest;
    boost::weak_ptr<libtorrent::torrent> _torrent;
    std::weak_ptr<FileDownloader> _downloader;
    std::shared_ptr<FileDistributionModel> _model;

    TrackingTask(Scheduler& scheduler,
                 const libtorrent::tracker_request& trackerRequest,
                 const TorrentSP & torrent,
                 const std::weak_ptr<FileDownloader>& downloader,
                 const std::shared_ptr<FileDistributionModel>& model);
    ~TrackingTask();

    //TODO: refactor
    void doHandle() override;
    PeerEntries getPeers(const std::shared_ptr<FileDownloader>& downloader);
    void reschedule();
};

TrackingTask::TrackingTask(Scheduler& scheduler,
                           const libtorrent::tracker_request& trackerRequest,
                           const TorrentSP & torrent,
                           const std::weak_ptr<FileDownloader>& downloader,
                           const std::shared_ptr<FileDistributionModel>& model)
    : Task(scheduler),
      _numTimesRescheduled(0),
      _trackerRequest(trackerRequest),
      _torrent(torrent),
      _downloader(downloader),
      _model(model)
{ }

TrackingTask::~TrackingTask() {}

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Winline"
//TODO: refactor
void
TrackingTask::doHandle() {
    if (std::shared_ptr<FileDownloader> downloader = _downloader.lock()) {
        //All torrents must be destructed before the session is destructed.
        //It's okay to prevent the torrent from expiring here
        //since the session can't be destructed while
        //we hold a shared_ptr to the downloader.
        if (TorrentSP torrent = _torrent.lock()) {
            PeerEntries peers = getPeers(downloader);

            if (!peers.empty()) {
                torrent->session().m_io_service.dispatch(
                [torrent_weak_ptr = _torrent, trackerRequest = _trackerRequest, peers = peers]() mutable {
                    if (auto torrent_sp = torrent_weak_ptr.lock()) {
                        torrent_sp->tracker_response(
                                trackerRequest,
                                libtorrent::address(),
                                std::list<libtorrent::address>(),
                                peers,
                                -1, -1, -1, -1, -1,
                                libtorrent::address(), "trackerid");
                    }
                });
            }

            if (peers.size() < 5) {
                reschedule();
            }
        }
    }
}
#pragma GCC diagnostic pop

PeerEntries
TrackingTask::getPeers(const std::shared_ptr<FileDownloader>& downloader) {
    std::string fileReference = downloader->infoHash2FileReference(_trackerRequest.info_hash);

    const size_t recommendedMaxNumberOfPeers = 30;
    PeerEntries peers = _model->getPeers(fileReference, recommendedMaxNumberOfPeers);

    //currently, libtorrent stops working if it tries to connect to itself.
    filterSelf(peers, downloader->_hostName, downloader->_port);
    resolveIPAddresses(peers);
    for (const auto& peer: peers) {
        LOG(debug, "Returning peer with ip %s", peer.ip.c_str());
    }

    return peers;
}

void
TrackingTask::reschedule() {
    if (_numTimesRescheduled < 5) {
        double fudgeFactor = 0.1;
        schedule(boost::posix_time::seconds(static_cast<int>(
                                                    std::pow(3., _numTimesRescheduled) + fudgeFactor)));
        _numTimesRescheduled++;
    }
}

} //anonymous namespace

FileDistributorTrackerImpl::FileDistributorTrackerImpl(const std::shared_ptr<FileDistributionModel>& model) :
     _model(model)
{}

FileDistributorTrackerImpl::~FileDistributorTrackerImpl() {
    LOG(debug, "Deconstructing FileDistributorTrackerImpl");

    LockGuard guard(_mutex);
    _scheduler.reset();
}

void
FileDistributorTrackerImpl::trackingRequest(
        libtorrent::tracker_request& request,
        const TorrentSP & torrent)
{
    LockGuard guard(_mutex);

    if (torrent != TorrentSP()) {
        std::shared_ptr<TrackingTask> trackingTask(new TrackingTask(
                        *_scheduler.get(), request, torrent, _downloader, _model));

        trackingTask->scheduleNow();
    }
}

void asioWorker(asio::io_service& ioService)
{
    while (!ioService.stopped()) {
        try {
            ioService.run();
        } catch (const ZKConnectionLossException & e) {
            LOG(info, "Connection loss in asioWorker thread, resuming. %s", e.what());
        } catch (const ZKOperationTimeoutException & e) {
            LOG(warning, "Operation timed out in asioWorker thread, will do quick exit to start a clean sheet. %s", e.what());
            std::quick_exit(31);
        }
    }
}

void
FileDistributorTrackerImpl::setDownloader(const std::shared_ptr<FileDownloader>& downloader)
{
    LockGuard guard(_mutex);

    _scheduler.reset();
    _downloader = downloader;

    if (downloader) {
        _scheduler.reset(new Scheduler([] (asio::io_service& ioService) { asioWorker(ioService); }));
    }
}