123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488 |
- /* <!-- copyright */
- /*
- * aria2 - The high speed download utility
- *
- * Copyright (C) 2006 Tatsuhiro Tsujikawa
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- *
- * In addition, as a special exception, the copyright holders give
- * permission to link the code of portions of this program with the
- * OpenSSL library under certain conditions as described in each
- * individual source file, and distribute linked combinations
- * including the two.
- * You must obey the GNU General Public License in all respects
- * for all of the code used other than OpenSSL. If you modify
- * file(s) with this exception, you may extend this exception to your
- * version of the file(s), but you are not obligated to do so. If you
- * do not wish to do so, delete this exception statement from your
- * version. If you delete this exception statement from all source
- * files in the program, then also delete it here.
- */
- /* copyright --> */
- #include "SegmentMan.h"
- #include <cassert>
- #include <algorithm>
- #include <numeric>
- #include "util.h"
- #include "message.h"
- #include "prefs.h"
- #include "PiecedSegment.h"
- #include "GrowSegment.h"
- #include "LogFactory.h"
- #include "Logger.h"
- #include "PieceStorage.h"
- #include "PeerStat.h"
- #include "Option.h"
- #include "DownloadContext.h"
- #include "Piece.h"
- #include "FileEntry.h"
- #include "wallclock.h"
- namespace aria2 {
- SegmentMan::SegmentMan(const Option* option,
- const SharedHandle<DownloadContext>& downloadContext,
- const PieceStorageHandle& pieceStorage):
- option_(option),
- logger_(LogFactory::getInstance()),
- downloadContext_(downloadContext),
- pieceStorage_(pieceStorage),
- lastPeerStatDlspdMapUpdated_(0),
- cachedDlspd_(0),
- ignoreBitfield_(downloadContext->getPieceLength(),
- downloadContext->getTotalLength())
- {
- ignoreBitfield_.enableFilter();
- }
- SegmentMan::~SegmentMan() {}
- bool SegmentMan::downloadFinished() const
- {
- if(pieceStorage_.isNull()) {
- return false;
- } else {
- return pieceStorage_->downloadFinished();
- }
- }
- void SegmentMan::init()
- {
- // TODO Do we have to do something about DownloadContext and
- // PieceStorage here?
- }
- uint64_t SegmentMan::getTotalLength() const
- {
- if(pieceStorage_.isNull()) {
- return 0;
- } else {
- return pieceStorage_->getTotalLength();
- }
- }
- void SegmentMan::setPieceStorage(const PieceStorageHandle& pieceStorage)
- {
- pieceStorage_ = pieceStorage;
- }
- void SegmentMan::setDownloadContext
- (const SharedHandle<DownloadContext>& downloadContext)
- {
- downloadContext_ = downloadContext;
- }
- SharedHandle<Segment> SegmentMan::checkoutSegment
- (cuid_t cuid, const SharedHandle<Piece>& piece)
- {
- if(piece.isNull()) {
- return SharedHandle<Segment>();
- }
- if(logger_->debug()) {
- logger_->debug("Attach segment#%lu to CUID#%s.",
- static_cast<unsigned long>(piece->getIndex()),
- util::itos(cuid).c_str());
- }
- SharedHandle<Segment> segment;
- if(piece->getLength() == 0) {
- segment.reset(new GrowSegment(piece));
- } else {
- segment.reset(new PiecedSegment(downloadContext_->getPieceLength(), piece));
- }
- SegmentEntryHandle entry(new SegmentEntry(cuid, segment));
- usedSegmentEntries_.push_back(entry);
- if(logger_->debug()) {
- logger_->debug("index=%lu, length=%lu, segmentLength=%lu,"
- " writtenLength=%lu",
- static_cast<unsigned long>(segment->getIndex()),
- static_cast<unsigned long>(segment->getLength()),
- static_cast<unsigned long>(segment->getSegmentLength()),
- static_cast<unsigned long>(segment->getWrittenLength()));
- }
- if(piece->getLength() > 0) {
- std::map<size_t, size_t>::iterator positr =
- segmentWrittenLengthMemo_.find(segment->getIndex());
- if(positr != segmentWrittenLengthMemo_.end()) {
- const size_t writtenLength = (*positr).second;
- if(logger_->debug()) {
- logger_->debug("writtenLength(in memo)=%lu, writtenLength=%lu",
- static_cast<unsigned long>(writtenLength),
- static_cast<unsigned long>(segment->getWrittenLength()));
- }
- // If the difference between cached writtenLength and segment's
- // writtenLength is less than one block, we assume that these
- // missing bytes are already downloaded.
- if(segment->getWrittenLength() < writtenLength &&
- writtenLength-segment->getWrittenLength() < piece->getBlockLength()) {
- segment->updateWrittenLength(writtenLength-segment->getWrittenLength());
- }
- }
- }
- return segment;
- }
- void SegmentMan::getInFlightSegment
- (std::vector<SharedHandle<Segment> >& segments, cuid_t cuid)
- {
- for(SegmentEntries::const_iterator itr = usedSegmentEntries_.begin(),
- eoi = usedSegmentEntries_.end(); itr != eoi; ++itr) {
- const SegmentEntryHandle& segmentEntry = *itr;
- if(segmentEntry->cuid == cuid) {
- segments.push_back(segmentEntry->segment);
- }
- }
- }
- SharedHandle<Segment> SegmentMan::getSegment(cuid_t cuid, size_t minSplitSize)
- {
- SharedHandle<Piece> piece =
- pieceStorage_->getSparseMissingUnusedPiece
- (minSplitSize,
- ignoreBitfield_.getFilterBitfield(), ignoreBitfield_.getBitfieldLength());
- return checkoutSegment(cuid, piece);
- }
- void SegmentMan::getSegment
- (std::vector<SharedHandle<Segment> >& segments,
- cuid_t cuid,
- size_t minSplitSize,
- const SharedHandle<FileEntry>& fileEntry,
- size_t maxSegments)
- {
- BitfieldMan filter(ignoreBitfield_);
- filter.enableFilter();
- filter.addNotFilter(fileEntry->getOffset(), fileEntry->getLength());
- std::vector<SharedHandle<Segment> > pending;
- while(segments.size() < maxSegments) {
- SharedHandle<Segment> segment =
- checkoutSegment(cuid,
- pieceStorage_->getSparseMissingUnusedPiece
- (minSplitSize,
- filter.getFilterBitfield(), filter.getBitfieldLength()));
- if(segment.isNull()) {
- break;
- }
- if(segment->getPositionToWrite() < fileEntry->getOffset() ||
- fileEntry->getLastOffset() <= segment->getPositionToWrite()) {
- pending.push_back(segment);
- } else {
- segments.push_back(segment);
- }
- }
- for(std::vector<SharedHandle<Segment> >::const_iterator i = pending.begin(),
- eoi = pending.end(); i != eoi; ++i) {
- cancelSegment(cuid, *i);
- }
- }
- SharedHandle<Segment> SegmentMan::getSegmentWithIndex
- (cuid_t cuid, size_t index) {
- if(index > 0 && downloadContext_->getNumPieces() <= index) {
- return SharedHandle<Segment>();
- }
- return checkoutSegment(cuid, pieceStorage_->getMissingPiece(index));
- }
- SharedHandle<Segment> SegmentMan::getCleanSegmentIfOwnerIsIdle
- (cuid_t cuid, size_t index)
- {
- if(index > 0 && downloadContext_->getNumPieces() <= index) {
- return SharedHandle<Segment>();
- }
- for(SegmentEntries::const_iterator itr = usedSegmentEntries_.begin(),
- eoi = usedSegmentEntries_.end(); itr != eoi; ++itr) {
- const SharedHandle<SegmentEntry>& segmentEntry = *itr;
- if(segmentEntry->segment->getIndex() == index) {
- if(segmentEntry->segment->getWrittenLength() > 0) {
- return SharedHandle<Segment>();
- }
- if(segmentEntry->cuid == cuid) {
- return segmentEntry->segment;
- }
- cuid_t owner = segmentEntry->cuid;
- SharedHandle<PeerStat> ps = getPeerStat(owner);
- if(ps.isNull() || (!ps.isNull() && ps->getStatus() == PeerStat::IDLE)) {
- cancelSegment(owner);
- return getSegmentWithIndex(cuid, index);
- } else {
- return SharedHandle<Segment>();
- }
- }
- }
- return SharedHandle<Segment>();
- }
- void SegmentMan::cancelSegment(const SharedHandle<Segment>& segment)
- {
- if(logger_->debug()) {
- logger_->debug("Canceling segment#%lu",
- static_cast<unsigned long>(segment->getIndex()));
- }
- pieceStorage_->cancelPiece(segment->getPiece());
- segmentWrittenLengthMemo_[segment->getIndex()] = segment->getWrittenLength();
- if(logger_->debug()) {
- logger_->debug("Memorized segment index=%lu, writtenLength=%lu",
- static_cast<unsigned long>(segment->getIndex()),
- static_cast<unsigned long>(segment->getWrittenLength()));
- }
- }
- void SegmentMan::cancelSegment(cuid_t cuid) {
- for(SegmentEntries::iterator itr = usedSegmentEntries_.begin(),
- eoi = usedSegmentEntries_.end(); itr != eoi;) {
- if((*itr)->cuid == cuid) {
- cancelSegment((*itr)->segment);
- itr = usedSegmentEntries_.erase(itr);
- eoi = usedSegmentEntries_.end();
- } else {
- ++itr;
- }
- }
- }
- void SegmentMan::cancelSegment
- (cuid_t cuid, const SharedHandle<Segment>& segment)
- {
- for(SegmentEntries::iterator itr = usedSegmentEntries_.begin(),
- eoi = usedSegmentEntries_.end(); itr != eoi;) {
- if((*itr)->cuid == cuid && *(*itr)->segment == *segment) {
- cancelSegment((*itr)->segment);
- itr = usedSegmentEntries_.erase(itr);
- //eoi = usedSegmentEntries_.end();
- break;
- } else {
- ++itr;
- }
- }
- }
- void SegmentMan::cancelAllSegments()
- {
- for(std::deque<SharedHandle<SegmentEntry> >::iterator itr =
- usedSegmentEntries_.begin(), eoi = usedSegmentEntries_.end();
- itr != eoi; ++itr) {
- cancelSegment((*itr)->segment);
- }
- usedSegmentEntries_.clear();
- }
- void SegmentMan::eraseSegmentWrittenLengthMemo()
- {
- segmentWrittenLengthMemo_.clear();
- }
- namespace {
- class FindSegmentEntry {
- private:
- SharedHandle<Segment> segment_;
- public:
- FindSegmentEntry(const SharedHandle<Segment>& segment):segment_(segment) {}
- bool operator()(const SegmentEntryHandle& segmentEntry) const
- {
- return segmentEntry->segment->getIndex() == segment_->getIndex();
- }
- };
- } // namespace
- bool SegmentMan::completeSegment
- (cuid_t cuid, const SharedHandle<Segment>& segment) {
- pieceStorage_->completePiece(segment->getPiece());
- pieceStorage_->advertisePiece(cuid, segment->getPiece()->getIndex());
- SegmentEntries::iterator itr = std::find_if(usedSegmentEntries_.begin(),
- usedSegmentEntries_.end(),
- FindSegmentEntry(segment));
- if(itr == usedSegmentEntries_.end()) {
- return false;
- } else {
- usedSegmentEntries_.erase(itr);
- return true;
- }
- }
- bool SegmentMan::hasSegment(size_t index) const {
- return pieceStorage_->hasPiece(index);
- }
- uint64_t SegmentMan::getDownloadLength() const {
- if(pieceStorage_.isNull()) {
- return 0;
- } else {
- return pieceStorage_->getCompletedLength();
- }
- }
- void SegmentMan::registerPeerStat(const SharedHandle<PeerStat>& peerStat)
- {
- for(std::vector<SharedHandle<PeerStat> >::iterator i = peerStats_.begin(),
- eoi = peerStats_.end(); i != eoi; ++i) {
- if((*i)->getStatus() == PeerStat::IDLE) {
- *i = peerStat;
- return;
- }
- }
- peerStats_.push_back(peerStat);
- }
- SharedHandle<PeerStat> SegmentMan::getPeerStat(cuid_t cuid) const
- {
- for(std::vector<SharedHandle<PeerStat> >::const_iterator i =
- peerStats_.begin(), eoi = peerStats_.end(); i != eoi; ++i) {
- if((*i)->getCuid() == cuid) {
- return *i;
- }
- }
- return SharedHandle<PeerStat>();
- }
- namespace {
- class PeerStatHostProtoEqual {
- private:
- const SharedHandle<PeerStat>& peerStat_;
- public:
- PeerStatHostProtoEqual(const SharedHandle<PeerStat>& peerStat):
- peerStat_(peerStat) {}
- bool operator()(const SharedHandle<PeerStat>& p) const
- {
- return peerStat_->getHostname() == p->getHostname() &&
- peerStat_->getProtocol() == p->getProtocol();
- }
- };
- } // namespace
- void SegmentMan::updateFastestPeerStat(const SharedHandle<PeerStat>& peerStat)
- {
- std::vector<SharedHandle<PeerStat> >::iterator i =
- std::find_if(fastestPeerStats_.begin(), fastestPeerStats_.end(),
- PeerStatHostProtoEqual(peerStat));
- if(i == fastestPeerStats_.end()) {
- fastestPeerStats_.push_back(peerStat);
- } else if((*i)->getAvgDownloadSpeed() < peerStat->getAvgDownloadSpeed()) {
- // *i's SessionDownloadLength must be added to peerStat
- peerStat->addSessionDownloadLength((*i)->getSessionDownloadLength());
- *i = peerStat;
- } else {
- // peerStat's SessionDownloadLength must be added to *i
- (*i)->addSessionDownloadLength(peerStat->getSessionDownloadLength());
- }
- }
- unsigned int SegmentMan::calculateDownloadSpeed()
- {
- unsigned int speed = 0;
- if(lastPeerStatDlspdMapUpdated_.differenceInMillis(global::wallclock) >= 250){
- lastPeerStatDlspdMapUpdated_ = global::wallclock;
- peerStatDlspdMap_.clear();
- for(std::vector<SharedHandle<PeerStat> >::const_iterator i =
- peerStats_.begin(), eoi = peerStats_.end(); i != eoi; ++i) {
- if((*i)->getStatus() == PeerStat::ACTIVE) {
- unsigned int s = (*i)->calculateDownloadSpeed();
- peerStatDlspdMap_[(*i)->getCuid()] = s;
- speed += s;
- }
- }
- cachedDlspd_ = speed;
- } else {
- speed = cachedDlspd_;
- }
- return speed;
- }
- void SegmentMan::updateDownloadSpeedFor(const SharedHandle<PeerStat>& pstat)
- {
- unsigned int newspd = pstat->calculateDownloadSpeed();
- unsigned int oldSpd = peerStatDlspdMap_[pstat->getCuid()];
- if(cachedDlspd_ > oldSpd) {
- cachedDlspd_ -= oldSpd;
- cachedDlspd_ += newspd;
- } else {
- cachedDlspd_ = newspd;
- }
- peerStatDlspdMap_[pstat->getCuid()] = newspd;
- }
- namespace {
- class PeerStatDownloadLengthOperator {
- public:
- uint64_t operator()(uint64_t total, const SharedHandle<PeerStat>& ps)
- {
- return ps->getSessionDownloadLength()+total;
- }
- };
- } // namespace
- uint64_t SegmentMan::calculateSessionDownloadLength() const
- {
- return std::accumulate(fastestPeerStats_.begin(), fastestPeerStats_.end(),
- 0LL, PeerStatDownloadLengthOperator());
- }
- size_t SegmentMan::countFreePieceFrom(size_t index) const
- {
- size_t numPieces = downloadContext_->getNumPieces();
- for(size_t i = index; i < numPieces; ++i) {
- if(pieceStorage_->hasPiece(i) || pieceStorage_->isPieceUsed(i)) {
- return i-index;
- }
- }
- return downloadContext_->getNumPieces()-index;
- }
- void SegmentMan::ignoreSegmentFor(const SharedHandle<FileEntry>& fileEntry)
- {
- if(logger_->debug()) {
- logger_->debug("ignoring segment for path=%s, offset=%s, length=%s",
- fileEntry->getPath().c_str(),
- util::itos(fileEntry->getOffset()).c_str(),
- util::uitos(fileEntry->getLength()).c_str());
- }
- ignoreBitfield_.addFilter(fileEntry->getOffset(), fileEntry->getLength());
- }
- void SegmentMan::recognizeSegmentFor(const SharedHandle<FileEntry>& fileEntry)
- {
- ignoreBitfield_.removeFilter(fileEntry->getOffset(), fileEntry->getLength());
- }
- bool SegmentMan::allSegmentsIgnored() const
- {
- return ignoreBitfield_.isAllFilterBitSet();
- }
- } // namespace aria2
|