RequestGroupMan.cc 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997
  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 "RequestGroupMan.h"
  36. #include <unistd.h>
  37. #include <cstring>
  38. #include <iomanip>
  39. #include <sstream>
  40. #include <numeric>
  41. #include <algorithm>
  42. #include <utility>
  43. #include "BtProgressInfoFile.h"
  44. #include "RecoverableException.h"
  45. #include "RequestGroup.h"
  46. #include "LogFactory.h"
  47. #include "Logger.h"
  48. #include "DownloadEngine.h"
  49. #include "message.h"
  50. #include "a2functional.h"
  51. #include "DownloadResult.h"
  52. #include "DownloadContext.h"
  53. #include "ServerStatMan.h"
  54. #include "ServerStat.h"
  55. #include "SegmentMan.h"
  56. #include "FeedbackURISelector.h"
  57. #include "InorderURISelector.h"
  58. #include "AdaptiveURISelector.h"
  59. #include "Option.h"
  60. #include "prefs.h"
  61. #include "File.h"
  62. #include "util.h"
  63. #include "Command.h"
  64. #include "FileEntry.h"
  65. #include "fmt.h"
  66. #include "FileAllocationEntry.h"
  67. #include "CheckIntegrityEntry.h"
  68. #include "Segment.h"
  69. #include "DlAbortEx.h"
  70. #include "uri.h"
  71. #include "Signature.h"
  72. #include "OutputFile.h"
  73. #include "download_helper.h"
  74. #include "UriListParser.h"
  75. #include "SingletonHolder.h"
  76. #include "Notifier.h"
  77. #include "PeerStat.h"
  78. #include "WrDiskCache.h"
  79. #include "PieceStorage.h"
  80. #include "DiskAdaptor.h"
  81. #include "SimpleRandomizer.h"
  82. #include "array_fun.h"
  83. #ifdef ENABLE_BITTORRENT
  84. # include "bittorrent_helper.h"
  85. #endif // ENABLE_BITTORRENT
  86. namespace aria2 {
  87. namespace {
  88. template<typename InputIterator>
  89. void appendReservedGroup(RequestGroupList& list,
  90. InputIterator first, InputIterator last)
  91. {
  92. for(; first != last; ++first) {
  93. list.push_back((*first)->getGID(), *first);
  94. }
  95. }
  96. } // namespace
  97. RequestGroupMan::RequestGroupMan
  98. (std::vector<std::shared_ptr<RequestGroup> > requestGroups,
  99. int maxSimultaneousDownloads,
  100. const Option* option)
  101. : maxSimultaneousDownloads_(maxSimultaneousDownloads),
  102. option_(option),
  103. serverStatMan_(new ServerStatMan()),
  104. maxOverallDownloadSpeedLimit_
  105. (option->getAsInt(PREF_MAX_OVERALL_DOWNLOAD_LIMIT)),
  106. maxOverallUploadSpeedLimit_(option->getAsInt
  107. (PREF_MAX_OVERALL_UPLOAD_LIMIT)),
  108. keepRunning_(option->getAsBool(PREF_ENABLE_RPC)),
  109. queueCheck_(true),
  110. removedErrorResult_(0),
  111. removedLastErrorResult_(error_code::FINISHED),
  112. maxDownloadResult_(option->getAsInt(PREF_MAX_DOWNLOAD_RESULT)),
  113. wrDiskCache_(nullptr),
  114. numOpenFile_(0),
  115. numStoppedTotal_(0)
  116. {
  117. appendReservedGroup(reservedGroups_,
  118. requestGroups.begin(), requestGroups.end());
  119. }
  120. RequestGroupMan::~RequestGroupMan()
  121. {
  122. delete wrDiskCache_;
  123. }
  124. bool RequestGroupMan::downloadFinished()
  125. {
  126. if(keepRunning_) {
  127. return false;
  128. }
  129. return requestGroups_.empty() && reservedGroups_.empty();
  130. }
  131. void RequestGroupMan::addRequestGroup
  132. (const std::shared_ptr<RequestGroup>& group)
  133. {
  134. requestGroups_.push_back(group->getGID(), group);
  135. }
  136. void RequestGroupMan::addReservedGroup
  137. (const std::vector<std::shared_ptr<RequestGroup> >& groups)
  138. {
  139. requestQueueCheck();
  140. appendReservedGroup(reservedGroups_, groups.begin(), groups.end());
  141. }
  142. void RequestGroupMan::addReservedGroup
  143. (const std::shared_ptr<RequestGroup>& group)
  144. {
  145. requestQueueCheck();
  146. reservedGroups_.push_back(group->getGID(), group);
  147. }
  148. namespace {
  149. struct RequestGroupKeyFunc {
  150. a2_gid_t operator()(const std::shared_ptr<RequestGroup>& rg) const
  151. {
  152. return rg->getGID();
  153. }
  154. };
  155. } // namespace
  156. void RequestGroupMan::insertReservedGroup
  157. (size_t pos, const std::vector<std::shared_ptr<RequestGroup> >& groups)
  158. {
  159. requestQueueCheck();
  160. pos = std::min(reservedGroups_.size(), pos);
  161. reservedGroups_.insert(pos, RequestGroupKeyFunc(),
  162. groups.begin(), groups.end());
  163. }
  164. void RequestGroupMan::insertReservedGroup
  165. (size_t pos, const std::shared_ptr<RequestGroup>& group)
  166. {
  167. requestQueueCheck();
  168. pos = std::min(reservedGroups_.size(), pos);
  169. reservedGroups_.insert(pos, group->getGID(), group);
  170. }
  171. size_t RequestGroupMan::countRequestGroup() const
  172. {
  173. return requestGroups_.size();
  174. }
  175. std::shared_ptr<RequestGroup> RequestGroupMan::findGroup(a2_gid_t gid) const
  176. {
  177. std::shared_ptr<RequestGroup> rg = requestGroups_.get(gid);
  178. if(!rg) {
  179. rg = reservedGroups_.get(gid);
  180. }
  181. return rg;
  182. }
  183. size_t RequestGroupMan::changeReservedGroupPosition
  184. (a2_gid_t gid, int pos, OffsetMode how)
  185. {
  186. ssize_t dest = reservedGroups_.move(gid, pos, how);
  187. if(dest == -1) {
  188. throw DL_ABORT_EX(fmt("GID#%s not found in the waiting queue.",
  189. GroupId::toHex(gid).c_str()));
  190. } else {
  191. return dest;
  192. }
  193. }
  194. bool RequestGroupMan::removeReservedGroup(a2_gid_t gid)
  195. {
  196. return reservedGroups_.remove(gid);
  197. }
  198. namespace {
  199. void notifyDownloadEvent
  200. (DownloadEvent event, const std::shared_ptr<RequestGroup>& group)
  201. {
  202. // Check NULL to make unit test easier.
  203. if(SingletonHolder<Notifier>::instance()) {
  204. SingletonHolder<Notifier>::instance()->notifyDownloadEvent(event, group);
  205. }
  206. }
  207. } // namespace
  208. namespace {
  209. void executeStopHook
  210. (const std::shared_ptr<RequestGroup>& group,
  211. const Option* option,
  212. error_code::Value result)
  213. {
  214. if(result == error_code::FINISHED &&
  215. !option->blank(PREF_ON_DOWNLOAD_COMPLETE)) {
  216. util::executeHookByOptName(group, option, PREF_ON_DOWNLOAD_COMPLETE);
  217. } else if(result != error_code::IN_PROGRESS &&
  218. result != error_code::REMOVED &&
  219. !option->blank(PREF_ON_DOWNLOAD_ERROR)) {
  220. util::executeHookByOptName(group, option, PREF_ON_DOWNLOAD_ERROR);
  221. } else if(!option->blank(PREF_ON_DOWNLOAD_STOP)) {
  222. util::executeHookByOptName(group, option, PREF_ON_DOWNLOAD_STOP);
  223. }
  224. if(result == error_code::FINISHED) {
  225. notifyDownloadEvent(EVENT_ON_DOWNLOAD_COMPLETE, group);
  226. } else if(result != error_code::IN_PROGRESS &&
  227. result != error_code::REMOVED) {
  228. notifyDownloadEvent(EVENT_ON_DOWNLOAD_ERROR, group);
  229. } else {
  230. notifyDownloadEvent(EVENT_ON_DOWNLOAD_STOP, group);
  231. }
  232. }
  233. } // namespace
  234. namespace {
  235. class ProcessStoppedRequestGroup {
  236. private:
  237. DownloadEngine* e_;
  238. RequestGroupList& reservedGroups_;
  239. void saveSignature(const std::shared_ptr<RequestGroup>& group)
  240. {
  241. auto& sig = group->getDownloadContext()->getSignature();
  242. if(sig && !sig->getBody().empty()) {
  243. // filename of signature file is the path to download file followed by
  244. // ".sig".
  245. std::string signatureFile = group->getFirstFilePath()+".sig";
  246. if(sig->save(signatureFile)) {
  247. A2_LOG_NOTICE(fmt(MSG_SIGNATURE_SAVED, signatureFile.c_str()));
  248. } else {
  249. A2_LOG_NOTICE(fmt(MSG_SIGNATURE_NOT_SAVED, signatureFile.c_str()));
  250. }
  251. }
  252. }
  253. // Collect statistics during download in PeerStats and update/register
  254. // ServerStatMan
  255. void collectStat(const std::shared_ptr<RequestGroup>& group)
  256. {
  257. if(group->getSegmentMan()) {
  258. bool singleConnection =
  259. group->getSegmentMan()->getPeerStats().size() == 1;
  260. const std::vector<std::shared_ptr<PeerStat> >& peerStats =
  261. group->getSegmentMan()->getFastestPeerStats();
  262. for(auto & stat : peerStats) {
  263. if(stat->getHostname().empty() || stat->getProtocol().empty()) {
  264. continue;
  265. }
  266. int speed = stat->getAvgDownloadSpeed();
  267. if (speed == 0) continue;
  268. std::shared_ptr<ServerStat> ss =
  269. e_->getRequestGroupMan()->getOrCreateServerStat(stat->getHostname(),
  270. stat->getProtocol());
  271. ss->increaseCounter();
  272. ss->updateDownloadSpeed(speed);
  273. if(singleConnection) {
  274. ss->updateSingleConnectionAvgSpeed(speed);
  275. }
  276. else {
  277. ss->updateMultiConnectionAvgSpeed(speed);
  278. }
  279. }
  280. }
  281. }
  282. public:
  283. ProcessStoppedRequestGroup
  284. (DownloadEngine* e,
  285. RequestGroupList& reservedGroups)
  286. : e_(e),
  287. reservedGroups_(reservedGroups)
  288. {}
  289. bool operator()(const RequestGroupList::value_type& group)
  290. {
  291. if(group->getNumCommand() == 0) {
  292. collectStat(group);
  293. const std::shared_ptr<DownloadContext>& dctx = group->getDownloadContext();
  294. // DownloadContext::resetDownloadStopTime() is only called when
  295. // download completed. If
  296. // DownloadContext::getDownloadStopTime().isZero() is true, then
  297. // there is a possibility that the download is error or
  298. // in-progress and resetDownloadStopTime() is not called. So
  299. // call it here.
  300. if(dctx->getDownloadStopTime().isZero()) {
  301. dctx->resetDownloadStopTime();
  302. }
  303. try {
  304. group->closeFile();
  305. if(group->isPauseRequested()) {
  306. A2_LOG_NOTICE
  307. (fmt(_("Download GID#%s paused"),
  308. GroupId::toHex(group->getGID()).c_str()));
  309. group->saveControlFile();
  310. } else if(group->downloadFinished() &&
  311. !group->getDownloadContext()->isChecksumVerificationNeeded()) {
  312. group->applyLastModifiedTimeToLocalFiles();
  313. group->reportDownloadFinished();
  314. if(group->allDownloadFinished() &&
  315. !group->getOption()->getAsBool(PREF_FORCE_SAVE)) {
  316. group->removeControlFile();
  317. saveSignature(group);
  318. } else {
  319. group->saveControlFile();
  320. }
  321. std::vector<std::shared_ptr<RequestGroup> > nextGroups;
  322. group->postDownloadProcessing(nextGroups);
  323. if(!nextGroups.empty()) {
  324. A2_LOG_DEBUG
  325. (fmt("Adding %lu RequestGroups as a result of"
  326. " PostDownloadHandler.",
  327. static_cast<unsigned long>(nextGroups.size())));
  328. e_->getRequestGroupMan()->insertReservedGroup(0, nextGroups);
  329. }
  330. #ifdef ENABLE_BITTORRENT
  331. // For in-memory download (e.g., Magnet URI), the
  332. // FileEntry::getPath() does not return actual file path, so
  333. // we don't remove it.
  334. if(group->getOption()->getAsBool(PREF_BT_REMOVE_UNSELECTED_FILE) &&
  335. !group->inMemoryDownload() &&
  336. dctx->hasAttribute(CTX_ATTR_BT)) {
  337. A2_LOG_INFO(fmt(MSG_REMOVING_UNSELECTED_FILE,
  338. GroupId::toHex(group->getGID()).c_str()));
  339. const std::vector<std::shared_ptr<FileEntry> >& files =
  340. dctx->getFileEntries();
  341. for(auto & file : files) {
  342. if(!file->isRequested()) {
  343. if(File(file->getPath()).remove()) {
  344. A2_LOG_INFO(fmt(MSG_FILE_REMOVED, file->getPath().c_str()));
  345. } else {
  346. A2_LOG_INFO(fmt(MSG_FILE_COULD_NOT_REMOVED,
  347. file->getPath().c_str()));
  348. }
  349. }
  350. }
  351. }
  352. #endif // ENABLE_BITTORRENT
  353. } else {
  354. A2_LOG_NOTICE
  355. (fmt(_("Download GID#%s not complete: %s"),
  356. GroupId::toHex(group->getGID()).c_str(),
  357. group->getDownloadContext()->getBasePath().c_str()));
  358. group->saveControlFile();
  359. }
  360. } catch(RecoverableException& ex) {
  361. A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, ex);
  362. }
  363. if(group->isPauseRequested()) {
  364. group->setState(RequestGroup::STATE_WAITING);
  365. reservedGroups_.push_front(group->getGID(), group);
  366. group->releaseRuntimeResource(e_);
  367. group->setForceHaltRequested(false);
  368. util::executeHookByOptName(group, e_->getOption(),
  369. PREF_ON_DOWNLOAD_PAUSE);
  370. notifyDownloadEvent(EVENT_ON_DOWNLOAD_PAUSE, group);
  371. // TODO Should we have to prepend spend uris to remaining uris
  372. // in case PREF_REUSE_URI is disabed?
  373. } else {
  374. std::shared_ptr<DownloadResult> dr = group->createDownloadResult();
  375. e_->getRequestGroupMan()->addDownloadResult(dr);
  376. executeStopHook(group, e_->getOption(), dr->result);
  377. group->releaseRuntimeResource(e_);
  378. }
  379. return true;
  380. } else {
  381. return false;
  382. }
  383. }
  384. };
  385. } // namespace
  386. void RequestGroupMan::removeStoppedGroup(DownloadEngine* e)
  387. {
  388. size_t numPrev = requestGroups_.size();
  389. requestGroups_.remove_if(ProcessStoppedRequestGroup(e, reservedGroups_));
  390. size_t numRemoved = numPrev-requestGroups_.size();
  391. if(numRemoved > 0) {
  392. A2_LOG_DEBUG(fmt("%lu RequestGroup(s) deleted.",
  393. static_cast<unsigned long>(numRemoved)));
  394. }
  395. }
  396. void RequestGroupMan::configureRequestGroup
  397. (const std::shared_ptr<RequestGroup>& requestGroup) const
  398. {
  399. const std::string& uriSelectorValue =
  400. requestGroup->getOption()->get(PREF_URI_SELECTOR);
  401. if(uriSelectorValue == V_FEEDBACK) {
  402. requestGroup->setURISelector(make_unique<FeedbackURISelector>
  403. (serverStatMan_));
  404. } else if(uriSelectorValue == V_INORDER) {
  405. requestGroup->setURISelector(make_unique<InorderURISelector>());
  406. } else if(uriSelectorValue == V_ADAPTIVE) {
  407. requestGroup->setURISelector(make_unique<AdaptiveURISelector>
  408. (serverStatMan_, requestGroup.get()));
  409. }
  410. }
  411. namespace {
  412. std::vector<std::unique_ptr<Command>> createInitialCommand
  413. (const std::shared_ptr<RequestGroup>& requestGroup, DownloadEngine* e)
  414. {
  415. std::vector<std::unique_ptr<Command>> res;
  416. requestGroup->createInitialCommand(res, e);
  417. return res;
  418. }
  419. } // namespace
  420. void RequestGroupMan::fillRequestGroupFromReserver(DownloadEngine* e)
  421. {
  422. removeStoppedGroup(e);
  423. if(static_cast<size_t>(maxSimultaneousDownloads_) <= requestGroups_.size()) {
  424. return;
  425. }
  426. int count = 0;
  427. int num = maxSimultaneousDownloads_-requestGroups_.size();
  428. std::vector<std::shared_ptr<RequestGroup> > pending;
  429. while(count < num && (uriListParser_ || !reservedGroups_.empty())) {
  430. if(uriListParser_ && reservedGroups_.empty()) {
  431. std::vector<std::shared_ptr<RequestGroup> > groups;
  432. // May throw exception
  433. bool ok = createRequestGroupFromUriListParser(groups, option_,
  434. uriListParser_.get());
  435. if(ok) {
  436. appendReservedGroup(reservedGroups_, groups.begin(), groups.end());
  437. } else {
  438. uriListParser_.reset();
  439. if(reservedGroups_.empty()) {
  440. break;
  441. }
  442. }
  443. }
  444. std::shared_ptr<RequestGroup> groupToAdd = *reservedGroups_.begin();
  445. reservedGroups_.pop_front();
  446. if((keepRunning_ && groupToAdd->isPauseRequested()) ||
  447. !groupToAdd->isDependencyResolved()) {
  448. pending.push_back(groupToAdd);
  449. continue;
  450. }
  451. // Drop pieceStorage here because paused download holds its
  452. // reference.
  453. groupToAdd->dropPieceStorage();
  454. configureRequestGroup(groupToAdd);
  455. groupToAdd->setRequestGroupMan(this);
  456. groupToAdd->setState(RequestGroup::STATE_ACTIVE);
  457. requestGroups_.push_back(groupToAdd->getGID(), groupToAdd);
  458. try {
  459. auto res = createInitialCommand(groupToAdd, e);
  460. ++count;
  461. if(res.empty()) {
  462. requestQueueCheck();
  463. } else {
  464. e->addCommand(std::move(res));
  465. }
  466. } catch(RecoverableException& ex) {
  467. A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, ex);
  468. A2_LOG_DEBUG("Deleting temporal commands.");
  469. groupToAdd->setLastErrorCode(ex.getErrorCode());
  470. // We add groupToAdd to e later in order to it is processed in
  471. // removeStoppedGroup().
  472. requestQueueCheck();
  473. }
  474. util::executeHookByOptName(groupToAdd, e->getOption(),
  475. PREF_ON_DOWNLOAD_START);
  476. notifyDownloadEvent(EVENT_ON_DOWNLOAD_START, groupToAdd);
  477. }
  478. if(!pending.empty()) {
  479. reservedGroups_.insert(reservedGroups_.begin(), RequestGroupKeyFunc(),
  480. pending.begin(), pending.end());
  481. }
  482. if(count > 0) {
  483. e->setNoWait(true);
  484. e->setRefreshInterval(0);
  485. A2_LOG_DEBUG(fmt("%d RequestGroup(s) added.", count));
  486. }
  487. }
  488. void RequestGroupMan::save()
  489. {
  490. for(auto& rg : requestGroups_) {
  491. if(rg->allDownloadFinished() &&
  492. !rg->getDownloadContext()->isChecksumVerificationNeeded() &&
  493. !rg->getOption()->getAsBool(PREF_FORCE_SAVE)) {
  494. rg->removeControlFile();
  495. } else {
  496. try {
  497. rg->saveControlFile();
  498. } catch(RecoverableException& e) {
  499. A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, e);
  500. }
  501. }
  502. }
  503. }
  504. void RequestGroupMan::closeFile()
  505. {
  506. for(auto & elem : requestGroups_) {
  507. elem->closeFile();
  508. }
  509. }
  510. RequestGroupMan::DownloadStat RequestGroupMan::getDownloadStat() const
  511. {
  512. int finished = 0;
  513. int error = removedErrorResult_;
  514. int inprogress = 0;
  515. int removed = 0;
  516. error_code::Value lastError = removedLastErrorResult_;
  517. for(auto & dr : downloadResults_) {
  518. if(dr->belongsTo != 0) {
  519. continue;
  520. }
  521. if(dr->result == error_code::FINISHED) {
  522. ++finished;
  523. } else if(dr->result == error_code::IN_PROGRESS) {
  524. ++inprogress;
  525. } else if(dr->result == error_code::REMOVED) {
  526. ++removed;
  527. } else {
  528. ++error;
  529. lastError = dr->result;
  530. }
  531. }
  532. return DownloadStat(error, inprogress,
  533. reservedGroups_.size(),
  534. lastError);
  535. }
  536. enum DownloadResultStatus {
  537. A2_STATUS_OK,
  538. A2_STATUS_INPR,
  539. A2_STATUS_RM,
  540. A2_STATUS_ERR
  541. };
  542. namespace {
  543. const char* getStatusStr(DownloadResultStatus status, bool useColor)
  544. {
  545. // status string is formatted in 4 characters wide.
  546. switch(status) {
  547. case(A2_STATUS_OK):
  548. if(useColor) {
  549. return "\033[1;32mOK\033[0m ";
  550. } else {
  551. return "OK ";
  552. }
  553. case(A2_STATUS_INPR):
  554. if(useColor) {
  555. return "\033[1;34mINPR\033[0m";
  556. } else {
  557. return "INPR";
  558. }
  559. case(A2_STATUS_RM):
  560. if(useColor) {
  561. return "\033[1mRM\033[0m ";
  562. } else {
  563. return "RM ";
  564. }
  565. case(A2_STATUS_ERR):
  566. if(useColor) {
  567. return "\033[1;31mERR\033[0m ";
  568. } else {
  569. return "ERR ";
  570. }
  571. default:
  572. return "";
  573. }
  574. }
  575. } // namespace
  576. void RequestGroupMan::showDownloadResults(OutputFile& o, bool full) const
  577. {
  578. int pathRowSize = 55;
  579. // Download Results:
  580. // idx|stat|path/length
  581. // ===+====+=======================================================================
  582. o.printf("\n%s"
  583. "\ngid |stat|avg speed |",
  584. _("Download Results:"));
  585. if(full) {
  586. o.write(" %|path/URI"
  587. "\n======+====+===========+===+");
  588. pathRowSize -= 4;
  589. } else {
  590. o.write("path/URI"
  591. "\n======+====+===========+");
  592. }
  593. std::string line(pathRowSize, '=');
  594. o.printf("%s\n", line.c_str());
  595. bool useColor = o.supportsColor() && option_->getAsBool(PREF_ENABLE_COLOR);
  596. int ok = 0;
  597. int err = 0;
  598. int inpr = 0;
  599. int rm = 0;
  600. for(auto & dr : downloadResults_) {
  601. if(dr->belongsTo != 0) {
  602. continue;
  603. }
  604. const char* status;
  605. switch(dr->result) {
  606. case error_code::FINISHED:
  607. status = getStatusStr(A2_STATUS_OK, useColor);
  608. ++ok;
  609. break;
  610. case error_code::IN_PROGRESS:
  611. status = getStatusStr(A2_STATUS_INPR, useColor);
  612. ++inpr;
  613. break;
  614. case error_code::REMOVED:
  615. status = getStatusStr(A2_STATUS_RM, useColor);
  616. ++rm;
  617. break;
  618. default:
  619. status = getStatusStr(A2_STATUS_ERR, useColor);
  620. ++err;
  621. }
  622. if(full) {
  623. formatDownloadResultFull(o, status, dr);
  624. } else {
  625. o.write(formatDownloadResult(status, dr).c_str());
  626. o.write("\n");
  627. }
  628. }
  629. if(ok > 0 || err > 0 || inpr > 0 || rm > 0) {
  630. o.printf("\n%s\n", _("Status Legend:"));
  631. if(ok > 0) {
  632. o.write(_("(OK):download completed."));
  633. }
  634. if(err > 0) {
  635. o.write(_("(ERR):error occurred."));
  636. }
  637. if(inpr > 0) {
  638. o.write(_("(INPR):download in-progress."));
  639. }
  640. if(rm > 0) {
  641. o.write(_("(RM):download removed."));
  642. }
  643. o.write("\n");
  644. }
  645. }
  646. namespace {
  647. void formatDownloadResultCommon
  648. (std::ostream& o,
  649. const char* status,
  650. const std::shared_ptr<DownloadResult>& downloadResult)
  651. {
  652. o << std::setw(3) << downloadResult->gid->toAbbrevHex() << "|"
  653. << std::setw(4) << status << "|"
  654. << std::setw(11);
  655. if(downloadResult->sessionTime > 0) {
  656. o << util::abbrevSize
  657. (downloadResult->sessionDownloadLength*1000/downloadResult->sessionTime)+
  658. "B/s";
  659. } else {
  660. o << "n/a";
  661. }
  662. o << "|";
  663. }
  664. } // namespace
  665. void RequestGroupMan::formatDownloadResultFull
  666. (OutputFile& out,
  667. const char* status,
  668. const std::shared_ptr<DownloadResult>& downloadResult) const
  669. {
  670. BitfieldMan bt(downloadResult->pieceLength, downloadResult->totalLength);
  671. bt.setBitfield(reinterpret_cast<const unsigned char*>
  672. (downloadResult->bitfield.data()),
  673. downloadResult->bitfield.size());
  674. bool head = true;
  675. const std::vector<std::shared_ptr<FileEntry> >& fileEntries =
  676. downloadResult->fileEntries;
  677. for(auto & f: fileEntries) {
  678. if(!f->isRequested()) {
  679. continue;
  680. }
  681. std::stringstream o;
  682. if(head) {
  683. formatDownloadResultCommon(o, status, downloadResult);
  684. head = false;
  685. } else {
  686. o << " | | |";
  687. }
  688. if(f->getLength() == 0 || downloadResult->bitfield.empty()) {
  689. o << " -|";
  690. } else {
  691. int64_t completedLength =
  692. bt.getOffsetCompletedLength(f->getOffset(), f->getLength());
  693. o << std::setw(3) << 100*completedLength/f->getLength() << "|";
  694. }
  695. writeFilePath(o, f, downloadResult->inMemoryDownload);
  696. o << "\n";
  697. out.write(o.str().c_str());
  698. }
  699. if(head) {
  700. std::stringstream o;
  701. formatDownloadResultCommon(o, status, downloadResult);
  702. o << " -|n/a\n";
  703. out.write(o.str().c_str());
  704. }
  705. }
  706. std::string RequestGroupMan::formatDownloadResult
  707. (const char* status,
  708. const std::shared_ptr<DownloadResult>& downloadResult) const
  709. {
  710. std::stringstream o;
  711. formatDownloadResultCommon(o, status, downloadResult);
  712. const std::vector<std::shared_ptr<FileEntry> >& fileEntries =
  713. downloadResult->fileEntries;
  714. writeFilePath(fileEntries.begin(), fileEntries.end(), o,
  715. downloadResult->inMemoryDownload);
  716. return o.str();
  717. }
  718. namespace {
  719. template<typename StringInputIterator, typename FileEntryInputIterator>
  720. bool sameFilePathExists(StringInputIterator sfirst,
  721. StringInputIterator slast,
  722. FileEntryInputIterator ffirst,
  723. FileEntryInputIterator flast)
  724. {
  725. for(; ffirst != flast; ++ffirst) {
  726. if(std::binary_search(sfirst, slast, (*ffirst)->getPath())) {
  727. return true;
  728. }
  729. }
  730. return false;
  731. }
  732. } // namespace
  733. bool RequestGroupMan::isSameFileBeingDownloaded(RequestGroup* requestGroup) const
  734. {
  735. // TODO it may be good to use dedicated method rather than use
  736. // isPreLocalFileCheckEnabled
  737. if(!requestGroup->isPreLocalFileCheckEnabled()) {
  738. return false;
  739. }
  740. std::vector<std::string> files;
  741. for(auto & rg : requestGroups_) {
  742. if(rg.get() != requestGroup) {
  743. const std::vector<std::shared_ptr<FileEntry> >& entries =
  744. rg->getDownloadContext()->getFileEntries();
  745. std::transform(entries.begin(), entries.end(),
  746. std::back_inserter(files),
  747. std::mem_fn(&FileEntry::getPath));
  748. }
  749. }
  750. std::sort(files.begin(), files.end());
  751. const std::vector<std::shared_ptr<FileEntry> >& entries =
  752. requestGroup->getDownloadContext()->getFileEntries();
  753. return sameFilePathExists(files.begin(), files.end(),
  754. entries.begin(), entries.end());
  755. }
  756. void RequestGroupMan::halt()
  757. {
  758. for(auto & elem : requestGroups_) {
  759. elem->setHaltRequested(true);
  760. }
  761. }
  762. void RequestGroupMan::forceHalt()
  763. {
  764. for(auto & elem : requestGroups_) {
  765. elem->setForceHaltRequested(true);
  766. }
  767. }
  768. TransferStat RequestGroupMan::calculateStat()
  769. {
  770. // TODO Currently, all time upload length is not set.
  771. return netStat_.toTransferStat();
  772. }
  773. std::shared_ptr<DownloadResult>
  774. RequestGroupMan::findDownloadResult(a2_gid_t gid) const
  775. {
  776. return downloadResults_.get(gid);
  777. }
  778. bool RequestGroupMan::removeDownloadResult(a2_gid_t gid)
  779. {
  780. return downloadResults_.remove(gid);
  781. }
  782. void RequestGroupMan::addDownloadResult(const std::shared_ptr<DownloadResult>& dr)
  783. {
  784. ++numStoppedTotal_;
  785. bool rv = downloadResults_.push_back(dr->gid->getNumericId(), dr);
  786. assert(rv);
  787. while(downloadResults_.size() > maxDownloadResult_){
  788. DownloadResultList::iterator i = downloadResults_.begin();
  789. // Save last encountered error code so that we can report it
  790. // later.
  791. const std::shared_ptr<DownloadResult>& dr = *i;
  792. if(dr->belongsTo == 0 && dr->result != error_code::FINISHED) {
  793. removedLastErrorResult_ = dr->result;
  794. ++removedErrorResult_;
  795. }
  796. downloadResults_.pop_front();
  797. }
  798. }
  799. void RequestGroupMan::purgeDownloadResult()
  800. {
  801. downloadResults_.clear();
  802. }
  803. std::shared_ptr<ServerStat>
  804. RequestGroupMan::findServerStat(const std::string& hostname,
  805. const std::string& protocol) const
  806. {
  807. return serverStatMan_->find(hostname, protocol);
  808. }
  809. std::shared_ptr<ServerStat>
  810. RequestGroupMan::getOrCreateServerStat(const std::string& hostname,
  811. const std::string& protocol)
  812. {
  813. std::shared_ptr<ServerStat> ss = findServerStat(hostname, protocol);
  814. if(!ss) {
  815. ss.reset(new ServerStat(hostname, protocol));
  816. addServerStat(ss);
  817. }
  818. return ss;
  819. }
  820. bool RequestGroupMan::addServerStat(const std::shared_ptr<ServerStat>& serverStat)
  821. {
  822. return serverStatMan_->add(serverStat);
  823. }
  824. bool RequestGroupMan::loadServerStat(const std::string& filename)
  825. {
  826. return serverStatMan_->load(filename);
  827. }
  828. bool RequestGroupMan::saveServerStat(const std::string& filename) const
  829. {
  830. return serverStatMan_->save(filename);
  831. }
  832. void RequestGroupMan::removeStaleServerStat(time_t timeout)
  833. {
  834. serverStatMan_->removeStaleServerStat(timeout);
  835. }
  836. bool RequestGroupMan::doesOverallDownloadSpeedExceed()
  837. {
  838. return maxOverallDownloadSpeedLimit_ > 0 &&
  839. maxOverallDownloadSpeedLimit_ < netStat_.calculateDownloadSpeed();
  840. }
  841. bool RequestGroupMan::doesOverallUploadSpeedExceed()
  842. {
  843. return maxOverallUploadSpeedLimit_ > 0 &&
  844. maxOverallUploadSpeedLimit_ < netStat_.calculateUploadSpeed();
  845. }
  846. void RequestGroupMan::getUsedHosts
  847. (std::vector<std::pair<size_t, std::string> >& usedHosts)
  848. {
  849. // vector of tuple which consists of use count, -download speed,
  850. // hostname. We want to sort by least used and faster download
  851. // speed. We use -download speed so that we can sort them using
  852. // operator<().
  853. std::vector<std::tuple<size_t, int, std::string> > tempHosts;
  854. for(const auto& rg : requestGroups_) {
  855. const auto& inFlightReqs =
  856. rg->getDownloadContext()->getFirstFileEntry()->getInFlightRequests();
  857. for(const auto& req : inFlightReqs) {
  858. uri_split_result us;
  859. if(uri_split(&us, req->getUri().c_str()) == 0) {
  860. std::string host = uri::getFieldString(us, USR_HOST,
  861. req->getUri().c_str());
  862. auto k = tempHosts.begin();
  863. auto eok = tempHosts.end();
  864. for(; k != eok; ++k) {
  865. if(std::get<2>(*k) == host) {
  866. ++std::get<0>(*k);
  867. break;
  868. }
  869. }
  870. if(k == eok) {
  871. std::string protocol = uri::getFieldString(us, USR_SCHEME,
  872. req->getUri().c_str());
  873. auto ss = findServerStat(host, protocol);
  874. int invDlSpeed = (ss && ss->isOK()) ?
  875. -(static_cast<int>(ss->getDownloadSpeed())) : 0;
  876. tempHosts.emplace_back(1, invDlSpeed, host);
  877. }
  878. }
  879. }
  880. }
  881. std::sort(tempHosts.begin(), tempHosts.end());
  882. std::transform(tempHosts.begin(), tempHosts.end(),
  883. std::back_inserter(usedHosts),
  884. [](const std::tuple<size_t, int, std::string>& x) {
  885. return std::make_pair(std::get<0>(x), std::get<2>(x));
  886. });
  887. }
  888. void RequestGroupMan::setUriListParser
  889. (const std::shared_ptr<UriListParser>& uriListParser)
  890. {
  891. uriListParser_ = uriListParser;
  892. }
  893. void RequestGroupMan::initWrDiskCache()
  894. {
  895. assert(wrDiskCache_ == nullptr);
  896. size_t limit = option_->getAsInt(PREF_DISK_CACHE);
  897. if(limit > 0) {
  898. wrDiskCache_ = new WrDiskCache(limit);
  899. }
  900. }
  901. void RequestGroupMan::ensureMaxOpenFileLimit(size_t numNewFile)
  902. {
  903. size_t max = option_->getAsInt(PREF_BT_MAX_OPEN_FILES);
  904. if(numOpenFile_ + numNewFile <= max) {
  905. numOpenFile_ += numNewFile;
  906. return;
  907. }
  908. assert(numNewFile <= max);
  909. size_t numClose = numOpenFile_ + numNewFile - max;
  910. size_t left = numClose;
  911. auto mark = std::begin(requestGroups_);
  912. std::advance(mark,
  913. SimpleRandomizer::getInstance()->
  914. getRandomNumber(requestGroups_.size()));
  915. for(auto i = mark; i != std::end(requestGroups_) && left > 0; ++i) {
  916. left -= (*i)->getPieceStorage()->getDiskAdaptor()->tryCloseFile(left);
  917. }
  918. for(auto i = std::begin(requestGroups_); i != mark && left > 0; ++i) {
  919. left -= (*i)->getPieceStorage()->getDiskAdaptor()->tryCloseFile(left);
  920. }
  921. assert(left == 0);
  922. numOpenFile_ += numNewFile - numClose;
  923. }
  924. void RequestGroupMan::reduceNumOfOpenedFile(size_t numCloseFile)
  925. {
  926. assert(numOpenFile_ >= numCloseFile);
  927. numOpenFile_ -= numCloseFile;
  928. }
  929. } // namespace aria2