SegmentMan.cc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. /* <!-- copyright */
  2. /*
  3. * aria2 - The high speed download utility
  4. *
  5. * Copyright (C) 2006 Tatsuhiro Tsujikawa
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. *
  21. * In addition, as a special exception, the copyright holders give
  22. * permission to link the code of portions of this program with the
  23. * OpenSSL library under certain conditions as described in each
  24. * individual source file, and distribute linked combinations
  25. * including the two.
  26. * You must obey the GNU General Public License in all respects
  27. * for all of the code used other than OpenSSL. If you modify
  28. * file(s) with this exception, you may extend this exception to your
  29. * version of the file(s), but you are not obligated to do so. If you
  30. * do not wish to do so, delete this exception statement from your
  31. * version. If you delete this exception statement from all source
  32. * files in the program, then also delete it here.
  33. */
  34. /* copyright --> */
  35. #include "SegmentMan.h"
  36. #include <cassert>
  37. #include <algorithm>
  38. #include <numeric>
  39. #include "util.h"
  40. #include "message.h"
  41. #include "prefs.h"
  42. #include "PiecedSegment.h"
  43. #include "GrowSegment.h"
  44. #include "LogFactory.h"
  45. #include "Logger.h"
  46. #include "PieceStorage.h"
  47. #include "PeerStat.h"
  48. #include "Option.h"
  49. #include "DownloadContext.h"
  50. #include "Piece.h"
  51. #include "FileEntry.h"
  52. namespace aria2 {
  53. SegmentEntry::SegmentEntry(cuid_t cuid, const SegmentHandle& segment):
  54. cuid(cuid), segment(segment) {}
  55. SegmentEntry::~SegmentEntry() {}
  56. SegmentMan::SegmentMan(const Option* option,
  57. const SharedHandle<DownloadContext>& downloadContext,
  58. const PieceStorageHandle& pieceStorage):
  59. _option(option),
  60. logger(LogFactory::getInstance()),
  61. _downloadContext(downloadContext),
  62. _pieceStorage(pieceStorage),
  63. _lastPeerStatDlspdMapUpdated(0),
  64. _cachedDlspd(0),
  65. _ignoreBitfield(downloadContext->getPieceLength(),
  66. downloadContext->getTotalLength())
  67. {
  68. _ignoreBitfield.enableFilter();
  69. }
  70. SegmentMan::~SegmentMan() {}
  71. bool SegmentMan::downloadFinished() const
  72. {
  73. if(_pieceStorage.isNull()) {
  74. return false;
  75. } else {
  76. return _pieceStorage->downloadFinished();
  77. }
  78. }
  79. void SegmentMan::init()
  80. {
  81. // TODO Do we have to do something about DownloadContext and PieceStorage here?
  82. }
  83. uint64_t SegmentMan::getTotalLength() const
  84. {
  85. if(_pieceStorage.isNull()) {
  86. return 0;
  87. } else {
  88. return _pieceStorage->getTotalLength();
  89. }
  90. }
  91. void SegmentMan::setPieceStorage(const PieceStorageHandle& pieceStorage)
  92. {
  93. _pieceStorage = pieceStorage;
  94. }
  95. void SegmentMan::setDownloadContext
  96. (const SharedHandle<DownloadContext>& downloadContext)
  97. {
  98. _downloadContext = downloadContext;
  99. }
  100. SegmentHandle SegmentMan::checkoutSegment(cuid_t cuid,
  101. const PieceHandle& piece)
  102. {
  103. if(piece.isNull()) {
  104. return SharedHandle<Segment>();
  105. }
  106. logger->debug("Attach segment#%d to CUID#%d.", piece->getIndex(), cuid);
  107. SegmentHandle segment;
  108. if(piece->getLength() == 0) {
  109. segment.reset(new GrowSegment(piece));
  110. } else {
  111. segment.reset(new PiecedSegment(_downloadContext->getPieceLength(), piece));
  112. }
  113. SegmentEntryHandle entry(new SegmentEntry(cuid, segment));
  114. usedSegmentEntries.push_back(entry);
  115. logger->debug("index=%d, length=%d, segmentLength=%d, writtenLength=%d",
  116. segment->getIndex(),
  117. segment->getLength(),
  118. segment->getSegmentLength(),
  119. segment->getWrittenLength());
  120. if(piece->getLength() > 0) {
  121. std::map<size_t, size_t>::iterator positr =
  122. _segmentWrittenLengthMemo.find(segment->getIndex());
  123. if(positr != _segmentWrittenLengthMemo.end()) {
  124. const size_t writtenLength = (*positr).second;
  125. logger->debug("writtenLength(in memo)=%d, writtenLength=%d",
  126. writtenLength, segment->getWrittenLength());
  127. // If the difference between cached writtenLength and segment's
  128. // writtenLength is less than one block, we assume that these
  129. // missing bytes are already downloaded.
  130. if(segment->getWrittenLength() < writtenLength &&
  131. writtenLength-segment->getWrittenLength() < piece->getBlockLength()) {
  132. segment->updateWrittenLength(writtenLength-segment->getWrittenLength());
  133. }
  134. }
  135. }
  136. return segment;
  137. }
  138. void SegmentMan::getInFlightSegment(std::deque<SharedHandle<Segment> >& segments,
  139. cuid_t cuid)
  140. {
  141. for(SegmentEntries::iterator itr = usedSegmentEntries.begin();
  142. itr != usedSegmentEntries.end(); ++itr) {
  143. const SegmentEntryHandle& segmentEntry = *itr;
  144. if(segmentEntry->cuid == cuid) {
  145. segments.push_back(segmentEntry->segment);
  146. }
  147. }
  148. }
  149. SegmentHandle SegmentMan::getSegment(cuid_t cuid) {
  150. PieceHandle piece =
  151. _pieceStorage->getSparseMissingUnusedPiece
  152. (_ignoreBitfield.getFilterBitfield(),_ignoreBitfield.getBitfieldLength());
  153. return checkoutSegment(cuid, piece);
  154. }
  155. void SegmentMan::getSegment(std::deque<SharedHandle<Segment> >& segments,
  156. cuid_t cuid,
  157. const SharedHandle<FileEntry>& fileEntry,
  158. size_t maxSegments)
  159. {
  160. BitfieldMan filter(_ignoreBitfield);
  161. filter.enableFilter();
  162. filter.addNotFilter(fileEntry->getOffset(), fileEntry->getLength());
  163. std::deque<SharedHandle<Segment> > pending;
  164. while(segments.size() < maxSegments) {
  165. SharedHandle<Segment> segment =
  166. checkoutSegment(cuid,
  167. _pieceStorage->getSparseMissingUnusedPiece
  168. (filter.getFilterBitfield(), filter.getBitfieldLength()));
  169. if(segment.isNull()) {
  170. break;
  171. }
  172. if(segment->getPositionToWrite() < fileEntry->getOffset() ||
  173. fileEntry->getLastOffset() <= segment->getPositionToWrite()) {
  174. pending.push_back(segment);
  175. } else {
  176. segments.push_back(segment);
  177. }
  178. }
  179. for(std::deque<SharedHandle<Segment> >::const_iterator i = pending.begin();
  180. i != pending.end(); ++i) {
  181. cancelSegment(cuid, *i);
  182. }
  183. }
  184. SegmentHandle SegmentMan::getSegment(cuid_t cuid, size_t index) {
  185. if(_downloadContext->getNumPieces() <= index) {
  186. return SharedHandle<Segment>();
  187. }
  188. return checkoutSegment(cuid, _pieceStorage->getMissingPiece(index));
  189. }
  190. void SegmentMan::cancelSegment(const SharedHandle<Segment>& segment)
  191. {
  192. _pieceStorage->cancelPiece(segment->getPiece());
  193. _segmentWrittenLengthMemo[segment->getIndex()] = segment->getWrittenLength();
  194. logger->debug("Memorized segment index=%u, writtenLength=%u",
  195. segment->getIndex(), segment->getWrittenLength());
  196. }
  197. void SegmentMan::cancelSegment(cuid_t cuid) {
  198. for(SegmentEntries::iterator itr = usedSegmentEntries.begin();
  199. itr != usedSegmentEntries.end();) {
  200. if((*itr)->cuid == cuid) {
  201. cancelSegment((*itr)->segment);
  202. itr = usedSegmentEntries.erase(itr);
  203. } else {
  204. ++itr;
  205. }
  206. }
  207. }
  208. void SegmentMan::cancelSegment
  209. (cuid_t cuid, const SharedHandle<Segment>& segment)
  210. {
  211. for(SegmentEntries::iterator itr = usedSegmentEntries.begin();
  212. itr != usedSegmentEntries.end();) {
  213. if((*itr)->cuid == cuid && (*itr)->segment == segment) {
  214. cancelSegment((*itr)->segment);
  215. itr = usedSegmentEntries.erase(itr);
  216. break;
  217. } else {
  218. ++itr;
  219. }
  220. }
  221. }
  222. class FindSegmentEntry {
  223. private:
  224. SegmentHandle _segment;
  225. public:
  226. FindSegmentEntry(const SegmentHandle& segment):_segment(segment) {}
  227. bool operator()(const SegmentEntryHandle& segmentEntry) const
  228. {
  229. return segmentEntry->segment->getIndex() == _segment->getIndex();
  230. }
  231. };
  232. bool SegmentMan::completeSegment(cuid_t cuid, const SegmentHandle& segment) {
  233. _pieceStorage->completePiece(segment->getPiece());
  234. _pieceStorage->advertisePiece(cuid, segment->getPiece()->getIndex());
  235. SegmentEntries::iterator itr = std::find_if(usedSegmentEntries.begin(),
  236. usedSegmentEntries.end(),
  237. FindSegmentEntry(segment));
  238. if(itr == usedSegmentEntries.end()) {
  239. return false;
  240. } else {
  241. usedSegmentEntries.erase(itr);
  242. return true;
  243. }
  244. }
  245. bool SegmentMan::hasSegment(size_t index) const {
  246. return _pieceStorage->hasPiece(index);
  247. }
  248. uint64_t SegmentMan::getDownloadLength() const {
  249. if(_pieceStorage.isNull()) {
  250. return 0;
  251. } else {
  252. return _pieceStorage->getCompletedLength();
  253. }
  254. }
  255. void SegmentMan::registerPeerStat(const SharedHandle<PeerStat>& peerStat)
  256. {
  257. for(std::deque<SharedHandle<PeerStat> >::iterator i = peerStats.begin();
  258. i != peerStats.end(); ++i) {
  259. if((*i)->getStatus() == PeerStat::IDLE) {
  260. *i = peerStat;
  261. return;
  262. }
  263. }
  264. peerStats.push_back(peerStat);
  265. }
  266. class PeerStatHostProtoEqual {
  267. private:
  268. const SharedHandle<PeerStat>& _peerStat;
  269. public:
  270. PeerStatHostProtoEqual(const SharedHandle<PeerStat>& peerStat):
  271. _peerStat(peerStat) {}
  272. bool operator()(const SharedHandle<PeerStat>& p) const
  273. {
  274. return _peerStat->getHostname() == p->getHostname() &&
  275. _peerStat->getProtocol() == p->getProtocol();
  276. }
  277. };
  278. void SegmentMan::updateFastestPeerStat(const SharedHandle<PeerStat>& peerStat)
  279. {
  280. std::deque<SharedHandle<PeerStat> >::iterator i =
  281. std::find_if(_fastestPeerStats.begin(), _fastestPeerStats.end(),
  282. PeerStatHostProtoEqual(peerStat));
  283. if(i == _fastestPeerStats.end()) {
  284. _fastestPeerStats.push_back(peerStat);
  285. } else if((*i)->getAvgDownloadSpeed() < peerStat->getAvgDownloadSpeed()) {
  286. // *i's SessionDownloadLength must be added to peerStat
  287. peerStat->addSessionDownloadLength((*i)->getSessionDownloadLength());
  288. *i = peerStat;
  289. } else {
  290. // peerStat's SessionDownloadLength must be added to *i
  291. (*i)->addSessionDownloadLength(peerStat->getSessionDownloadLength());
  292. }
  293. }
  294. unsigned int SegmentMan::calculateDownloadSpeed()
  295. {
  296. unsigned int speed = 0;
  297. if(_lastPeerStatDlspdMapUpdated.elapsedInMillis(250)) {
  298. _lastPeerStatDlspdMapUpdated.reset();
  299. _peerStatDlspdMap.clear();
  300. for(std::deque<SharedHandle<PeerStat> >::const_iterator i =
  301. peerStats.begin(); i != peerStats.end(); ++i) {
  302. if((*i)->getStatus() == PeerStat::ACTIVE) {
  303. unsigned int s = (*i)->calculateDownloadSpeed();
  304. _peerStatDlspdMap[(*i)->getCuid()] = s;
  305. speed += s;
  306. }
  307. }
  308. _cachedDlspd = speed;
  309. } else {
  310. speed = _cachedDlspd;
  311. }
  312. return speed;
  313. }
  314. void SegmentMan::updateDownloadSpeedFor(const SharedHandle<PeerStat>& pstat)
  315. {
  316. unsigned int newspd = pstat->calculateDownloadSpeed();
  317. unsigned int oldSpd = _peerStatDlspdMap[pstat->getCuid()];
  318. if(_cachedDlspd > oldSpd) {
  319. _cachedDlspd -= oldSpd;
  320. _cachedDlspd += newspd;
  321. } else {
  322. _cachedDlspd = newspd;
  323. }
  324. _peerStatDlspdMap[pstat->getCuid()] = newspd;
  325. }
  326. class PeerStatDownloadLengthOperator {
  327. public:
  328. uint64_t operator()(uint64_t total, const SharedHandle<PeerStat>& ps)
  329. {
  330. return ps->getSessionDownloadLength()+total;
  331. }
  332. };
  333. uint64_t SegmentMan::calculateSessionDownloadLength() const
  334. {
  335. return std::accumulate(_fastestPeerStats.begin(), _fastestPeerStats.end(),
  336. 0LL, PeerStatDownloadLengthOperator());
  337. }
  338. size_t SegmentMan::countFreePieceFrom(size_t index) const
  339. {
  340. size_t numPieces = _downloadContext->getNumPieces();
  341. for(size_t i = index; i < numPieces; ++i) {
  342. if(_pieceStorage->hasPiece(i) || _pieceStorage->isPieceUsed(i)) {
  343. return i-index;
  344. }
  345. }
  346. return _downloadContext->getNumPieces()-index;
  347. }
  348. void SegmentMan::ignoreSegmentFor(const SharedHandle<FileEntry>& fileEntry)
  349. {
  350. _ignoreBitfield.addFilter(fileEntry->getOffset(), fileEntry->getLength());
  351. }
  352. void SegmentMan::recognizeSegmentFor(const SharedHandle<FileEntry>& fileEntry)
  353. {
  354. _ignoreBitfield.removeFilter(fileEntry->getOffset(), fileEntry->getLength());
  355. }
  356. bool SegmentMan::allSegmentsIgnored() const
  357. {
  358. return _ignoreBitfield.isAllFilterBitSet();
  359. }
  360. } // namespace aria2