DefaultPieceStorage.cc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  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 "DownloadContext.h"
  37. #include "Piece.h"
  38. #include "Peer.h"
  39. #include "LogFactory.h"
  40. #include "Logger.h"
  41. #include "prefs.h"
  42. #include "DirectDiskAdaptor.h"
  43. #include "MultiDiskAdaptor.h"
  44. #include "CopyDiskAdaptor.h"
  45. #include "DiskWriter.h"
  46. #include "BitfieldManFactory.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 <numeric>
  56. #include <algorithm>
  57. namespace aria2 {
  58. DefaultPieceStorage::DefaultPieceStorage(const DownloadContextHandle& downloadContext, const Option* option):
  59. downloadContext(downloadContext),
  60. diskAdaptor(0),
  61. _diskWriterFactory(new DefaultDiskWriterFactory()),
  62. endGamePieceNum(END_GAME_PIECE_NUM),
  63. option(option)
  64. {
  65. bitfieldMan =
  66. BitfieldManFactory::getFactoryInstance()->
  67. createBitfieldMan(downloadContext->getPieceLength(),
  68. downloadContext->getTotalLength());
  69. logger = LogFactory::getInstance();
  70. }
  71. DefaultPieceStorage::~DefaultPieceStorage() {
  72. delete bitfieldMan;
  73. }
  74. bool DefaultPieceStorage::hasMissingPiece(const PeerHandle& peer)
  75. {
  76. return bitfieldMan->hasMissingPiece(peer->getBitfield(),
  77. peer->getBitfieldLength());
  78. }
  79. bool DefaultPieceStorage::isEndGame()
  80. {
  81. return bitfieldMan->countMissingBlock() <= endGamePieceNum;
  82. }
  83. bool DefaultPieceStorage::getMissingPieceIndex(size_t& index, const PeerHandle& peer)
  84. {
  85. if(isEndGame()) {
  86. return bitfieldMan->getMissingIndex(index, peer->getBitfield(),
  87. peer->getBitfieldLength());
  88. } else {
  89. return bitfieldMan->getMissingUnusedIndex(index, peer->getBitfield(),
  90. peer->getBitfieldLength());
  91. }
  92. }
  93. PieceHandle DefaultPieceStorage::checkOutPiece(size_t index)
  94. {
  95. bitfieldMan->setUseBit(index);
  96. PieceHandle piece = findUsedPiece(index);
  97. if(piece.isNull()) {
  98. piece = new Piece(index, bitfieldMan->getBlockLength(index));
  99. addUsedPiece(piece);
  100. return piece;
  101. } else {
  102. return piece;
  103. }
  104. }
  105. /**
  106. * Newly instantiated piece is not added to usedPieces.
  107. * Because it is waste of memory and there is no chance to use them later.
  108. */
  109. PieceHandle DefaultPieceStorage::getPiece(size_t index)
  110. {
  111. if(0 <= index && index <= bitfieldMan->getMaxIndex()) {
  112. PieceHandle piece = findUsedPiece(index);
  113. if(piece.isNull()) {
  114. piece = new Piece(index, bitfieldMan->getBlockLength(index));
  115. if(hasPiece(index)) {
  116. piece->setAllBlock();
  117. }
  118. }
  119. return piece;
  120. } else {
  121. return 0;
  122. }
  123. }
  124. void DefaultPieceStorage::addUsedPiece(const PieceHandle& piece)
  125. {
  126. usedPieces.push_back(piece);
  127. }
  128. class FindPiece {
  129. private:
  130. size_t index;
  131. public:
  132. FindPiece(size_t index):index(index) {}
  133. bool operator()(const PieceHandle& piece) {
  134. return piece->getIndex() == index;
  135. }
  136. };
  137. PieceHandle DefaultPieceStorage::findUsedPiece(size_t index) const
  138. {
  139. Pieces::const_iterator itr = std::find_if(usedPieces.begin(),
  140. usedPieces.end(),
  141. FindPiece(index));
  142. if(itr == usedPieces.end()) {
  143. return 0;
  144. } else {
  145. return *itr;
  146. }
  147. }
  148. PieceHandle DefaultPieceStorage::getMissingPiece(const PeerHandle& peer)
  149. {
  150. size_t index;
  151. if(getMissingPieceIndex(index, peer)) {
  152. return checkOutPiece(index);
  153. } else {
  154. return 0;
  155. }
  156. }
  157. bool DefaultPieceStorage::getMissingFastPieceIndex(size_t& index,
  158. const PeerHandle& peer)
  159. {
  160. if(peer->isFastExtensionEnabled() && peer->countPeerAllowedIndexSet() > 0) {
  161. BitfieldMan tempBitfield(bitfieldMan->getBlockLength(),
  162. bitfieldMan->getTotalLength());
  163. for(std::deque<size_t>::const_iterator itr = peer->getPeerAllowedIndexSet().begin();
  164. itr != peer->getPeerAllowedIndexSet().end(); itr++) {
  165. if(!bitfieldMan->isBitSet(index) && peer->hasPiece(*itr)) {
  166. tempBitfield.setBit(*itr);
  167. }
  168. }
  169. if(isEndGame()) {
  170. return bitfieldMan->getMissingIndex(index, tempBitfield.getBitfield(),
  171. tempBitfield.getBitfieldLength());
  172. } else {
  173. return bitfieldMan->getMissingUnusedIndex(index,
  174. tempBitfield.getBitfield(),
  175. tempBitfield.getBitfieldLength());
  176. }
  177. }
  178. return false;
  179. }
  180. PieceHandle DefaultPieceStorage::getMissingFastPiece(const PeerHandle& peer)
  181. {
  182. size_t index;
  183. if(getMissingFastPieceIndex(index, peer)) {
  184. return checkOutPiece(index);
  185. } else {
  186. return 0;
  187. }
  188. }
  189. PieceHandle DefaultPieceStorage::getMissingPiece()
  190. {
  191. size_t index;
  192. if(bitfieldMan->getSparseMissingUnusedIndex(index)) {
  193. return checkOutPiece(index);
  194. } else {
  195. return 0;
  196. }
  197. }
  198. PieceHandle DefaultPieceStorage::getMissingPiece(size_t index)
  199. {
  200. if(hasPiece(index) || isPieceUsed(index)) {
  201. return 0;
  202. } else {
  203. return checkOutPiece(index);
  204. }
  205. }
  206. void DefaultPieceStorage::deleteUsedPiece(const PieceHandle& piece)
  207. {
  208. if(piece.isNull()) {
  209. return;
  210. }
  211. Pieces::iterator itr = std::find(usedPieces.begin(), usedPieces.end(), piece);
  212. if(itr != usedPieces.end()) {
  213. usedPieces.erase(itr);
  214. }
  215. }
  216. void DefaultPieceStorage::reduceUsedPieces(size_t delMax)
  217. {
  218. if(usedPieces.size() <= delMax) {
  219. return;
  220. }
  221. size_t toDelete = usedPieces.size()-delMax;
  222. int fillRate = 10;
  223. while(fillRate < 50) {
  224. size_t deleted = deleteUsedPiecesByFillRate(fillRate, toDelete);
  225. if(deleted == 0) {
  226. break;
  227. }
  228. toDelete -= deleted;
  229. fillRate += 10;
  230. }
  231. }
  232. size_t DefaultPieceStorage::deleteUsedPiecesByFillRate(int fillRate,
  233. size_t toDelete)
  234. {
  235. size_t deleted = 0;
  236. for(Pieces::iterator itr = usedPieces.begin();
  237. itr != usedPieces.end() && deleted < toDelete;) {
  238. PieceHandle& piece = *itr;
  239. if(!bitfieldMan->isUseBitSet(piece->getIndex()) &&
  240. piece->countCompleteBlock() <= piece->countBlock()*(fillRate/100.0)) {
  241. logger->debug(MSG_DELETING_USED_PIECE,
  242. piece->getIndex(),
  243. (piece->countCompleteBlock()*100)/piece->countBlock(),
  244. fillRate);
  245. itr = usedPieces.erase(itr);
  246. deleted++;
  247. } else {
  248. itr++;
  249. }
  250. }
  251. return deleted;
  252. }
  253. void DefaultPieceStorage::completePiece(const PieceHandle& piece)
  254. {
  255. if(piece.isNull()) {
  256. return;
  257. }
  258. deleteUsedPiece(piece);
  259. if(!isEndGame()) {
  260. reduceUsedPieces(100);
  261. }
  262. if(allDownloadFinished()) {
  263. return;
  264. }
  265. bitfieldMan->setBit(piece->getIndex());
  266. bitfieldMan->unsetUseBit(piece->getIndex());
  267. if(downloadFinished()) {
  268. diskAdaptor->onDownloadComplete();
  269. if(isSelectiveDownloadingMode()) {
  270. logger->notice(MSG_SELECTIVE_DOWNLOAD_COMPLETED);
  271. // following line was commented out in order to stop sending request
  272. // message after user-specified files were downloaded.
  273. //finishSelectiveDownloadingMode();
  274. } else {
  275. logger->info(MSG_DOWNLOAD_COMPLETED);
  276. }
  277. }
  278. }
  279. bool DefaultPieceStorage::isSelectiveDownloadingMode()
  280. {
  281. return bitfieldMan->isFilterEnabled();
  282. }
  283. void DefaultPieceStorage::finishSelectiveDownloadingMode()
  284. {
  285. bitfieldMan->clearFilter();
  286. diskAdaptor->addAllDownloadEntry();
  287. }
  288. // not unittested
  289. void DefaultPieceStorage::cancelPiece(const PieceHandle& piece)
  290. {
  291. if(piece.isNull()) {
  292. return;
  293. }
  294. bitfieldMan->unsetUseBit(piece->getIndex());
  295. if(!isEndGame()) {
  296. if(piece->getCompletedLength() == 0) {
  297. deleteUsedPiece(piece);
  298. }
  299. }
  300. }
  301. bool DefaultPieceStorage::hasPiece(size_t index)
  302. {
  303. return bitfieldMan->isBitSet(index);
  304. }
  305. bool DefaultPieceStorage::isPieceUsed(size_t index)
  306. {
  307. return bitfieldMan->isUseBitSet(index);
  308. }
  309. uint64_t DefaultPieceStorage::getTotalLength()
  310. {
  311. return bitfieldMan->getTotalLength();
  312. }
  313. uint64_t DefaultPieceStorage::getFilteredTotalLength()
  314. {
  315. return bitfieldMan->getFilteredTotalLength();
  316. }
  317. uint64_t DefaultPieceStorage::getCompletedLength()
  318. {
  319. return bitfieldMan->getCompletedLength()+getInFlightPieceCompletedLength();
  320. }
  321. uint64_t DefaultPieceStorage::getFilteredCompletedLength()
  322. {
  323. return bitfieldMan->getFilteredCompletedLength()+getInFlightPieceCompletedLength();
  324. }
  325. size_t DefaultPieceStorage::getInFlightPieceCompletedLength() const
  326. {
  327. return std::accumulate(usedPieces.begin(), usedPieces.end(), 0, adopt2nd(std::plus<size_t>(), mem_fun_sh(&Piece::getCompletedLength)));
  328. }
  329. // not unittested
  330. void DefaultPieceStorage::setFileFilter(const std::deque<std::string>& filePaths)
  331. {
  332. if(downloadContext->getFileMode() != DownloadContext::MULTI || filePaths.empty()) {
  333. return;
  334. }
  335. diskAdaptor->removeAllDownloadEntry();
  336. for(std::deque<std::string>::const_iterator pitr = filePaths.begin();
  337. pitr != filePaths.end(); pitr++) {
  338. if(!diskAdaptor->addDownloadEntry(*pitr)) {
  339. throw new DlAbortEx(EX_NO_SUCH_FILE_ENTRY, (*pitr).c_str());
  340. }
  341. FileEntryHandle fileEntry = diskAdaptor->getFileEntryFromPath(*pitr);
  342. bitfieldMan->addFilter(fileEntry->getOffset(), fileEntry->getLength());
  343. }
  344. bitfieldMan->enableFilter();
  345. }
  346. void DefaultPieceStorage::setFileFilter(IntSequence seq)
  347. {
  348. std::deque<int32_t> fileIndexes = seq.flush();
  349. // TODO Is sorting necessary?
  350. std::sort(fileIndexes.begin(), fileIndexes.end());
  351. fileIndexes.erase(std::unique(fileIndexes.begin(), fileIndexes.end()), fileIndexes.end());
  352. std::deque<std::string> filePaths;
  353. const FileEntries& entries = diskAdaptor->getFileEntries();
  354. for(size_t i = 0; i < entries.size(); i++) {
  355. if(std::find(fileIndexes.begin(), fileIndexes.end(), i+1) != fileIndexes.end()) {
  356. logger->debug("index=%d is %s", i+1, entries[i]->getPath().c_str());
  357. filePaths.push_back(entries[i]->getPath());
  358. }
  359. }
  360. setFileFilter(filePaths);
  361. }
  362. // not unittested
  363. void DefaultPieceStorage::clearFileFilter()
  364. {
  365. bitfieldMan->clearFilter();
  366. diskAdaptor->addAllDownloadEntry();
  367. }
  368. // not unittested
  369. bool DefaultPieceStorage::downloadFinished()
  370. {
  371. // TODO iterate all requested FileEntry and Call bitfieldMan->isBitSetOffsetRange()
  372. return bitfieldMan->isFilteredAllBitSet();
  373. }
  374. // not unittested
  375. bool DefaultPieceStorage::allDownloadFinished()
  376. {
  377. return bitfieldMan->isAllBitSet();
  378. }
  379. // not unittested
  380. void DefaultPieceStorage::initStorage()
  381. {
  382. if(downloadContext->getFileMode() == DownloadContext::SINGLE) {
  383. logger->debug("Instantiating DirectDiskAdaptor");
  384. DiskWriterHandle writer = _diskWriterFactory->newDiskWriter();
  385. writer->setDirectIOAllowed(option->getAsBool(PREF_ENABLE_DIRECT_IO));
  386. DirectDiskAdaptorHandle directDiskAdaptor = new DirectDiskAdaptor();
  387. directDiskAdaptor->setDiskWriter(writer);
  388. directDiskAdaptor->setTotalLength(downloadContext->getTotalLength());
  389. this->diskAdaptor = directDiskAdaptor;
  390. } else {
  391. // file mode == DownloadContext::MULTI
  392. if(option->get(PREF_DIRECT_FILE_MAPPING) == V_TRUE) {
  393. logger->debug("Instantiating MultiDiskAdaptor");
  394. MultiDiskAdaptorHandle multiDiskAdaptor = new MultiDiskAdaptor();
  395. multiDiskAdaptor->setDirectIOAllowed(option->getAsBool(PREF_ENABLE_DIRECT_IO));
  396. multiDiskAdaptor->setPieceLength(downloadContext->getPieceLength());
  397. multiDiskAdaptor->setTopDir(downloadContext->getName());
  398. this->diskAdaptor = multiDiskAdaptor;
  399. } else {
  400. logger->debug("Instantiating CopyDiskAdaptor");
  401. DiskWriterHandle writer = _diskWriterFactory->newDiskWriter();
  402. writer->setDirectIOAllowed(option->getAsBool(PREF_ENABLE_DIRECT_IO));
  403. CopyDiskAdaptorHandle copyDiskAdaptor = new CopyDiskAdaptor();
  404. copyDiskAdaptor->setDiskWriter(writer);
  405. copyDiskAdaptor->setTempFilename(downloadContext->getName()+".a2tmp");
  406. copyDiskAdaptor->setTotalLength(downloadContext->getTotalLength());
  407. if(downloadContext->getFileMode() == DownloadContext::MULTI) {
  408. copyDiskAdaptor->setTopDir(downloadContext->getName());
  409. }
  410. this->diskAdaptor = copyDiskAdaptor;
  411. }
  412. }
  413. diskAdaptor->setStoreDir(downloadContext->getDir());
  414. diskAdaptor->setFileEntries(downloadContext->getFileEntries());
  415. }
  416. void DefaultPieceStorage::setBitfield(const unsigned char* bitfield,
  417. size_t bitfieldLength)
  418. {
  419. bitfieldMan->setBitfield(bitfield, bitfieldLength);
  420. }
  421. size_t DefaultPieceStorage::getBitfieldLength()
  422. {
  423. return bitfieldMan->getBitfieldLength();
  424. }
  425. const unsigned char* DefaultPieceStorage::getBitfield()
  426. {
  427. return bitfieldMan->getBitfield();
  428. }
  429. DiskAdaptorHandle DefaultPieceStorage::getDiskAdaptor() {
  430. return diskAdaptor;
  431. }
  432. size_t DefaultPieceStorage::getPieceLength(size_t index)
  433. {
  434. return bitfieldMan->getBlockLength(index);
  435. }
  436. void DefaultPieceStorage::advertisePiece(int32_t cuid, size_t index)
  437. {
  438. HaveEntry entry(cuid, index);
  439. haves.push_front(entry);
  440. }
  441. std::deque<size_t>
  442. DefaultPieceStorage::getAdvertisedPieceIndexes(int32_t myCuid,
  443. const Time& lastCheckTime)
  444. {
  445. std::deque<size_t> indexes;
  446. for(Haves::const_iterator itr = haves.begin(); itr != haves.end(); itr++) {
  447. const Haves::value_type& have = *itr;
  448. if(have.getCuid() == myCuid) {
  449. continue;
  450. }
  451. if(lastCheckTime.isNewer(have.getRegisteredTime())) {
  452. break;
  453. }
  454. indexes.push_back(have.getIndex());
  455. }
  456. return indexes;
  457. }
  458. class FindElapsedHave
  459. {
  460. private:
  461. time_t elapsed;
  462. public:
  463. FindElapsedHave(time_t elapsed):elapsed(elapsed) {}
  464. bool operator()(const HaveEntry& have) {
  465. if(have.getRegisteredTime().elapsed(elapsed)) {
  466. return true;
  467. } else {
  468. return false;
  469. }
  470. }
  471. };
  472. void DefaultPieceStorage::removeAdvertisedPiece(time_t elapsed)
  473. {
  474. Haves::iterator itr =
  475. std::find_if(haves.begin(), haves.end(), FindElapsedHave(elapsed));
  476. if(itr != haves.end()) {
  477. logger->debug(MSG_REMOVED_HAVE_ENTRY, haves.end()-itr);
  478. haves.erase(itr, haves.end());
  479. }
  480. }
  481. void DefaultPieceStorage::markAllPiecesDone()
  482. {
  483. bitfieldMan->setAllBit();
  484. }
  485. void DefaultPieceStorage::markPiecesDone(uint64_t length)
  486. {
  487. if(length == bitfieldMan->getTotalLength()) {
  488. bitfieldMan->setAllBit();
  489. } else {
  490. size_t numPiece = length/bitfieldMan->getBlockLength();
  491. if(numPiece > 0) {
  492. bitfieldMan->setBitRange(0, numPiece-1);
  493. }
  494. size_t r = (length%bitfieldMan->getBlockLength())/Piece::BLOCK_LENGTH;
  495. if(r > 0) {
  496. PieceHandle p = new Piece(numPiece, bitfieldMan->getBlockLength(numPiece));
  497. for(size_t i = 0; i < r; ++i) {
  498. p->completeBlock(i);
  499. }
  500. addUsedPiece(p);
  501. }
  502. }
  503. }
  504. void DefaultPieceStorage::markPieceMissing(size_t index)
  505. {
  506. bitfieldMan->unsetBit(index);
  507. }
  508. void DefaultPieceStorage::addInFlightPiece(const Pieces& pieces)
  509. {
  510. std::copy(pieces.begin(), pieces.end(), std::back_inserter(usedPieces));
  511. }
  512. size_t DefaultPieceStorage::countInFlightPiece()
  513. {
  514. return usedPieces.size();
  515. }
  516. Pieces DefaultPieceStorage::getInFlightPieces()
  517. {
  518. return usedPieces;
  519. }
  520. void DefaultPieceStorage::setDiskWriterFactory(const DiskWriterFactoryHandle& diskWriterFactory)
  521. {
  522. _diskWriterFactory = diskWriterFactory;
  523. }
  524. } // namespace aria2