RequestGroupMan.cc 29 KB

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