DefaultPieceStorage.cc 23 KB

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