DefaultPieceStorage.cc 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  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->countFastSet() > 0) {
  156. BitfieldMan tempBitfield(bitfieldMan->getBlockLength(),
  157. bitfieldMan->getTotalLength());
  158. for(Integers::const_iterator itr = peer->getFastSet().begin();
  159. itr != peer->getFastSet().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. sort(fileIndexes.begin(), fileIndexes.end());
  363. fileIndexes.erase(unique(fileIndexes.begin(), fileIndexes.end()), fileIndexes.end());
  364. Strings filePaths;
  365. const FileEntries& entries = diskAdaptor->getFileEntries();
  366. for(int32_t i = 0; i < (int32_t)entries.size(); i++) {
  367. if(find(fileIndexes.begin(), fileIndexes.end(), i+1) != fileIndexes.end()) {
  368. logger->debug("index=%d is %s", i+1, entries[i]->getPath().c_str());
  369. filePaths.push_back(entries[i]->getPath());
  370. }
  371. }
  372. setFileFilter(filePaths);
  373. }
  374. // not unittested
  375. void DefaultPieceStorage::clearFileFilter()
  376. {
  377. bitfieldMan->clearFilter();
  378. diskAdaptor->addAllDownloadEntry();
  379. }
  380. // not unittested
  381. bool DefaultPieceStorage::downloadFinished()
  382. {
  383. // TODO iterate all requested FileEntry and Call bitfieldMan->isBitSetOffsetRange()
  384. return bitfieldMan->isFilteredAllBitSet();
  385. }
  386. // not unittested
  387. bool DefaultPieceStorage::allDownloadFinished()
  388. {
  389. return bitfieldMan->isAllBitSet();
  390. }
  391. // not unittested
  392. void DefaultPieceStorage::initStorage()
  393. {
  394. if(downloadContext->getFileMode() == DownloadContext::SINGLE) {
  395. logger->debug("Instantiating DirectDiskAdaptor");
  396. DiskWriterHandle writer = _diskWriterFactory->newDiskWriter();
  397. DirectDiskAdaptorHandle directDiskAdaptor = new DirectDiskAdaptor();
  398. directDiskAdaptor->setDiskWriter(writer);
  399. directDiskAdaptor->setTotalLength(downloadContext->getTotalLength());
  400. this->diskAdaptor = directDiskAdaptor;
  401. } else {
  402. // file mode == DownloadContext::MULTI
  403. if(option->get(PREF_DIRECT_FILE_MAPPING) == V_TRUE) {
  404. logger->debug("Instantiating MultiDiskAdaptor");
  405. MultiDiskAdaptorHandle multiDiskAdaptor = new MultiDiskAdaptor();
  406. multiDiskAdaptor->setPieceLength(downloadContext->getPieceLength());
  407. multiDiskAdaptor->setTopDir(downloadContext->getName());
  408. this->diskAdaptor = multiDiskAdaptor;
  409. } else {
  410. logger->debug("Instantiating CopyDiskAdaptor");
  411. DiskWriterHandle writer = _diskWriterFactory->newDiskWriter();
  412. CopyDiskAdaptorHandle copyDiskAdaptor = new CopyDiskAdaptor();
  413. copyDiskAdaptor->setDiskWriter(writer);
  414. copyDiskAdaptor->setTempFilename(downloadContext->getName()+".a2tmp");
  415. copyDiskAdaptor->setTotalLength(downloadContext->getTotalLength());
  416. if(downloadContext->getFileMode() == DownloadContext::MULTI) {
  417. copyDiskAdaptor->setTopDir(downloadContext->getName());
  418. }
  419. this->diskAdaptor = copyDiskAdaptor;
  420. }
  421. }
  422. diskAdaptor->setStoreDir(downloadContext->getDir());
  423. diskAdaptor->setFileEntries(downloadContext->getFileEntries());
  424. }
  425. void DefaultPieceStorage::setBitfield(const unsigned char* bitfield,
  426. int32_t bitfieldLength)
  427. {
  428. bitfieldMan->setBitfield(bitfield, bitfieldLength);
  429. }
  430. int32_t DefaultPieceStorage::getBitfieldLength()
  431. {
  432. return bitfieldMan->getBitfieldLength();
  433. }
  434. const unsigned char* DefaultPieceStorage::getBitfield()
  435. {
  436. return bitfieldMan->getBitfield();
  437. }
  438. DiskAdaptorHandle DefaultPieceStorage::getDiskAdaptor() {
  439. return diskAdaptor;
  440. }
  441. int32_t DefaultPieceStorage::getPieceLength(int32_t index)
  442. {
  443. return bitfieldMan->getBlockLength(index);
  444. }
  445. void DefaultPieceStorage::advertisePiece(int32_t cuid, int32_t index)
  446. {
  447. HaveEntry entry(cuid, index);
  448. haves.push_front(entry);
  449. }
  450. Integers DefaultPieceStorage::getAdvertisedPieceIndexes(int32_t myCuid,
  451. const Time& lastCheckTime)
  452. {
  453. Integers indexes;
  454. for(Haves::const_iterator itr = haves.begin(); itr != haves.end(); itr++) {
  455. const Haves::value_type& have = *itr;
  456. if(have.getCuid() == myCuid) {
  457. continue;
  458. }
  459. if(lastCheckTime.isNewer(have.getRegisteredTime())) {
  460. break;
  461. }
  462. indexes.push_back(have.getIndex());
  463. }
  464. return indexes;
  465. }
  466. class FindElapsedHave
  467. {
  468. private:
  469. int32_t elapsed;
  470. public:
  471. FindElapsedHave(int32_t elapsed):elapsed(elapsed) {}
  472. bool operator()(const HaveEntry& have) {
  473. if(have.getRegisteredTime().elapsed(elapsed)) {
  474. return true;
  475. } else {
  476. return false;
  477. }
  478. }
  479. };
  480. void DefaultPieceStorage::removeAdvertisedPiece(int32_t elapsed)
  481. {
  482. Haves::iterator itr =
  483. find_if(haves.begin(), haves.end(), FindElapsedHave(elapsed));
  484. if(itr != haves.end()) {
  485. logger->debug(MSG_REMOVED_HAVE_ENTRY, haves.end()-itr);
  486. haves.erase(itr, haves.end());
  487. }
  488. }
  489. void DefaultPieceStorage::markAllPiecesDone()
  490. {
  491. bitfieldMan->setAllBit();
  492. }
  493. void DefaultPieceStorage::markPiecesDone(int64_t length)
  494. {
  495. if(length == bitfieldMan->getTotalLength()) {
  496. bitfieldMan->setAllBit();
  497. } else {
  498. int32_t numPiece = length/bitfieldMan->getBlockLength();
  499. if(numPiece > 0) {
  500. bitfieldMan->setBitRange(0, numPiece-1);
  501. }
  502. int32_t r = (length%bitfieldMan->getBlockLength())/Piece::BLOCK_LENGTH;
  503. if(r > 0) {
  504. PieceHandle p = new Piece(numPiece, bitfieldMan->getBlockLength(numPiece));
  505. for(int32_t i = 0; i < r; ++i) {
  506. p->completeBlock(i);
  507. }
  508. addUsedPiece(p);
  509. }
  510. }
  511. }
  512. void DefaultPieceStorage::markPieceMissing(int32_t index)
  513. {
  514. bitfieldMan->unsetBit(index);
  515. }
  516. void DefaultPieceStorage::addInFlightPiece(const Pieces& pieces)
  517. {
  518. copy(pieces.begin(), pieces.end(), back_inserter(usedPieces));
  519. }
  520. int32_t DefaultPieceStorage::countInFlightPiece()
  521. {
  522. return usedPieces.size();
  523. }
  524. Pieces DefaultPieceStorage::getInFlightPieces()
  525. {
  526. return usedPieces;
  527. }
  528. void DefaultPieceStorage::setDiskWriterFactory(const DiskWriterFactoryHandle& diskWriterFactory)
  529. {
  530. _diskWriterFactory = diskWriterFactory;
  531. }