DefaultPieceStorage.cc 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812
  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 "DefaultPieceStorage.h"
  36. #include <numeric>
  37. #include <algorithm>
  38. #include "DownloadContext.h"
  39. #include "Piece.h"
  40. #include "Peer.h"
  41. #include "LogFactory.h"
  42. #include "Logger.h"
  43. #include "prefs.h"
  44. #include "DirectDiskAdaptor.h"
  45. #include "MultiDiskAdaptor.h"
  46. #include "DiskWriter.h"
  47. #include "BitfieldMan.h"
  48. #include "message.h"
  49. #include "DefaultDiskWriterFactory.h"
  50. #include "FileEntry.h"
  51. #include "DlAbortEx.h"
  52. #include "util.h"
  53. #include "a2functional.h"
  54. #include "Option.h"
  55. #include "fmt.h"
  56. #include "RarestPieceSelector.h"
  57. #include "DefaultStreamPieceSelector.h"
  58. #include "InorderStreamPieceSelector.h"
  59. #include "array_fun.h"
  60. #include "PieceStatMan.h"
  61. #include "wallclock.h"
  62. #include "bitfield.h"
  63. #ifdef ENABLE_BITTORRENT
  64. # include "bittorrent_helper.h"
  65. #endif // ENABLE_BITTORRENT
  66. namespace aria2 {
  67. DefaultPieceStorage::DefaultPieceStorage
  68. (const SharedHandle<DownloadContext>& downloadContext, const Option* option)
  69. : downloadContext_(downloadContext),
  70. bitfieldMan_(new BitfieldMan(downloadContext->getPieceLength(),
  71. downloadContext->getTotalLength())),
  72. diskWriterFactory_(new DefaultDiskWriterFactory()),
  73. endGame_(false),
  74. endGamePieceNum_(END_GAME_PIECE_NUM),
  75. option_(option),
  76. pieceStatMan_(new PieceStatMan(downloadContext->getNumPieces(), true)),
  77. pieceSelector_(new RarestPieceSelector(pieceStatMan_))
  78. {
  79. const std::string& pieceSelectorOpt =
  80. option_->get(PREF_STREAM_PIECE_SELECTOR);
  81. if(pieceSelectorOpt.empty() || pieceSelectorOpt == A2_V_DEFAULT) {
  82. streamPieceSelector_ = SharedHandle<StreamPieceSelector>
  83. (new DefaultStreamPieceSelector(bitfieldMan_));
  84. } else if(pieceSelectorOpt == V_INORDER) {
  85. streamPieceSelector_ = SharedHandle<StreamPieceSelector>
  86. (new InorderStreamPieceSelector(bitfieldMan_));
  87. }
  88. }
  89. DefaultPieceStorage::~DefaultPieceStorage()
  90. {
  91. delete bitfieldMan_;
  92. }
  93. SharedHandle<Piece> DefaultPieceStorage::checkOutPiece
  94. (size_t index, cuid_t cuid)
  95. {
  96. bitfieldMan_->setUseBit(index);
  97. SharedHandle<Piece> piece = findUsedPiece(index);
  98. if(!piece) {
  99. piece.reset(new Piece(index, bitfieldMan_->getBlockLength(index)));
  100. #ifdef ENABLE_MESSAGE_DIGEST
  101. piece->setHashType(downloadContext_->getPieceHashType());
  102. #endif // ENABLE_MESSAGE_DIGEST
  103. addUsedPiece(piece);
  104. }
  105. piece->addUser(cuid);
  106. return piece;
  107. }
  108. /**
  109. * Newly instantiated piece is not added to usedPieces.
  110. * Because it is waste of memory and there is no chance to use them later.
  111. */
  112. SharedHandle<Piece> DefaultPieceStorage::getPiece(size_t index)
  113. {
  114. SharedHandle<Piece> piece;
  115. if(0 <= index && index <= bitfieldMan_->getMaxIndex()) {
  116. piece = findUsedPiece(index);
  117. if(!piece) {
  118. piece.reset(new Piece(index, bitfieldMan_->getBlockLength(index)));
  119. if(hasPiece(index)) {
  120. piece->setAllBlock();
  121. }
  122. }
  123. }
  124. return piece;
  125. }
  126. void DefaultPieceStorage::addUsedPiece(const SharedHandle<Piece>& piece)
  127. {
  128. std::deque<SharedHandle<Piece> >::iterator i =
  129. std::lower_bound(usedPieces_.begin(), usedPieces_.end(), piece,
  130. DerefLess<SharedHandle<Piece> >());
  131. usedPieces_.insert(i, piece);
  132. A2_LOG_DEBUG(fmt("usedPieces_.size()=%lu",
  133. static_cast<unsigned long>(usedPieces_.size())));
  134. }
  135. SharedHandle<Piece> DefaultPieceStorage::findUsedPiece(size_t index) const
  136. {
  137. SharedHandle<Piece> p(new Piece());
  138. p->setIndex(index);
  139. std::deque<SharedHandle<Piece> >::const_iterator i =
  140. std::lower_bound(usedPieces_.begin(), usedPieces_.end(), p,
  141. DerefLess<SharedHandle<Piece> >());
  142. if(i != usedPieces_.end() && *(*i) == *p) {
  143. return *i;
  144. } else {
  145. p.reset();
  146. return p;
  147. }
  148. }
  149. #ifdef ENABLE_BITTORRENT
  150. bool DefaultPieceStorage::hasMissingPiece(const SharedHandle<Peer>& peer)
  151. {
  152. return bitfieldMan_->hasMissingPiece(peer->getBitfield(),
  153. peer->getBitfieldLength());
  154. }
  155. void DefaultPieceStorage::getMissingPiece
  156. (std::vector<SharedHandle<Piece> >& pieces,
  157. size_t minMissingBlocks,
  158. const unsigned char* bitfield,
  159. size_t length,
  160. cuid_t cuid)
  161. {
  162. const size_t mislen = bitfieldMan_->getBitfieldLength();
  163. array_ptr<unsigned char> misbitfield(new unsigned char[mislen]);
  164. size_t blocks = bitfieldMan_->countBlock();
  165. size_t misBlock = 0;
  166. if(isEndGame()) {
  167. bool r = bitfieldMan_->getAllMissingIndexes
  168. (misbitfield, mislen, bitfield, length);
  169. if(!r) {
  170. return;
  171. }
  172. std::vector<size_t> indexes;
  173. for(size_t i = 0; i < blocks; ++i) {
  174. if(bitfield::test(misbitfield, blocks, i)) {
  175. indexes.push_back(i);
  176. }
  177. }
  178. std::random_shuffle(indexes.begin(), indexes.end());
  179. for(std::vector<size_t>::const_iterator i = indexes.begin(),
  180. eoi = indexes.end(); i != eoi && misBlock < minMissingBlocks; ++i) {
  181. SharedHandle<Piece> piece = checkOutPiece(*i, cuid);
  182. if(piece->getUsedBySegment()) {
  183. // We don't share piece downloaded via HTTP/FTP
  184. piece->removeUser(cuid);
  185. } else {
  186. pieces.push_back(piece);
  187. misBlock += piece->countMissingBlock();
  188. }
  189. }
  190. } else {
  191. bool r = bitfieldMan_->getAllMissingUnusedIndexes
  192. (misbitfield, mislen, bitfield, length);
  193. if(!r) {
  194. return;
  195. }
  196. while(misBlock < minMissingBlocks) {
  197. size_t index;
  198. if(pieceSelector_->select(index, misbitfield, blocks)) {
  199. pieces.push_back(checkOutPiece(index, cuid));
  200. bitfield::flipBit(misbitfield, blocks, index);
  201. misBlock += pieces.back()->countMissingBlock();
  202. } else {
  203. break;
  204. }
  205. }
  206. }
  207. }
  208. namespace {
  209. void unsetExcludedIndexes(BitfieldMan& bitfield,
  210. const std::vector<size_t>& excludedIndexes)
  211. {
  212. std::for_each(excludedIndexes.begin(), excludedIndexes.end(),
  213. std::bind1st(std::mem_fun(&BitfieldMan::unsetBit), &bitfield));
  214. }
  215. } // namespace
  216. void DefaultPieceStorage::createFastIndexBitfield
  217. (BitfieldMan& bitfield, const SharedHandle<Peer>& peer)
  218. {
  219. for(std::vector<size_t>::const_iterator itr =
  220. peer->getPeerAllowedIndexSet().begin(),
  221. eoi = peer->getPeerAllowedIndexSet().end(); itr != eoi; ++itr) {
  222. if(!bitfieldMan_->isBitSet(*itr) && peer->hasPiece(*itr)) {
  223. bitfield.setBit(*itr);
  224. }
  225. }
  226. }
  227. void DefaultPieceStorage::getMissingPiece
  228. (std::vector<SharedHandle<Piece> >& pieces,
  229. size_t minMissingBlocks,
  230. const SharedHandle<Peer>& peer,
  231. cuid_t cuid)
  232. {
  233. getMissingPiece(pieces, minMissingBlocks,
  234. peer->getBitfield(), peer->getBitfieldLength(),
  235. cuid);
  236. }
  237. void DefaultPieceStorage::getMissingPiece
  238. (std::vector<SharedHandle<Piece> >& pieces,
  239. size_t minMissingBlocks,
  240. const SharedHandle<Peer>& peer,
  241. const std::vector<size_t>& excludedIndexes,
  242. cuid_t cuid)
  243. {
  244. BitfieldMan tempBitfield(bitfieldMan_->getBlockLength(),
  245. bitfieldMan_->getTotalLength());
  246. tempBitfield.setBitfield(peer->getBitfield(), peer->getBitfieldLength());
  247. unsetExcludedIndexes(tempBitfield, excludedIndexes);
  248. getMissingPiece(pieces, minMissingBlocks,
  249. tempBitfield.getBitfield(), tempBitfield.getBitfieldLength(),
  250. cuid);
  251. }
  252. void DefaultPieceStorage::getMissingFastPiece
  253. (std::vector<SharedHandle<Piece> >& pieces,
  254. size_t minMissingBlocks,
  255. const SharedHandle<Peer>& peer,
  256. cuid_t cuid)
  257. {
  258. if(peer->isFastExtensionEnabled() && peer->countPeerAllowedIndexSet() > 0) {
  259. BitfieldMan tempBitfield(bitfieldMan_->getBlockLength(),
  260. bitfieldMan_->getTotalLength());
  261. createFastIndexBitfield(tempBitfield, peer);
  262. getMissingPiece(pieces, minMissingBlocks,
  263. tempBitfield.getBitfield(),
  264. tempBitfield.getBitfieldLength(),
  265. cuid);
  266. }
  267. }
  268. void DefaultPieceStorage::getMissingFastPiece
  269. (std::vector<SharedHandle<Piece> >& pieces,
  270. size_t minMissingBlocks,
  271. const SharedHandle<Peer>& peer,
  272. const std::vector<size_t>& excludedIndexes,
  273. cuid_t cuid)
  274. {
  275. if(peer->isFastExtensionEnabled() && peer->countPeerAllowedIndexSet() > 0) {
  276. BitfieldMan tempBitfield(bitfieldMan_->getBlockLength(),
  277. bitfieldMan_->getTotalLength());
  278. createFastIndexBitfield(tempBitfield, peer);
  279. unsetExcludedIndexes(tempBitfield, excludedIndexes);
  280. getMissingPiece(pieces, minMissingBlocks,
  281. tempBitfield.getBitfield(),
  282. tempBitfield.getBitfieldLength(),
  283. cuid);
  284. }
  285. }
  286. SharedHandle<Piece>
  287. DefaultPieceStorage::getMissingPiece
  288. (const SharedHandle<Peer>& peer,
  289. cuid_t cuid)
  290. {
  291. std::vector<SharedHandle<Piece> > pieces;
  292. getMissingPiece(pieces, 1, peer, cuid);
  293. if(pieces.empty()) {
  294. return SharedHandle<Piece>();
  295. } else {
  296. return pieces.front();
  297. }
  298. }
  299. SharedHandle<Piece> DefaultPieceStorage::getMissingPiece
  300. (const SharedHandle<Peer>& peer,
  301. const std::vector<size_t>& excludedIndexes,
  302. cuid_t cuid)
  303. {
  304. std::vector<SharedHandle<Piece> > pieces;
  305. getMissingPiece(pieces, 1, peer, excludedIndexes, cuid);
  306. if(pieces.empty()) {
  307. return SharedHandle<Piece>();
  308. } else {
  309. return pieces.front();
  310. }
  311. }
  312. SharedHandle<Piece> DefaultPieceStorage::getMissingFastPiece
  313. (const SharedHandle<Peer>& peer,
  314. cuid_t cuid)
  315. {
  316. std::vector<SharedHandle<Piece> > pieces;
  317. getMissingFastPiece(pieces, 1, peer, cuid);
  318. if(pieces.empty()) {
  319. return SharedHandle<Piece>();
  320. } else {
  321. return pieces.front();
  322. }
  323. }
  324. SharedHandle<Piece> DefaultPieceStorage::getMissingFastPiece
  325. (const SharedHandle<Peer>& peer,
  326. const std::vector<size_t>& excludedIndexes,
  327. cuid_t cuid)
  328. {
  329. std::vector<SharedHandle<Piece> > pieces;
  330. getMissingFastPiece(pieces, 1, peer, excludedIndexes, cuid);
  331. if(pieces.empty()) {
  332. return SharedHandle<Piece>();
  333. } else {
  334. return pieces.front();
  335. }
  336. }
  337. #endif // ENABLE_BITTORRENT
  338. bool DefaultPieceStorage::hasMissingUnusedPiece()
  339. {
  340. size_t index;
  341. return bitfieldMan_->getFirstMissingUnusedIndex(index);
  342. }
  343. SharedHandle<Piece> DefaultPieceStorage::getMissingPiece
  344. (size_t minSplitSize,
  345. const unsigned char* ignoreBitfield,
  346. size_t length,
  347. cuid_t cuid)
  348. {
  349. size_t index;
  350. if(streamPieceSelector_->select
  351. (index, minSplitSize, ignoreBitfield, length)) {
  352. return checkOutPiece(index, cuid);
  353. } else {
  354. return SharedHandle<Piece>();
  355. }
  356. }
  357. SharedHandle<Piece> DefaultPieceStorage::getMissingPiece
  358. (size_t index,
  359. cuid_t cuid)
  360. {
  361. if(hasPiece(index) || isPieceUsed(index)) {
  362. return SharedHandle<Piece>();
  363. } else {
  364. return checkOutPiece(index, cuid);
  365. }
  366. }
  367. void DefaultPieceStorage::deleteUsedPiece(const SharedHandle<Piece>& piece)
  368. {
  369. if(!piece) {
  370. return;
  371. }
  372. std::deque<SharedHandle<Piece> >::iterator i =
  373. std::lower_bound(usedPieces_.begin(), usedPieces_.end(), piece,
  374. DerefLess<SharedHandle<Piece> >());
  375. if(i != usedPieces_.end() && *(*i) == *piece) {
  376. usedPieces_.erase(i);
  377. }
  378. }
  379. // void DefaultPieceStorage::reduceUsedPieces(size_t upperBound)
  380. // {
  381. // size_t usedPiecesSize = usedPieces.size();
  382. // if(usedPiecesSize <= upperBound) {
  383. // return;
  384. // }
  385. // size_t delNum = usedPiecesSize-upperBound;
  386. // int fillRate = 10;
  387. // while(delNum && fillRate <= 15) {
  388. // delNum -= deleteUsedPiecesByFillRate(fillRate, delNum);
  389. // fillRate += 5;
  390. // }
  391. // }
  392. // size_t DefaultPieceStorage::deleteUsedPiecesByFillRate(int fillRate,
  393. // size_t delNum)
  394. // {
  395. // size_t deleted = 0;
  396. // for(Pieces::iterator itr = usedPieces.begin();
  397. // itr != usedPieces.end() && deleted < delNum;) {
  398. // SharedHandle<Piece>& piece = *itr;
  399. // if(!bitfieldMan->isUseBitSet(piece->getIndex()) &&
  400. // piece->countCompleteBlock() <= piece->countBlock()*(fillRate/100.0)) {
  401. // logger->info(MSG_DELETING_USED_PIECE,
  402. // piece->getIndex(),
  403. // (piece->countCompleteBlock()*100)/piece->countBlock(),
  404. // fillRate);
  405. // itr = usedPieces.erase(itr);
  406. // ++deleted;
  407. // } else {
  408. // ++itr;
  409. // }
  410. // }
  411. // return deleted;
  412. // }
  413. void DefaultPieceStorage::completePiece(const SharedHandle<Piece>& piece)
  414. {
  415. if(!piece) {
  416. return;
  417. }
  418. deleteUsedPiece(piece);
  419. // if(!isEndGame()) {
  420. // reduceUsedPieces(100);
  421. // }
  422. if(allDownloadFinished()) {
  423. return;
  424. }
  425. bitfieldMan_->setBit(piece->getIndex());
  426. bitfieldMan_->unsetUseBit(piece->getIndex());
  427. addPieceStats(piece->getIndex());
  428. if(downloadFinished()) {
  429. downloadContext_->resetDownloadStopTime();
  430. if(isSelectiveDownloadingMode()) {
  431. A2_LOG_NOTICE(MSG_SELECTIVE_DOWNLOAD_COMPLETED);
  432. // following line was commented out in order to stop sending request
  433. // message after user-specified files were downloaded.
  434. //finishSelectiveDownloadingMode();
  435. } else {
  436. A2_LOG_INFO(MSG_DOWNLOAD_COMPLETED);
  437. }
  438. #ifdef ENABLE_BITTORRENT
  439. if(downloadContext_->hasAttribute(bittorrent::BITTORRENT)) {
  440. SharedHandle<TorrentAttribute> torrentAttrs =
  441. bittorrent::getTorrentAttrs(downloadContext_);
  442. if(!torrentAttrs->metadata.empty()) {
  443. util::executeHookByOptName(downloadContext_->getOwnerRequestGroup(),
  444. option_, PREF_ON_BT_DOWNLOAD_COMPLETE);
  445. }
  446. }
  447. #endif // ENABLE_BITTORRENT
  448. }
  449. }
  450. bool DefaultPieceStorage::isSelectiveDownloadingMode()
  451. {
  452. return bitfieldMan_->isFilterEnabled();
  453. }
  454. // not unittested
  455. void DefaultPieceStorage::cancelPiece
  456. (const SharedHandle<Piece>& piece, cuid_t cuid)
  457. {
  458. if(!piece) {
  459. return;
  460. }
  461. piece->removeUser(cuid);
  462. if(!piece->getUsed()) {
  463. bitfieldMan_->unsetUseBit(piece->getIndex());
  464. }
  465. if(!isEndGame()) {
  466. if(piece->getCompletedLength() == 0) {
  467. deleteUsedPiece(piece);
  468. }
  469. }
  470. }
  471. bool DefaultPieceStorage::hasPiece(size_t index)
  472. {
  473. return bitfieldMan_->isBitSet(index);
  474. }
  475. bool DefaultPieceStorage::isPieceUsed(size_t index)
  476. {
  477. return bitfieldMan_->isUseBitSet(index);
  478. }
  479. uint64_t DefaultPieceStorage::getTotalLength()
  480. {
  481. return bitfieldMan_->getTotalLength();
  482. }
  483. uint64_t DefaultPieceStorage::getFilteredTotalLength()
  484. {
  485. return bitfieldMan_->getFilteredTotalLength();
  486. }
  487. uint64_t DefaultPieceStorage::getCompletedLength()
  488. {
  489. uint64_t completedLength =
  490. bitfieldMan_->getCompletedLength()+getInFlightPieceCompletedLength();
  491. uint64_t totalLength = getTotalLength();
  492. if(completedLength > totalLength) {
  493. completedLength = totalLength;
  494. }
  495. return completedLength;
  496. }
  497. uint64_t DefaultPieceStorage::getFilteredCompletedLength()
  498. {
  499. return bitfieldMan_->getFilteredCompletedLength()+
  500. getInFlightPieceCompletedLength();
  501. }
  502. size_t DefaultPieceStorage::getInFlightPieceCompletedLength() const
  503. {
  504. return std::accumulate(usedPieces_.begin(), usedPieces_.end(),
  505. 0, adopt2nd(std::plus<size_t>(),
  506. mem_fun_sh(&Piece::getCompletedLength)));
  507. }
  508. // not unittested
  509. void DefaultPieceStorage::setupFileFilter()
  510. {
  511. const std::vector<SharedHandle<FileEntry> >& fileEntries =
  512. downloadContext_->getFileEntries();
  513. bool allSelected = true;
  514. for(std::vector<SharedHandle<FileEntry> >::const_iterator i =
  515. fileEntries.begin(), eoi = fileEntries.end();
  516. i != eoi; ++i) {
  517. if(!(*i)->isRequested()) {
  518. allSelected = false;
  519. break;
  520. }
  521. }
  522. if(allSelected) {
  523. return;
  524. }
  525. for(std::vector<SharedHandle<FileEntry> >::const_iterator i =
  526. fileEntries.begin(), eoi = fileEntries.end(); i != eoi; ++i) {
  527. if((*i)->isRequested()) {
  528. bitfieldMan_->addFilter((*i)->getOffset(), (*i)->getLength());
  529. }
  530. }
  531. bitfieldMan_->enableFilter();
  532. }
  533. // not unittested
  534. void DefaultPieceStorage::clearFileFilter()
  535. {
  536. bitfieldMan_->clearFilter();
  537. }
  538. // not unittested
  539. bool DefaultPieceStorage::downloadFinished()
  540. {
  541. // TODO iterate all requested FileEntry and Call
  542. // bitfieldMan->isBitSetOffsetRange()
  543. return bitfieldMan_->isFilteredAllBitSet();
  544. }
  545. // not unittested
  546. bool DefaultPieceStorage::allDownloadFinished()
  547. {
  548. return bitfieldMan_->isAllBitSet();
  549. }
  550. // not unittested
  551. void DefaultPieceStorage::initStorage()
  552. {
  553. if(downloadContext_->getFileEntries().size() == 1) {
  554. A2_LOG_DEBUG("Instantiating DirectDiskAdaptor");
  555. DirectDiskAdaptorHandle directDiskAdaptor(new DirectDiskAdaptor());
  556. directDiskAdaptor->setTotalLength(downloadContext_->getTotalLength());
  557. directDiskAdaptor->setFileEntries
  558. (downloadContext_->getFileEntries().begin(),
  559. downloadContext_->getFileEntries().end());
  560. DiskWriterHandle writer =
  561. diskWriterFactory_->newDiskWriter(directDiskAdaptor->getFilePath());
  562. directDiskAdaptor->setDiskWriter(writer);
  563. diskAdaptor_ = directDiskAdaptor;
  564. } else {
  565. A2_LOG_DEBUG("Instantiating MultiDiskAdaptor");
  566. MultiDiskAdaptorHandle multiDiskAdaptor(new MultiDiskAdaptor());
  567. multiDiskAdaptor->setFileEntries(downloadContext_->getFileEntries().begin(),
  568. downloadContext_->getFileEntries().end());
  569. multiDiskAdaptor->setPieceLength(downloadContext_->getPieceLength());
  570. multiDiskAdaptor->setMaxOpenFiles
  571. (option_->getAsInt(PREF_BT_MAX_OPEN_FILES));
  572. diskAdaptor_ = multiDiskAdaptor;
  573. }
  574. if(option_->get(PREF_FILE_ALLOCATION) == V_FALLOC) {
  575. diskAdaptor_->enableFallocate();
  576. }
  577. }
  578. void DefaultPieceStorage::setBitfield(const unsigned char* bitfield,
  579. size_t bitfieldLength)
  580. {
  581. bitfieldMan_->setBitfield(bitfield, bitfieldLength);
  582. addPieceStats(bitfield, bitfieldLength);
  583. }
  584. size_t DefaultPieceStorage::getBitfieldLength()
  585. {
  586. return bitfieldMan_->getBitfieldLength();
  587. }
  588. const unsigned char* DefaultPieceStorage::getBitfield()
  589. {
  590. return bitfieldMan_->getBitfield();
  591. }
  592. DiskAdaptorHandle DefaultPieceStorage::getDiskAdaptor() {
  593. return diskAdaptor_;
  594. }
  595. size_t DefaultPieceStorage::getPieceLength(size_t index)
  596. {
  597. return bitfieldMan_->getBlockLength(index);
  598. }
  599. void DefaultPieceStorage::advertisePiece(cuid_t cuid, size_t index)
  600. {
  601. HaveEntry entry(cuid, index, global::wallclock);
  602. haves_.push_front(entry);
  603. }
  604. void
  605. DefaultPieceStorage::getAdvertisedPieceIndexes(std::vector<size_t>& indexes,
  606. cuid_t myCuid,
  607. const Timer& lastCheckTime)
  608. {
  609. for(std::deque<HaveEntry>::const_iterator itr = haves_.begin(),
  610. eoi = haves_.end(); itr != eoi; ++itr) {
  611. const HaveEntry& have = *itr;
  612. if(have.getCuid() == myCuid) {
  613. continue;
  614. }
  615. if(lastCheckTime > have.getRegisteredTime()) {
  616. break;
  617. }
  618. indexes.push_back(have.getIndex());
  619. }
  620. }
  621. namespace {
  622. class FindElapsedHave
  623. {
  624. private:
  625. time_t elapsed;
  626. public:
  627. FindElapsedHave(time_t elapsed):elapsed(elapsed) {}
  628. bool operator()(const HaveEntry& have) {
  629. if(have.getRegisteredTime().difference(global::wallclock) >= elapsed) {
  630. return true;
  631. } else {
  632. return false;
  633. }
  634. }
  635. };
  636. } // namespace
  637. void DefaultPieceStorage::removeAdvertisedPiece(time_t elapsed)
  638. {
  639. std::deque<HaveEntry>::iterator itr =
  640. std::find_if(haves_.begin(), haves_.end(), FindElapsedHave(elapsed));
  641. if(itr != haves_.end()) {
  642. A2_LOG_DEBUG(fmt(MSG_REMOVED_HAVE_ENTRY,
  643. static_cast<unsigned long>(haves_.end()-itr)));
  644. haves_.erase(itr, haves_.end());
  645. }
  646. }
  647. void DefaultPieceStorage::markAllPiecesDone()
  648. {
  649. bitfieldMan_->setAllBit();
  650. }
  651. void DefaultPieceStorage::markPiecesDone(uint64_t length)
  652. {
  653. if(length == bitfieldMan_->getTotalLength()) {
  654. bitfieldMan_->setAllBit();
  655. } else if(length == 0) {
  656. // TODO this would go to markAllPiecesUndone()
  657. bitfieldMan_->clearAllBit();
  658. usedPieces_.clear();
  659. } else {
  660. size_t numPiece = length/bitfieldMan_->getBlockLength();
  661. if(numPiece > 0) {
  662. bitfieldMan_->setBitRange(0, numPiece-1);
  663. }
  664. size_t r = (length%bitfieldMan_->getBlockLength())/Piece::BLOCK_LENGTH;
  665. if(r > 0) {
  666. SharedHandle<Piece> p
  667. (new Piece(numPiece, bitfieldMan_->getBlockLength(numPiece)));
  668. for(size_t i = 0; i < r; ++i) {
  669. p->completeBlock(i);
  670. }
  671. #ifdef ENABLE_MESSAGE_DIGEST
  672. p->setHashType(downloadContext_->getPieceHashType());
  673. #endif // ENABLE_MESSAGE_DIGEST
  674. addUsedPiece(p);
  675. }
  676. }
  677. }
  678. void DefaultPieceStorage::markPieceMissing(size_t index)
  679. {
  680. bitfieldMan_->unsetBit(index);
  681. }
  682. void DefaultPieceStorage::addInFlightPiece
  683. (const std::vector<SharedHandle<Piece> >& pieces)
  684. {
  685. usedPieces_.insert(usedPieces_.end(), pieces.begin(), pieces.end());
  686. std::sort(usedPieces_.begin(), usedPieces_.end(),
  687. DerefLess<SharedHandle<Piece> >());
  688. }
  689. size_t DefaultPieceStorage::countInFlightPiece()
  690. {
  691. return usedPieces_.size();
  692. }
  693. void DefaultPieceStorage::getInFlightPieces
  694. (std::vector<SharedHandle<Piece> >& pieces)
  695. {
  696. pieces.insert(pieces.end(), usedPieces_.begin(), usedPieces_.end());
  697. }
  698. void DefaultPieceStorage::setDiskWriterFactory
  699. (const DiskWriterFactoryHandle& diskWriterFactory)
  700. {
  701. diskWriterFactory_ = diskWriterFactory;
  702. }
  703. void DefaultPieceStorage::addPieceStats(const unsigned char* bitfield,
  704. size_t bitfieldLength)
  705. {
  706. pieceStatMan_->addPieceStats(bitfield, bitfieldLength);
  707. }
  708. void DefaultPieceStorage::subtractPieceStats(const unsigned char* bitfield,
  709. size_t bitfieldLength)
  710. {
  711. pieceStatMan_->subtractPieceStats(bitfield, bitfieldLength);
  712. }
  713. void DefaultPieceStorage::updatePieceStats(const unsigned char* newBitfield,
  714. size_t newBitfieldLength,
  715. const unsigned char* oldBitfield)
  716. {
  717. pieceStatMan_->updatePieceStats(newBitfield, newBitfieldLength,
  718. oldBitfield);
  719. }
  720. void DefaultPieceStorage::addPieceStats(size_t index)
  721. {
  722. pieceStatMan_->addPieceStats(index);
  723. }
  724. size_t DefaultPieceStorage::getNextUsedIndex(size_t index)
  725. {
  726. for(size_t i = index+1; i < bitfieldMan_->countBlock(); ++i) {
  727. if(bitfieldMan_->isUseBitSet(i) || bitfieldMan_->isBitSet(i)) {
  728. return i;
  729. }
  730. }
  731. return bitfieldMan_->countBlock();
  732. }
  733. } // namespace aria2