SegmentMan.cc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  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. #include "wallclock.h"
  53. namespace aria2 {
  54. SegmentEntry::SegmentEntry(cuid_t cuid, const SharedHandle<Segment>& segment):
  55. cuid(cuid), segment(segment) {}
  56. SegmentEntry::~SegmentEntry() {}
  57. SegmentMan::SegmentMan(const Option* option,
  58. const SharedHandle<DownloadContext>& downloadContext,
  59. const PieceStorageHandle& pieceStorage):
  60. _option(option),
  61. logger(LogFactory::getInstance()),
  62. _downloadContext(downloadContext),
  63. _pieceStorage(pieceStorage),
  64. _lastPeerStatDlspdMapUpdated(0),
  65. _cachedDlspd(0),
  66. _ignoreBitfield(downloadContext->getPieceLength(),
  67. downloadContext->getTotalLength())
  68. {
  69. _ignoreBitfield.enableFilter();
  70. }
  71. SegmentMan::~SegmentMan() {}
  72. bool SegmentMan::downloadFinished() const
  73. {
  74. if(_pieceStorage.isNull()) {
  75. return false;
  76. } else {
  77. return _pieceStorage->downloadFinished();
  78. }
  79. }
  80. void SegmentMan::init()
  81. {
  82. // TODO Do we have to do something about DownloadContext and PieceStorage here?
  83. }
  84. uint64_t SegmentMan::getTotalLength() const
  85. {
  86. if(_pieceStorage.isNull()) {
  87. return 0;
  88. } else {
  89. return _pieceStorage->getTotalLength();
  90. }
  91. }
  92. void SegmentMan::setPieceStorage(const PieceStorageHandle& pieceStorage)
  93. {
  94. _pieceStorage = pieceStorage;
  95. }
  96. void SegmentMan::setDownloadContext
  97. (const SharedHandle<DownloadContext>& downloadContext)
  98. {
  99. _downloadContext = downloadContext;
  100. }
  101. SharedHandle<Segment> SegmentMan::checkoutSegment
  102. (cuid_t cuid, const SharedHandle<Piece>& piece)
  103. {
  104. if(piece.isNull()) {
  105. return SharedHandle<Segment>();
  106. }
  107. if(logger->debug()) {
  108. logger->debug("Attach segment#%d to CUID#%s.",
  109. piece->getIndex(), util::itos(cuid).c_str());
  110. }
  111. SharedHandle<Segment> segment;
  112. if(piece->getLength() == 0) {
  113. segment.reset(new GrowSegment(piece));
  114. } else {
  115. segment.reset(new PiecedSegment(_downloadContext->getPieceLength(), piece));
  116. }
  117. SegmentEntryHandle entry(new SegmentEntry(cuid, segment));
  118. usedSegmentEntries.push_back(entry);
  119. if(logger->debug()) {
  120. logger->debug("index=%d, length=%d, segmentLength=%d, writtenLength=%d",
  121. segment->getIndex(),
  122. segment->getLength(),
  123. segment->getSegmentLength(),
  124. segment->getWrittenLength());
  125. }
  126. if(piece->getLength() > 0) {
  127. std::map<size_t, size_t>::iterator positr =
  128. _segmentWrittenLengthMemo.find(segment->getIndex());
  129. if(positr != _segmentWrittenLengthMemo.end()) {
  130. const size_t writtenLength = (*positr).second;
  131. if(logger->debug()) {
  132. logger->debug("writtenLength(in memo)=%d, writtenLength=%d",
  133. writtenLength, segment->getWrittenLength());
  134. }
  135. // If the difference between cached writtenLength and segment's
  136. // writtenLength is less than one block, we assume that these
  137. // missing bytes are already downloaded.
  138. if(segment->getWrittenLength() < writtenLength &&
  139. writtenLength-segment->getWrittenLength() < piece->getBlockLength()) {
  140. segment->updateWrittenLength(writtenLength-segment->getWrittenLength());
  141. }
  142. }
  143. }
  144. return segment;
  145. }
  146. void SegmentMan::getInFlightSegment
  147. (std::vector<SharedHandle<Segment> >& segments, cuid_t cuid)
  148. {
  149. for(SegmentEntries::const_iterator itr = usedSegmentEntries.begin(),
  150. eoi = usedSegmentEntries.end(); itr != eoi; ++itr) {
  151. const SegmentEntryHandle& segmentEntry = *itr;
  152. if(segmentEntry->cuid == cuid) {
  153. segments.push_back(segmentEntry->segment);
  154. }
  155. }
  156. }
  157. SharedHandle<Segment> SegmentMan::getSegment(cuid_t cuid) {
  158. SharedHandle<Piece> piece =
  159. _pieceStorage->getSparseMissingUnusedPiece
  160. (_ignoreBitfield.getFilterBitfield(),_ignoreBitfield.getBitfieldLength());
  161. return checkoutSegment(cuid, piece);
  162. }
  163. void SegmentMan::getSegment
  164. (std::vector<SharedHandle<Segment> >& segments,
  165. cuid_t cuid,
  166. const SharedHandle<FileEntry>& fileEntry,
  167. size_t maxSegments)
  168. {
  169. BitfieldMan filter(_ignoreBitfield);
  170. filter.enableFilter();
  171. filter.addNotFilter(fileEntry->getOffset(), fileEntry->getLength());
  172. std::vector<SharedHandle<Segment> > pending;
  173. while(segments.size() < maxSegments) {
  174. SharedHandle<Segment> segment =
  175. checkoutSegment(cuid,
  176. _pieceStorage->getSparseMissingUnusedPiece
  177. (filter.getFilterBitfield(), filter.getBitfieldLength()));
  178. if(segment.isNull()) {
  179. break;
  180. }
  181. if(segment->getPositionToWrite() < fileEntry->getOffset() ||
  182. fileEntry->getLastOffset() <= segment->getPositionToWrite()) {
  183. pending.push_back(segment);
  184. } else {
  185. segments.push_back(segment);
  186. }
  187. }
  188. for(std::vector<SharedHandle<Segment> >::const_iterator i = pending.begin(),
  189. eoi = pending.end(); i != eoi; ++i) {
  190. cancelSegment(cuid, *i);
  191. }
  192. }
  193. SharedHandle<Segment> SegmentMan::getSegment(cuid_t cuid, size_t index) {
  194. if(index > 0 && _downloadContext->getNumPieces() <= index) {
  195. return SharedHandle<Segment>();
  196. }
  197. return checkoutSegment(cuid, _pieceStorage->getMissingPiece(index));
  198. }
  199. SharedHandle<Segment> SegmentMan::getCleanSegmentIfOwnerIsIdle
  200. (cuid_t cuid, size_t index)
  201. {
  202. if(index > 0 && _downloadContext->getNumPieces() <= index) {
  203. return SharedHandle<Segment>();
  204. }
  205. for(SegmentEntries::const_iterator itr = usedSegmentEntries.begin(),
  206. eoi = usedSegmentEntries.end(); itr != eoi; ++itr) {
  207. const SharedHandle<SegmentEntry>& segmentEntry = *itr;
  208. if(segmentEntry->segment->getIndex() == index) {
  209. if(segmentEntry->cuid == cuid) {
  210. return segmentEntry->segment;
  211. }
  212. if(segmentEntry->segment->getWrittenLength() > 0) {
  213. return SharedHandle<Segment>();
  214. }
  215. cuid_t owner = segmentEntry->cuid;
  216. SharedHandle<PeerStat> ps = getPeerStat(owner);
  217. if(ps.isNull() || (!ps.isNull() && ps->getStatus() == PeerStat::IDLE)) {
  218. cancelSegment(owner);
  219. return getSegment(cuid, index);
  220. } else {
  221. return SharedHandle<Segment>();
  222. }
  223. }
  224. }
  225. return checkoutSegment(cuid, _pieceStorage->getMissingPiece(index));
  226. }
  227. void SegmentMan::cancelSegment(const SharedHandle<Segment>& segment)
  228. {
  229. if(logger->debug()) {
  230. logger->debug("Canceling segment#%d", segment->getIndex());
  231. }
  232. _pieceStorage->cancelPiece(segment->getPiece());
  233. _segmentWrittenLengthMemo[segment->getIndex()] = segment->getWrittenLength();
  234. if(logger->debug()) {
  235. logger->debug("Memorized segment index=%u, writtenLength=%u",
  236. segment->getIndex(), segment->getWrittenLength());
  237. }
  238. }
  239. void SegmentMan::cancelSegment(cuid_t cuid) {
  240. for(SegmentEntries::iterator itr = usedSegmentEntries.begin(),
  241. eoi = usedSegmentEntries.end(); itr != eoi;) {
  242. if((*itr)->cuid == cuid) {
  243. cancelSegment((*itr)->segment);
  244. itr = usedSegmentEntries.erase(itr);
  245. eoi = usedSegmentEntries.end();
  246. } else {
  247. ++itr;
  248. }
  249. }
  250. }
  251. void SegmentMan::cancelSegment
  252. (cuid_t cuid, const SharedHandle<Segment>& segment)
  253. {
  254. for(SegmentEntries::iterator itr = usedSegmentEntries.begin(),
  255. eoi = usedSegmentEntries.end(); itr != eoi;) {
  256. if((*itr)->cuid == cuid && (*itr)->segment == segment) {
  257. cancelSegment((*itr)->segment);
  258. itr = usedSegmentEntries.erase(itr);
  259. //eoi = usedSegmentEntries.end();
  260. break;
  261. } else {
  262. ++itr;
  263. }
  264. }
  265. }
  266. void SegmentMan::cancelAllSegments()
  267. {
  268. for(std::deque<SharedHandle<SegmentEntry> >::iterator itr =
  269. usedSegmentEntries.begin(), eoi = usedSegmentEntries.end();
  270. itr != eoi; ++itr) {
  271. cancelSegment((*itr)->segment);
  272. }
  273. usedSegmentEntries.clear();
  274. }
  275. void SegmentMan::eraseSegmentWrittenLengthMemo()
  276. {
  277. _segmentWrittenLengthMemo.clear();
  278. }
  279. class FindSegmentEntry {
  280. private:
  281. SharedHandle<Segment> _segment;
  282. public:
  283. FindSegmentEntry(const SharedHandle<Segment>& segment):_segment(segment) {}
  284. bool operator()(const SegmentEntryHandle& segmentEntry) const
  285. {
  286. return segmentEntry->segment->getIndex() == _segment->getIndex();
  287. }
  288. };
  289. bool SegmentMan::completeSegment
  290. (cuid_t cuid, const SharedHandle<Segment>& segment) {
  291. _pieceStorage->completePiece(segment->getPiece());
  292. _pieceStorage->advertisePiece(cuid, segment->getPiece()->getIndex());
  293. SegmentEntries::iterator itr = std::find_if(usedSegmentEntries.begin(),
  294. usedSegmentEntries.end(),
  295. FindSegmentEntry(segment));
  296. if(itr == usedSegmentEntries.end()) {
  297. return false;
  298. } else {
  299. usedSegmentEntries.erase(itr);
  300. return true;
  301. }
  302. }
  303. bool SegmentMan::hasSegment(size_t index) const {
  304. return _pieceStorage->hasPiece(index);
  305. }
  306. uint64_t SegmentMan::getDownloadLength() const {
  307. if(_pieceStorage.isNull()) {
  308. return 0;
  309. } else {
  310. return _pieceStorage->getCompletedLength();
  311. }
  312. }
  313. void SegmentMan::registerPeerStat(const SharedHandle<PeerStat>& peerStat)
  314. {
  315. for(std::vector<SharedHandle<PeerStat> >::iterator i = peerStats.begin(),
  316. eoi = peerStats.end(); i != eoi; ++i) {
  317. if((*i)->getStatus() == PeerStat::IDLE) {
  318. *i = peerStat;
  319. return;
  320. }
  321. }
  322. peerStats.push_back(peerStat);
  323. }
  324. SharedHandle<PeerStat> SegmentMan::getPeerStat(cuid_t cuid) const
  325. {
  326. for(std::vector<SharedHandle<PeerStat> >::const_iterator i =
  327. peerStats.begin(), eoi = peerStats.end(); i != eoi; ++i) {
  328. if((*i)->getCuid() == cuid) {
  329. return *i;
  330. }
  331. }
  332. return SharedHandle<PeerStat>();
  333. }
  334. class PeerStatHostProtoEqual {
  335. private:
  336. const SharedHandle<PeerStat>& _peerStat;
  337. public:
  338. PeerStatHostProtoEqual(const SharedHandle<PeerStat>& peerStat):
  339. _peerStat(peerStat) {}
  340. bool operator()(const SharedHandle<PeerStat>& p) const
  341. {
  342. return _peerStat->getHostname() == p->getHostname() &&
  343. _peerStat->getProtocol() == p->getProtocol();
  344. }
  345. };
  346. void SegmentMan::updateFastestPeerStat(const SharedHandle<PeerStat>& peerStat)
  347. {
  348. std::vector<SharedHandle<PeerStat> >::iterator i =
  349. std::find_if(_fastestPeerStats.begin(), _fastestPeerStats.end(),
  350. PeerStatHostProtoEqual(peerStat));
  351. if(i == _fastestPeerStats.end()) {
  352. _fastestPeerStats.push_back(peerStat);
  353. } else if((*i)->getAvgDownloadSpeed() < peerStat->getAvgDownloadSpeed()) {
  354. // *i's SessionDownloadLength must be added to peerStat
  355. peerStat->addSessionDownloadLength((*i)->getSessionDownloadLength());
  356. *i = peerStat;
  357. } else {
  358. // peerStat's SessionDownloadLength must be added to *i
  359. (*i)->addSessionDownloadLength(peerStat->getSessionDownloadLength());
  360. }
  361. }
  362. unsigned int SegmentMan::calculateDownloadSpeed()
  363. {
  364. unsigned int speed = 0;
  365. if(_lastPeerStatDlspdMapUpdated.differenceInMillis(global::wallclock) >= 250){
  366. _lastPeerStatDlspdMapUpdated = global::wallclock;
  367. _peerStatDlspdMap.clear();
  368. for(std::vector<SharedHandle<PeerStat> >::const_iterator i =
  369. peerStats.begin(), eoi = peerStats.end(); i != eoi; ++i) {
  370. if((*i)->getStatus() == PeerStat::ACTIVE) {
  371. unsigned int s = (*i)->calculateDownloadSpeed();
  372. _peerStatDlspdMap[(*i)->getCuid()] = s;
  373. speed += s;
  374. }
  375. }
  376. _cachedDlspd = speed;
  377. } else {
  378. speed = _cachedDlspd;
  379. }
  380. return speed;
  381. }
  382. void SegmentMan::updateDownloadSpeedFor(const SharedHandle<PeerStat>& pstat)
  383. {
  384. unsigned int newspd = pstat->calculateDownloadSpeed();
  385. unsigned int oldSpd = _peerStatDlspdMap[pstat->getCuid()];
  386. if(_cachedDlspd > oldSpd) {
  387. _cachedDlspd -= oldSpd;
  388. _cachedDlspd += newspd;
  389. } else {
  390. _cachedDlspd = newspd;
  391. }
  392. _peerStatDlspdMap[pstat->getCuid()] = newspd;
  393. }
  394. class PeerStatDownloadLengthOperator {
  395. public:
  396. uint64_t operator()(uint64_t total, const SharedHandle<PeerStat>& ps)
  397. {
  398. return ps->getSessionDownloadLength()+total;
  399. }
  400. };
  401. uint64_t SegmentMan::calculateSessionDownloadLength() const
  402. {
  403. return std::accumulate(_fastestPeerStats.begin(), _fastestPeerStats.end(),
  404. 0LL, PeerStatDownloadLengthOperator());
  405. }
  406. size_t SegmentMan::countFreePieceFrom(size_t index) const
  407. {
  408. size_t numPieces = _downloadContext->getNumPieces();
  409. for(size_t i = index; i < numPieces; ++i) {
  410. if(_pieceStorage->hasPiece(i) || _pieceStorage->isPieceUsed(i)) {
  411. return i-index;
  412. }
  413. }
  414. return _downloadContext->getNumPieces()-index;
  415. }
  416. void SegmentMan::ignoreSegmentFor(const SharedHandle<FileEntry>& fileEntry)
  417. {
  418. if(logger->debug()) {
  419. logger->debug("ignoring segment for path=%s, offset=%s, length=%s",
  420. fileEntry->getPath().c_str(),
  421. util::itos(fileEntry->getOffset()).c_str(),
  422. util::uitos(fileEntry->getLength()).c_str());
  423. }
  424. _ignoreBitfield.addFilter(fileEntry->getOffset(), fileEntry->getLength());
  425. }
  426. void SegmentMan::recognizeSegmentFor(const SharedHandle<FileEntry>& fileEntry)
  427. {
  428. _ignoreBitfield.removeFilter(fileEntry->getOffset(), fileEntry->getLength());
  429. }
  430. bool SegmentMan::allSegmentsIgnored() const
  431. {
  432. return _ignoreBitfield.isAllFilterBitSet();
  433. }
  434. } // namespace aria2