DefaultPieceStorage.cc 24 KB

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