DefaultPieceStorage.cc 17 KB

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