DefaultPieceStorage.cc 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869
  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_(new RarestPieceSelector(pieceStatMan_)),
  83. wrDiskCache_(0)
  84. {
  85. const std::string& pieceSelectorOpt =
  86. option_->get(PREF_STREAM_PIECE_SELECTOR);
  87. if(pieceSelectorOpt.empty() || pieceSelectorOpt == A2_V_DEFAULT) {
  88. streamPieceSelector_.reset(new DefaultStreamPieceSelector(bitfieldMan_));
  89. } else if(pieceSelectorOpt == V_INORDER) {
  90. streamPieceSelector_.reset(new InorderStreamPieceSelector(bitfieldMan_));
  91. } else if(pieceSelectorOpt == A2_V_GEOM) {
  92. streamPieceSelector_.reset(new GeomStreamPieceSelector(bitfieldMan_, 1.5));
  93. }
  94. }
  95. DefaultPieceStorage::~DefaultPieceStorage()
  96. {
  97. delete bitfieldMan_;
  98. }
  99. std::shared_ptr<Piece> DefaultPieceStorage::checkOutPiece
  100. (size_t index, cuid_t cuid)
  101. {
  102. bitfieldMan_->setUseBit(index);
  103. std::shared_ptr<Piece> piece = findUsedPiece(index);
  104. if(!piece) {
  105. piece.reset(new Piece(index, bitfieldMan_->getBlockLength(index)));
  106. #ifdef ENABLE_MESSAGE_DIGEST
  107. piece->setHashType(downloadContext_->getPieceHashType());
  108. #endif // ENABLE_MESSAGE_DIGEST
  109. addUsedPiece(piece);
  110. }
  111. piece->addUser(cuid);
  112. RequestGroup* group = downloadContext_->getOwnerRequestGroup();
  113. if((!group || !group->inMemoryDownload()) &&
  114. wrDiskCache_ && !piece->getWrDiskCacheEntry()) {
  115. // So, we rely on the fact that diskAdaptor_ is not reinitialized
  116. // in the session.
  117. piece->initWrCache(wrDiskCache_, diskAdaptor_);
  118. }
  119. return piece;
  120. }
  121. /**
  122. * Newly instantiated piece is not added to usedPieces.
  123. * Because it is waste of memory and there is no chance to use them later.
  124. */
  125. std::shared_ptr<Piece> DefaultPieceStorage::getPiece(size_t index)
  126. {
  127. std::shared_ptr<Piece> piece;
  128. if(index <= bitfieldMan_->getMaxIndex()) {
  129. piece = findUsedPiece(index);
  130. if(!piece) {
  131. piece.reset(new Piece(index, bitfieldMan_->getBlockLength(index)));
  132. if(hasPiece(index)) {
  133. piece->setAllBlock();
  134. }
  135. }
  136. }
  137. return piece;
  138. }
  139. void DefaultPieceStorage::addUsedPiece(const std::shared_ptr<Piece>& piece)
  140. {
  141. usedPieces_.insert(piece);
  142. A2_LOG_DEBUG(fmt("usedPieces_.size()=%lu",
  143. static_cast<unsigned long>(usedPieces_.size())));
  144. }
  145. std::shared_ptr<Piece> DefaultPieceStorage::findUsedPiece(size_t index) const
  146. {
  147. std::shared_ptr<Piece> p(new Piece());
  148. p->setIndex(index);
  149. UsedPieceSet::iterator i = usedPieces_.find(p);
  150. if(i == usedPieces_.end()) {
  151. p.reset();
  152. return p;
  153. } else {
  154. return *i;
  155. }
  156. }
  157. #ifdef ENABLE_BITTORRENT
  158. bool DefaultPieceStorage::hasMissingPiece(const std::shared_ptr<Peer>& peer)
  159. {
  160. return bitfieldMan_->hasMissingPiece(peer->getBitfield(),
  161. peer->getBitfieldLength());
  162. }
  163. void DefaultPieceStorage::getMissingPiece
  164. (std::vector<std::shared_ptr<Piece> >& pieces,
  165. size_t minMissingBlocks,
  166. const unsigned char* bitfield,
  167. size_t length,
  168. cuid_t cuid)
  169. {
  170. const size_t mislen = bitfieldMan_->getBitfieldLength();
  171. array_ptr<unsigned char> misbitfield(new unsigned char[mislen]);
  172. size_t blocks = bitfieldMan_->countBlock();
  173. size_t misBlock = 0;
  174. if(isEndGame()) {
  175. bool r = bitfieldMan_->getAllMissingIndexes
  176. (misbitfield, mislen, bitfield, length);
  177. if(!r) {
  178. return;
  179. }
  180. std::vector<size_t> indexes;
  181. for(size_t i = 0; i < blocks; ++i) {
  182. if(bitfield::test(misbitfield, blocks, i)) {
  183. indexes.push_back(i);
  184. }
  185. }
  186. std::random_shuffle(indexes.begin(), indexes.end());
  187. for(std::vector<size_t>::const_iterator i = indexes.begin(),
  188. eoi = indexes.end(); i != eoi && misBlock < minMissingBlocks; ++i) {
  189. std::shared_ptr<Piece> piece = checkOutPiece(*i, cuid);
  190. if(piece->getUsedBySegment()) {
  191. // We don't share piece downloaded via HTTP/FTP
  192. piece->removeUser(cuid);
  193. } else {
  194. pieces.push_back(piece);
  195. misBlock += piece->countMissingBlock();
  196. }
  197. }
  198. } else {
  199. bool r = bitfieldMan_->getAllMissingUnusedIndexes
  200. (misbitfield, mislen, bitfield, length);
  201. if(!r) {
  202. return;
  203. }
  204. while(misBlock < minMissingBlocks) {
  205. size_t index;
  206. if(pieceSelector_->select(index, misbitfield, blocks)) {
  207. pieces.push_back(checkOutPiece(index, cuid));
  208. bitfield::flipBit(misbitfield, blocks, index);
  209. misBlock += pieces.back()->countMissingBlock();
  210. } else {
  211. break;
  212. }
  213. }
  214. }
  215. }
  216. namespace {
  217. void unsetExcludedIndexes(BitfieldMan& bitfield,
  218. const std::vector<size_t>& excludedIndexes)
  219. {
  220. using namespace std::placeholders;
  221. std::for_each(excludedIndexes.begin(), excludedIndexes.end(),
  222. std::bind(&BitfieldMan::unsetBit, &bitfield, _1));
  223. }
  224. } // namespace
  225. void DefaultPieceStorage::createFastIndexBitfield
  226. (BitfieldMan& bitfield, const std::shared_ptr<Peer>& peer)
  227. {
  228. for(std::set<size_t>::const_iterator itr =
  229. peer->getPeerAllowedIndexSet().begin(),
  230. eoi = peer->getPeerAllowedIndexSet().end(); itr != eoi; ++itr) {
  231. if(!bitfieldMan_->isBitSet(*itr) && peer->hasPiece(*itr)) {
  232. bitfield.setBit(*itr);
  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 std::shared_ptr<Piece>();
  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 std::shared_ptr<Piece>();
  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 std::shared_ptr<Piece>();
  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 std::shared_ptr<Piece>();
  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 std::shared_ptr<Piece>();
  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 std::shared_ptr<Piece>();
  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(UsedPieceSet::const_iterator i = usedPieces_.begin(),
  523. eoi = usedPieces_.end(); i != eoi; ++i) {
  524. len += (*i)->getCompletedLength();
  525. }
  526. return len;
  527. }
  528. int64_t DefaultPieceStorage::getInFlightPieceFilteredCompletedLength() const
  529. {
  530. int64_t len = 0;
  531. for(UsedPieceSet::const_iterator i = usedPieces_.begin(),
  532. eoi = usedPieces_.end(); i != eoi; ++i) {
  533. if(bitfieldMan_->isFilterBitSet((*i)->getIndex())) {
  534. len += (*i)->getCompletedLength();
  535. }
  536. }
  537. return len;
  538. }
  539. // not unittested
  540. void DefaultPieceStorage::setupFileFilter()
  541. {
  542. const std::vector<std::shared_ptr<FileEntry> >& fileEntries =
  543. downloadContext_->getFileEntries();
  544. bool allSelected = true;
  545. for(std::vector<std::shared_ptr<FileEntry> >::const_iterator i =
  546. fileEntries.begin(), eoi = fileEntries.end();
  547. i != eoi; ++i) {
  548. if(!(*i)->isRequested()) {
  549. allSelected = false;
  550. break;
  551. }
  552. }
  553. if(allSelected) {
  554. return;
  555. }
  556. for(std::vector<std::shared_ptr<FileEntry> >::const_iterator i =
  557. fileEntries.begin(), eoi = fileEntries.end(); i != eoi; ++i) {
  558. if((*i)->isRequested()) {
  559. bitfieldMan_->addFilter((*i)->getOffset(), (*i)->getLength());
  560. }
  561. }
  562. bitfieldMan_->enableFilter();
  563. }
  564. // not unittested
  565. void DefaultPieceStorage::clearFileFilter()
  566. {
  567. bitfieldMan_->clearFilter();
  568. }
  569. // not unittested
  570. bool DefaultPieceStorage::downloadFinished()
  571. {
  572. // TODO iterate all requested FileEntry and Call
  573. // bitfieldMan->isBitSetOffsetRange()
  574. return bitfieldMan_->isFilteredAllBitSet();
  575. }
  576. // not unittested
  577. bool DefaultPieceStorage::allDownloadFinished()
  578. {
  579. return bitfieldMan_->isAllBitSet();
  580. }
  581. // not unittested
  582. void DefaultPieceStorage::initStorage()
  583. {
  584. if(downloadContext_->getFileEntries().size() == 1) {
  585. A2_LOG_DEBUG("Instantiating DirectDiskAdaptor");
  586. DirectDiskAdaptor* directDiskAdaptor(new DirectDiskAdaptor());
  587. directDiskAdaptor->setTotalLength(downloadContext_->getTotalLength());
  588. directDiskAdaptor->setFileEntries
  589. (downloadContext_->getFileEntries().begin(),
  590. downloadContext_->getFileEntries().end());
  591. std::shared_ptr<DiskWriter> writer =
  592. diskWriterFactory_->newDiskWriter(directDiskAdaptor->getFilePath());
  593. directDiskAdaptor->setDiskWriter(writer);
  594. diskAdaptor_.reset(directDiskAdaptor);
  595. } else {
  596. A2_LOG_DEBUG("Instantiating MultiDiskAdaptor");
  597. MultiDiskAdaptor* multiDiskAdaptor(new MultiDiskAdaptor());
  598. multiDiskAdaptor->setFileEntries(downloadContext_->getFileEntries().begin(),
  599. downloadContext_->getFileEntries().end());
  600. multiDiskAdaptor->setPieceLength(downloadContext_->getPieceLength());
  601. multiDiskAdaptor->setMaxOpenFiles
  602. (option_->getAsInt(PREF_BT_MAX_OPEN_FILES));
  603. diskAdaptor_.reset(multiDiskAdaptor);
  604. }
  605. if(option_->get(PREF_FILE_ALLOCATION) == V_FALLOC) {
  606. diskAdaptor_->setFileAllocationMethod(DiskAdaptor::FILE_ALLOC_FALLOC);
  607. } else if(option_->get(PREF_FILE_ALLOCATION) == V_TRUNC) {
  608. diskAdaptor_->setFileAllocationMethod(DiskAdaptor::FILE_ALLOC_TRUNC);
  609. }
  610. }
  611. void DefaultPieceStorage::setBitfield(const unsigned char* bitfield,
  612. size_t bitfieldLength)
  613. {
  614. bitfieldMan_->setBitfield(bitfield, bitfieldLength);
  615. addPieceStats(bitfield, bitfieldLength);
  616. }
  617. size_t DefaultPieceStorage::getBitfieldLength()
  618. {
  619. return bitfieldMan_->getBitfieldLength();
  620. }
  621. const unsigned char* DefaultPieceStorage::getBitfield()
  622. {
  623. return bitfieldMan_->getBitfield();
  624. }
  625. std::shared_ptr<DiskAdaptor> DefaultPieceStorage::getDiskAdaptor() {
  626. return diskAdaptor_;
  627. }
  628. WrDiskCache* DefaultPieceStorage::getWrDiskCache()
  629. {
  630. return wrDiskCache_;
  631. }
  632. void DefaultPieceStorage::flushWrDiskCacheEntry()
  633. {
  634. if(!wrDiskCache_) {
  635. return;
  636. }
  637. // UsedPieceSet is sorted by piece index. It means we can flush
  638. // cache by non-decreasing offset, which is good to reduce disk seek
  639. // unless the file is heavily fragmented.
  640. for(UsedPieceSet::const_iterator i = usedPieces_.begin(),
  641. eoi = usedPieces_.end(); i != eoi; ++i) {
  642. WrDiskCacheEntry* ce = (*i)->getWrDiskCacheEntry();
  643. if(ce) {
  644. (*i)->flushWrCache(wrDiskCache_);
  645. (*i)->releaseWrCache(wrDiskCache_);
  646. }
  647. }
  648. }
  649. int32_t DefaultPieceStorage::getPieceLength(size_t index)
  650. {
  651. return bitfieldMan_->getBlockLength(index);
  652. }
  653. void DefaultPieceStorage::advertisePiece(cuid_t cuid, size_t index)
  654. {
  655. HaveEntry entry(cuid, index, global::wallclock());
  656. haves_.push_front(entry);
  657. }
  658. void
  659. DefaultPieceStorage::getAdvertisedPieceIndexes(std::vector<size_t>& indexes,
  660. cuid_t myCuid,
  661. const Timer& lastCheckTime)
  662. {
  663. for(std::deque<HaveEntry>::const_iterator itr = haves_.begin(),
  664. eoi = haves_.end(); itr != eoi; ++itr) {
  665. const HaveEntry& have = *itr;
  666. if(lastCheckTime > have.getRegisteredTime()) {
  667. break;
  668. }
  669. indexes.push_back(have.getIndex());
  670. }
  671. }
  672. namespace {
  673. class FindElapsedHave
  674. {
  675. private:
  676. time_t elapsed;
  677. public:
  678. FindElapsedHave(time_t elapsed):elapsed(elapsed) {}
  679. bool operator()(const HaveEntry& have) {
  680. if(have.getRegisteredTime().difference(global::wallclock()) >= elapsed) {
  681. return true;
  682. } else {
  683. return false;
  684. }
  685. }
  686. };
  687. } // namespace
  688. void DefaultPieceStorage::removeAdvertisedPiece(time_t elapsed)
  689. {
  690. std::deque<HaveEntry>::iterator itr =
  691. std::find_if(haves_.begin(), haves_.end(), FindElapsedHave(elapsed));
  692. if(itr != haves_.end()) {
  693. A2_LOG_DEBUG(fmt(MSG_REMOVED_HAVE_ENTRY,
  694. static_cast<unsigned long>(haves_.end()-itr)));
  695. haves_.erase(itr, haves_.end());
  696. }
  697. }
  698. void DefaultPieceStorage::markAllPiecesDone()
  699. {
  700. bitfieldMan_->setAllBit();
  701. }
  702. void DefaultPieceStorage::markPiecesDone(int64_t length)
  703. {
  704. if(length == bitfieldMan_->getTotalLength()) {
  705. bitfieldMan_->setAllBit();
  706. } else if(length == 0) {
  707. // TODO this would go to markAllPiecesUndone()
  708. bitfieldMan_->clearAllBit();
  709. usedPieces_.clear();
  710. } else {
  711. size_t numPiece = length/bitfieldMan_->getBlockLength();
  712. if(numPiece > 0) {
  713. bitfieldMan_->setBitRange(0, numPiece-1);
  714. }
  715. size_t r = (length%bitfieldMan_->getBlockLength())/Piece::BLOCK_LENGTH;
  716. if(r > 0) {
  717. std::shared_ptr<Piece> p
  718. (new Piece(numPiece, bitfieldMan_->getBlockLength(numPiece)));
  719. for(size_t i = 0; i < r; ++i) {
  720. p->completeBlock(i);
  721. }
  722. #ifdef ENABLE_MESSAGE_DIGEST
  723. p->setHashType(downloadContext_->getPieceHashType());
  724. #endif // ENABLE_MESSAGE_DIGEST
  725. addUsedPiece(p);
  726. }
  727. }
  728. }
  729. void DefaultPieceStorage::markPieceMissing(size_t index)
  730. {
  731. bitfieldMan_->unsetBit(index);
  732. }
  733. void DefaultPieceStorage::addInFlightPiece
  734. (const std::vector<std::shared_ptr<Piece> >& pieces)
  735. {
  736. usedPieces_.insert(pieces.begin(), pieces.end());
  737. }
  738. size_t DefaultPieceStorage::countInFlightPiece()
  739. {
  740. return usedPieces_.size();
  741. }
  742. void DefaultPieceStorage::getInFlightPieces
  743. (std::vector<std::shared_ptr<Piece> >& pieces)
  744. {
  745. pieces.insert(pieces.end(), usedPieces_.begin(), usedPieces_.end());
  746. }
  747. void DefaultPieceStorage::setDiskWriterFactory
  748. (const std::shared_ptr<DiskWriterFactory>& diskWriterFactory)
  749. {
  750. diskWriterFactory_ = diskWriterFactory;
  751. }
  752. void DefaultPieceStorage::addPieceStats(const unsigned char* bitfield,
  753. size_t bitfieldLength)
  754. {
  755. pieceStatMan_->addPieceStats(bitfield, bitfieldLength);
  756. }
  757. void DefaultPieceStorage::subtractPieceStats(const unsigned char* bitfield,
  758. size_t bitfieldLength)
  759. {
  760. pieceStatMan_->subtractPieceStats(bitfield, bitfieldLength);
  761. }
  762. void DefaultPieceStorage::updatePieceStats(const unsigned char* newBitfield,
  763. size_t newBitfieldLength,
  764. const unsigned char* oldBitfield)
  765. {
  766. pieceStatMan_->updatePieceStats(newBitfield, newBitfieldLength,
  767. oldBitfield);
  768. }
  769. void DefaultPieceStorage::addPieceStats(size_t index)
  770. {
  771. pieceStatMan_->addPieceStats(index);
  772. }
  773. size_t DefaultPieceStorage::getNextUsedIndex(size_t index)
  774. {
  775. for(size_t i = index+1; i < bitfieldMan_->countBlock(); ++i) {
  776. if(bitfieldMan_->isUseBitSet(i) || bitfieldMan_->isBitSet(i)) {
  777. return i;
  778. }
  779. }
  780. return bitfieldMan_->countBlock();
  781. }
  782. void DefaultPieceStorage::onDownloadIncomplete()
  783. {
  784. streamPieceSelector_->onBitfieldInit();
  785. }
  786. } // namespace aria2