DefaultPieceStorage.cc 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871
  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. std::shared_ptr<TorrentAttribute> torrentAttrs =
  446. bittorrent::getTorrentAttrs(downloadContext_);
  447. if(!torrentAttrs->metadata.empty()) {
  448. #ifdef __MINGW32__
  449. // On Windows, if aria2 opens files with GENERIC_WRITE access
  450. // right, some programs cannot open them aria2 is seeding. To
  451. // avoid this situation, re-open the files with read-only
  452. // enabled.
  453. A2_LOG_INFO("Closing files and re-open them with read-only mode"
  454. " enabled.");
  455. diskAdaptor_->closeFile();
  456. diskAdaptor_->enableReadOnly();
  457. diskAdaptor_->openFile();
  458. #endif // __MINGW32__
  459. util::executeHookByOptName(downloadContext_->getOwnerRequestGroup(),
  460. option_, PREF_ON_BT_DOWNLOAD_COMPLETE);
  461. SingletonHolder<Notifier>::instance()->
  462. notifyDownloadEvent(EVENT_ON_BT_DOWNLOAD_COMPLETE,
  463. downloadContext_->getOwnerRequestGroup());
  464. }
  465. }
  466. #endif // ENABLE_BITTORRENT
  467. }
  468. }
  469. bool DefaultPieceStorage::isSelectiveDownloadingMode()
  470. {
  471. return bitfieldMan_->isFilterEnabled();
  472. }
  473. // not unittested
  474. void DefaultPieceStorage::cancelPiece
  475. (const std::shared_ptr<Piece>& piece, cuid_t cuid)
  476. {
  477. if(!piece) {
  478. return;
  479. }
  480. piece->removeUser(cuid);
  481. if(!piece->getUsed()) {
  482. bitfieldMan_->unsetUseBit(piece->getIndex());
  483. }
  484. if(!isEndGame()) {
  485. if(piece->getCompletedLength() == 0) {
  486. deleteUsedPiece(piece);
  487. }
  488. }
  489. }
  490. bool DefaultPieceStorage::hasPiece(size_t index)
  491. {
  492. return bitfieldMan_->isBitSet(index);
  493. }
  494. bool DefaultPieceStorage::isPieceUsed(size_t index)
  495. {
  496. return bitfieldMan_->isUseBitSet(index);
  497. }
  498. int64_t DefaultPieceStorage::getTotalLength()
  499. {
  500. return bitfieldMan_->getTotalLength();
  501. }
  502. int64_t DefaultPieceStorage::getFilteredTotalLength()
  503. {
  504. return bitfieldMan_->getFilteredTotalLength();
  505. }
  506. int64_t DefaultPieceStorage::getCompletedLength()
  507. {
  508. int64_t completedLength =
  509. bitfieldMan_->getCompletedLength()+getInFlightPieceCompletedLength();
  510. int64_t totalLength = getTotalLength();
  511. if(completedLength > totalLength) {
  512. completedLength = totalLength;
  513. }
  514. return completedLength;
  515. }
  516. int64_t DefaultPieceStorage::getFilteredCompletedLength()
  517. {
  518. return bitfieldMan_->getFilteredCompletedLength()+
  519. getInFlightPieceFilteredCompletedLength();
  520. }
  521. int64_t DefaultPieceStorage::getInFlightPieceCompletedLength() const
  522. {
  523. int64_t len = 0;
  524. for(UsedPieceSet::const_iterator i = usedPieces_.begin(),
  525. eoi = usedPieces_.end(); i != eoi; ++i) {
  526. len += (*i)->getCompletedLength();
  527. }
  528. return len;
  529. }
  530. int64_t DefaultPieceStorage::getInFlightPieceFilteredCompletedLength() const
  531. {
  532. int64_t len = 0;
  533. for(UsedPieceSet::const_iterator i = usedPieces_.begin(),
  534. eoi = usedPieces_.end(); i != eoi; ++i) {
  535. if(bitfieldMan_->isFilterBitSet((*i)->getIndex())) {
  536. len += (*i)->getCompletedLength();
  537. }
  538. }
  539. return len;
  540. }
  541. // not unittested
  542. void DefaultPieceStorage::setupFileFilter()
  543. {
  544. const std::vector<std::shared_ptr<FileEntry> >& fileEntries =
  545. downloadContext_->getFileEntries();
  546. bool allSelected = true;
  547. for(std::vector<std::shared_ptr<FileEntry> >::const_iterator i =
  548. fileEntries.begin(), eoi = fileEntries.end();
  549. i != eoi; ++i) {
  550. if(!(*i)->isRequested()) {
  551. allSelected = false;
  552. break;
  553. }
  554. }
  555. if(allSelected) {
  556. return;
  557. }
  558. for(std::vector<std::shared_ptr<FileEntry> >::const_iterator i =
  559. fileEntries.begin(), eoi = fileEntries.end(); i != eoi; ++i) {
  560. if((*i)->isRequested()) {
  561. bitfieldMan_->addFilter((*i)->getOffset(), (*i)->getLength());
  562. }
  563. }
  564. bitfieldMan_->enableFilter();
  565. }
  566. // not unittested
  567. void DefaultPieceStorage::clearFileFilter()
  568. {
  569. bitfieldMan_->clearFilter();
  570. }
  571. // not unittested
  572. bool DefaultPieceStorage::downloadFinished()
  573. {
  574. // TODO iterate all requested FileEntry and Call
  575. // bitfieldMan->isBitSetOffsetRange()
  576. return bitfieldMan_->isFilteredAllBitSet();
  577. }
  578. // not unittested
  579. bool DefaultPieceStorage::allDownloadFinished()
  580. {
  581. return bitfieldMan_->isAllBitSet();
  582. }
  583. // not unittested
  584. void DefaultPieceStorage::initStorage()
  585. {
  586. if(downloadContext_->getFileEntries().size() == 1) {
  587. A2_LOG_DEBUG("Instantiating DirectDiskAdaptor");
  588. DirectDiskAdaptor* directDiskAdaptor(new DirectDiskAdaptor());
  589. directDiskAdaptor->setTotalLength(downloadContext_->getTotalLength());
  590. directDiskAdaptor->setFileEntries
  591. (downloadContext_->getFileEntries().begin(),
  592. downloadContext_->getFileEntries().end());
  593. std::shared_ptr<DiskWriter> writer =
  594. diskWriterFactory_->newDiskWriter(directDiskAdaptor->getFilePath());
  595. directDiskAdaptor->setDiskWriter(writer);
  596. diskAdaptor_.reset(directDiskAdaptor);
  597. } else {
  598. A2_LOG_DEBUG("Instantiating MultiDiskAdaptor");
  599. MultiDiskAdaptor* multiDiskAdaptor(new MultiDiskAdaptor());
  600. multiDiskAdaptor->setFileEntries(downloadContext_->getFileEntries().begin(),
  601. downloadContext_->getFileEntries().end());
  602. multiDiskAdaptor->setPieceLength(downloadContext_->getPieceLength());
  603. multiDiskAdaptor->setMaxOpenFiles
  604. (option_->getAsInt(PREF_BT_MAX_OPEN_FILES));
  605. diskAdaptor_.reset(multiDiskAdaptor);
  606. }
  607. if(option_->get(PREF_FILE_ALLOCATION) == V_FALLOC) {
  608. diskAdaptor_->setFileAllocationMethod(DiskAdaptor::FILE_ALLOC_FALLOC);
  609. } else if(option_->get(PREF_FILE_ALLOCATION) == V_TRUNC) {
  610. diskAdaptor_->setFileAllocationMethod(DiskAdaptor::FILE_ALLOC_TRUNC);
  611. }
  612. }
  613. void DefaultPieceStorage::setBitfield(const unsigned char* bitfield,
  614. size_t bitfieldLength)
  615. {
  616. bitfieldMan_->setBitfield(bitfield, bitfieldLength);
  617. addPieceStats(bitfield, bitfieldLength);
  618. }
  619. size_t DefaultPieceStorage::getBitfieldLength()
  620. {
  621. return bitfieldMan_->getBitfieldLength();
  622. }
  623. const unsigned char* DefaultPieceStorage::getBitfield()
  624. {
  625. return bitfieldMan_->getBitfield();
  626. }
  627. std::shared_ptr<DiskAdaptor> DefaultPieceStorage::getDiskAdaptor() {
  628. return diskAdaptor_;
  629. }
  630. WrDiskCache* DefaultPieceStorage::getWrDiskCache()
  631. {
  632. return wrDiskCache_;
  633. }
  634. void DefaultPieceStorage::flushWrDiskCacheEntry()
  635. {
  636. if(!wrDiskCache_) {
  637. return;
  638. }
  639. // UsedPieceSet is sorted by piece index. It means we can flush
  640. // cache by non-decreasing offset, which is good to reduce disk seek
  641. // unless the file is heavily fragmented.
  642. for(UsedPieceSet::const_iterator i = usedPieces_.begin(),
  643. eoi = usedPieces_.end(); i != eoi; ++i) {
  644. WrDiskCacheEntry* ce = (*i)->getWrDiskCacheEntry();
  645. if(ce) {
  646. (*i)->flushWrCache(wrDiskCache_);
  647. (*i)->releaseWrCache(wrDiskCache_);
  648. }
  649. }
  650. }
  651. int32_t DefaultPieceStorage::getPieceLength(size_t index)
  652. {
  653. return bitfieldMan_->getBlockLength(index);
  654. }
  655. void DefaultPieceStorage::advertisePiece(cuid_t cuid, size_t index)
  656. {
  657. HaveEntry entry(cuid, index, global::wallclock());
  658. haves_.push_front(entry);
  659. }
  660. void
  661. DefaultPieceStorage::getAdvertisedPieceIndexes(std::vector<size_t>& indexes,
  662. cuid_t myCuid,
  663. const Timer& lastCheckTime)
  664. {
  665. for(std::deque<HaveEntry>::const_iterator itr = haves_.begin(),
  666. eoi = haves_.end(); itr != eoi; ++itr) {
  667. const HaveEntry& have = *itr;
  668. if(lastCheckTime > have.getRegisteredTime()) {
  669. break;
  670. }
  671. indexes.push_back(have.getIndex());
  672. }
  673. }
  674. namespace {
  675. class FindElapsedHave
  676. {
  677. private:
  678. time_t elapsed;
  679. public:
  680. FindElapsedHave(time_t elapsed):elapsed(elapsed) {}
  681. bool operator()(const HaveEntry& have) {
  682. if(have.getRegisteredTime().difference(global::wallclock()) >= elapsed) {
  683. return true;
  684. } else {
  685. return false;
  686. }
  687. }
  688. };
  689. } // namespace
  690. void DefaultPieceStorage::removeAdvertisedPiece(time_t elapsed)
  691. {
  692. std::deque<HaveEntry>::iterator itr =
  693. std::find_if(haves_.begin(), haves_.end(), FindElapsedHave(elapsed));
  694. if(itr != haves_.end()) {
  695. A2_LOG_DEBUG(fmt(MSG_REMOVED_HAVE_ENTRY,
  696. static_cast<unsigned long>(haves_.end()-itr)));
  697. haves_.erase(itr, haves_.end());
  698. }
  699. }
  700. void DefaultPieceStorage::markAllPiecesDone()
  701. {
  702. bitfieldMan_->setAllBit();
  703. }
  704. void DefaultPieceStorage::markPiecesDone(int64_t length)
  705. {
  706. if(length == bitfieldMan_->getTotalLength()) {
  707. bitfieldMan_->setAllBit();
  708. } else if(length == 0) {
  709. // TODO this would go to markAllPiecesUndone()
  710. bitfieldMan_->clearAllBit();
  711. usedPieces_.clear();
  712. } else {
  713. size_t numPiece = length/bitfieldMan_->getBlockLength();
  714. if(numPiece > 0) {
  715. bitfieldMan_->setBitRange(0, numPiece-1);
  716. }
  717. size_t r = (length%bitfieldMan_->getBlockLength())/Piece::BLOCK_LENGTH;
  718. if(r > 0) {
  719. std::shared_ptr<Piece> p
  720. (new Piece(numPiece, bitfieldMan_->getBlockLength(numPiece)));
  721. for(size_t i = 0; i < r; ++i) {
  722. p->completeBlock(i);
  723. }
  724. #ifdef ENABLE_MESSAGE_DIGEST
  725. p->setHashType(downloadContext_->getPieceHashType());
  726. #endif // ENABLE_MESSAGE_DIGEST
  727. addUsedPiece(p);
  728. }
  729. }
  730. }
  731. void DefaultPieceStorage::markPieceMissing(size_t index)
  732. {
  733. bitfieldMan_->unsetBit(index);
  734. }
  735. void DefaultPieceStorage::addInFlightPiece
  736. (const std::vector<std::shared_ptr<Piece> >& pieces)
  737. {
  738. usedPieces_.insert(pieces.begin(), pieces.end());
  739. }
  740. size_t DefaultPieceStorage::countInFlightPiece()
  741. {
  742. return usedPieces_.size();
  743. }
  744. void DefaultPieceStorage::getInFlightPieces
  745. (std::vector<std::shared_ptr<Piece> >& pieces)
  746. {
  747. pieces.insert(pieces.end(), usedPieces_.begin(), usedPieces_.end());
  748. }
  749. void DefaultPieceStorage::setDiskWriterFactory
  750. (const std::shared_ptr<DiskWriterFactory>& diskWriterFactory)
  751. {
  752. diskWriterFactory_ = diskWriterFactory;
  753. }
  754. void DefaultPieceStorage::addPieceStats(const unsigned char* bitfield,
  755. size_t bitfieldLength)
  756. {
  757. pieceStatMan_->addPieceStats(bitfield, bitfieldLength);
  758. }
  759. void DefaultPieceStorage::subtractPieceStats(const unsigned char* bitfield,
  760. size_t bitfieldLength)
  761. {
  762. pieceStatMan_->subtractPieceStats(bitfield, bitfieldLength);
  763. }
  764. void DefaultPieceStorage::updatePieceStats(const unsigned char* newBitfield,
  765. size_t newBitfieldLength,
  766. const unsigned char* oldBitfield)
  767. {
  768. pieceStatMan_->updatePieceStats(newBitfield, newBitfieldLength,
  769. oldBitfield);
  770. }
  771. void DefaultPieceStorage::addPieceStats(size_t index)
  772. {
  773. pieceStatMan_->addPieceStats(index);
  774. }
  775. size_t DefaultPieceStorage::getNextUsedIndex(size_t index)
  776. {
  777. for(size_t i = index+1; i < bitfieldMan_->countBlock(); ++i) {
  778. if(bitfieldMan_->isUseBitSet(i) || bitfieldMan_->isBitSet(i)) {
  779. return i;
  780. }
  781. }
  782. return bitfieldMan_->countBlock();
  783. }
  784. void DefaultPieceStorage::onDownloadIncomplete()
  785. {
  786. streamPieceSelector_->onBitfieldInit();
  787. }
  788. } // namespace aria2