DefaultPieceStorage.cc 25 KB

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