RequestGroupMan.cc 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902
  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 "PeerStat.h"
  56. #include "SegmentMan.h"
  57. #include "FeedbackURISelector.h"
  58. #include "InorderURISelector.h"
  59. #include "AdaptiveURISelector.h"
  60. #include "Option.h"
  61. #include "prefs.h"
  62. #include "File.h"
  63. #include "util.h"
  64. #include "Command.h"
  65. #include "FileEntry.h"
  66. #include "fmt.h"
  67. #include "FileAllocationEntry.h"
  68. #include "CheckIntegrityEntry.h"
  69. #include "Segment.h"
  70. #include "DlAbortEx.h"
  71. #include "uri.h"
  72. #include "Triplet.h"
  73. #include "Signature.h"
  74. #include "OutputFile.h"
  75. namespace aria2 {
  76. RequestGroupMan::RequestGroupMan
  77. (const std::vector<SharedHandle<RequestGroup> >& requestGroups,
  78. unsigned int maxSimultaneousDownloads,
  79. const Option* option)
  80. : reservedGroups_(requestGroups.begin(), requestGroups.end()),
  81. maxSimultaneousDownloads_(maxSimultaneousDownloads),
  82. option_(option),
  83. serverStatMan_(new ServerStatMan()),
  84. maxOverallDownloadSpeedLimit_
  85. (option->getAsInt(PREF_MAX_OVERALL_DOWNLOAD_LIMIT)),
  86. maxOverallUploadSpeedLimit_(option->getAsInt
  87. (PREF_MAX_OVERALL_UPLOAD_LIMIT)),
  88. rpc_(option->getAsBool(PREF_ENABLE_RPC)),
  89. queueCheck_(true),
  90. removedErrorResult_(0),
  91. removedLastErrorResult_(error_code::FINISHED),
  92. maxDownloadResult_(option->getAsInt(PREF_MAX_DOWNLOAD_RESULT))
  93. {}
  94. RequestGroupMan::~RequestGroupMan() {}
  95. bool RequestGroupMan::downloadFinished()
  96. {
  97. if(rpc_) {
  98. return false;
  99. }
  100. return requestGroups_.empty() && reservedGroups_.empty();
  101. }
  102. void RequestGroupMan::addRequestGroup
  103. (const SharedHandle<RequestGroup>& group)
  104. {
  105. requestGroups_.push_back(group);
  106. }
  107. void RequestGroupMan::addReservedGroup
  108. (const std::vector<SharedHandle<RequestGroup> >& groups)
  109. {
  110. requestQueueCheck();
  111. reservedGroups_.insert(reservedGroups_.end(), groups.begin(), groups.end());
  112. }
  113. void RequestGroupMan::addReservedGroup
  114. (const SharedHandle<RequestGroup>& group)
  115. {
  116. requestQueueCheck();
  117. reservedGroups_.push_back(group);
  118. }
  119. void RequestGroupMan::insertReservedGroup
  120. (size_t pos, const std::vector<SharedHandle<RequestGroup> >& groups)
  121. {
  122. requestQueueCheck();
  123. reservedGroups_.insert
  124. (reservedGroups_.begin()+std::min(reservedGroups_.size(), pos),
  125. groups.begin(), groups.end());
  126. }
  127. void RequestGroupMan::insertReservedGroup
  128. (size_t pos, const SharedHandle<RequestGroup>& group)
  129. {
  130. requestQueueCheck();
  131. reservedGroups_.insert
  132. (reservedGroups_.begin()+std::min(reservedGroups_.size(), pos), group);
  133. }
  134. size_t RequestGroupMan::countRequestGroup() const
  135. {
  136. return requestGroups_.size();
  137. }
  138. SharedHandle<RequestGroup> RequestGroupMan::getRequestGroup(size_t index) const
  139. {
  140. if(index < requestGroups_.size()) {
  141. return requestGroups_[index];
  142. } else {
  143. return SharedHandle<RequestGroup>();
  144. }
  145. }
  146. namespace {
  147. template<typename Iterator>
  148. Iterator findByGID(Iterator first, Iterator last, a2_gid_t gid)
  149. {
  150. for(; first != last; ++first) {
  151. if((*first)->getGID() == gid) {
  152. return first;
  153. }
  154. }
  155. return first;
  156. }
  157. } // namespace
  158. SharedHandle<RequestGroup>
  159. RequestGroupMan::findRequestGroup(a2_gid_t gid) const
  160. {
  161. std::deque<SharedHandle<RequestGroup> >::const_iterator i =
  162. findByGID(requestGroups_.begin(), requestGroups_.end(), gid);
  163. if(i == requestGroups_.end()) {
  164. return SharedHandle<RequestGroup>();
  165. } else {
  166. return *i;
  167. }
  168. }
  169. SharedHandle<RequestGroup>
  170. RequestGroupMan::findReservedGroup(a2_gid_t gid) const
  171. {
  172. std::deque<SharedHandle<RequestGroup> >::const_iterator i =
  173. findByGID(reservedGroups_.begin(), reservedGroups_.end(), gid);
  174. if(i == reservedGroups_.end()) {
  175. return SharedHandle<RequestGroup>();
  176. } else {
  177. return *i;
  178. }
  179. }
  180. size_t RequestGroupMan::changeReservedGroupPosition
  181. (a2_gid_t gid, int pos, HOW how)
  182. {
  183. std::deque<SharedHandle<RequestGroup> >::iterator i =
  184. findByGID(reservedGroups_.begin(), reservedGroups_.end(), gid);
  185. if(i == reservedGroups_.end()) {
  186. throw DL_ABORT_EX
  187. (fmt("GID#%s not found in the waiting queue.",
  188. util::itos(gid).c_str()));
  189. }
  190. SharedHandle<RequestGroup> rg = *i;
  191. const size_t maxPos = reservedGroups_.size()-1;
  192. if(how == POS_SET) {
  193. if(pos < 0) {
  194. pos = 0;
  195. } else if(pos > 0) {
  196. pos = std::min(maxPos, (size_t)pos);
  197. }
  198. } else if(how == POS_CUR) {
  199. size_t abspos = std::distance(reservedGroups_.begin(), i);
  200. if(pos < 0) {
  201. int dist = -std::distance(reservedGroups_.begin(), i);
  202. pos = abspos+std::max(pos, dist);
  203. } else if(pos > 0) {
  204. int dist = std::distance(i, reservedGroups_.end())-1;
  205. pos = abspos+std::min(pos, dist);
  206. } else {
  207. pos = abspos;
  208. }
  209. } else if(how == POS_END) {
  210. if(pos >= 0) {
  211. pos = maxPos;
  212. } else {
  213. pos = maxPos-std::min(maxPos, (size_t)-pos);
  214. }
  215. }
  216. if(std::distance(reservedGroups_.begin(), i) < pos) {
  217. std::rotate(i, i+1, reservedGroups_.begin()+pos+1);
  218. } else {
  219. std::rotate(reservedGroups_.begin()+pos, i, i+1);
  220. }
  221. return pos;
  222. }
  223. bool RequestGroupMan::removeReservedGroup(a2_gid_t gid)
  224. {
  225. std::deque<SharedHandle<RequestGroup> >::iterator i =
  226. findByGID(reservedGroups_.begin(), reservedGroups_.end(), gid);
  227. if(i == reservedGroups_.end()) {
  228. return false;
  229. } else {
  230. reservedGroups_.erase(i);
  231. return true;
  232. }
  233. }
  234. namespace {
  235. void executeStopHook
  236. (const SharedHandle<RequestGroup>& group,
  237. const Option* option,
  238. error_code::Value result)
  239. {
  240. if(result == error_code::FINISHED &&
  241. !option->blank(PREF_ON_DOWNLOAD_COMPLETE)) {
  242. util::executeHookByOptName(group, option, PREF_ON_DOWNLOAD_COMPLETE);
  243. } else if(result != error_code::IN_PROGRESS &&
  244. result != error_code::REMOVED &&
  245. !option->blank(PREF_ON_DOWNLOAD_ERROR)) {
  246. util::executeHookByOptName(group, option, PREF_ON_DOWNLOAD_ERROR);
  247. } else if(!option->blank(PREF_ON_DOWNLOAD_STOP)) {
  248. util::executeHookByOptName(group, option, PREF_ON_DOWNLOAD_STOP);
  249. }
  250. }
  251. } // namespace
  252. namespace {
  253. class ProcessStoppedRequestGroup {
  254. private:
  255. DownloadEngine* e_;
  256. std::deque<SharedHandle<DownloadResult> >& downloadResults_;
  257. std::deque<SharedHandle<RequestGroup> >& reservedGroups_;
  258. Logger* logger_;
  259. void saveSignature(const SharedHandle<RequestGroup>& group)
  260. {
  261. SharedHandle<Signature> sig =
  262. group->getDownloadContext()->getSignature();
  263. if(sig && !sig->getBody().empty()) {
  264. // filename of signature file is the path to download file followed by
  265. // ".sig".
  266. std::string signatureFile = group->getFirstFilePath()+".sig";
  267. if(sig->save(signatureFile)) {
  268. A2_LOG_NOTICE(fmt(MSG_SIGNATURE_SAVED, signatureFile.c_str()));
  269. } else {
  270. A2_LOG_NOTICE(fmt(MSG_SIGNATURE_NOT_SAVED, signatureFile.c_str()));
  271. }
  272. }
  273. }
  274. public:
  275. ProcessStoppedRequestGroup
  276. (DownloadEngine* e,
  277. std::deque<SharedHandle<DownloadResult> >& downloadResults,
  278. std::deque<SharedHandle<RequestGroup> >& reservedGroups)
  279. : e_(e),
  280. downloadResults_(downloadResults),
  281. reservedGroups_(reservedGroups)
  282. {}
  283. void operator()(const SharedHandle<RequestGroup>& group)
  284. {
  285. if(group->getNumCommand() == 0) {
  286. const SharedHandle<DownloadContext>& dctx = group->getDownloadContext();
  287. // DownloadContext::resetDownloadStopTime() is only called when
  288. // download completed. If
  289. // DownloadContext::getDownloadStopTime().isZero() is true, then
  290. // there is a possibility that the download is error or
  291. // in-progress and resetDownloadStopTime() is not called. So
  292. // call it here.
  293. if(dctx->getDownloadStopTime().isZero()) {
  294. dctx->resetDownloadStopTime();
  295. }
  296. try {
  297. group->closeFile();
  298. if(group->downloadFinished() &&
  299. !group->getDownloadContext()->isChecksumVerificationNeeded()) {
  300. group->setPauseRequested(false);
  301. group->applyLastModifiedTimeToLocalFiles();
  302. group->reportDownloadFinished();
  303. if(group->allDownloadFinished()) {
  304. group->removeControlFile();
  305. saveSignature(group);
  306. } else {
  307. group->saveControlFile();
  308. }
  309. std::vector<SharedHandle<RequestGroup> > nextGroups;
  310. group->postDownloadProcessing(nextGroups);
  311. if(!nextGroups.empty()) {
  312. A2_LOG_DEBUG
  313. (fmt("Adding %lu RequestGroups as a result of"
  314. " PostDownloadHandler.",
  315. static_cast<unsigned long>(nextGroups.size())));
  316. e_->getRequestGroupMan()->insertReservedGroup(0, nextGroups);
  317. }
  318. } else {
  319. A2_LOG_NOTICE
  320. (fmt("Download GID#%s not complete: %s",
  321. util::itos(group->getGID()).c_str(),
  322. group->getDownloadContext()->getBasePath().c_str()));
  323. group->saveControlFile();
  324. }
  325. } catch(RecoverableException& ex) {
  326. A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, ex);
  327. }
  328. if(group->isPauseRequested()) {
  329. reservedGroups_.push_front(group);
  330. group->releaseRuntimeResource(e_);
  331. group->setForceHaltRequested(false);
  332. util::executeHookByOptName
  333. (group, e_->getOption(), PREF_ON_DOWNLOAD_PAUSE);
  334. // TODO Should we have to prepend spend uris to remaining uris
  335. // in case PREF_REUSE_URI is disabed?
  336. } else {
  337. SharedHandle<DownloadResult> dr = group->createDownloadResult();
  338. e_->getRequestGroupMan()->addDownloadResult(dr);
  339. executeStopHook(group, e_->getOption(), dr->result);
  340. group->releaseRuntimeResource(e_);
  341. }
  342. }
  343. }
  344. };
  345. } // namespace
  346. namespace {
  347. class CollectServerStat {
  348. private:
  349. RequestGroupMan* requestGroupMan_;
  350. public:
  351. CollectServerStat(RequestGroupMan* requestGroupMan):
  352. requestGroupMan_(requestGroupMan) {}
  353. void operator()(const SharedHandle<RequestGroup>& group)
  354. {
  355. if(group->getNumCommand() == 0) {
  356. // Collect statistics during download in PeerStats and update/register
  357. // ServerStatMan
  358. if(group->getSegmentMan()) {
  359. bool singleConnection =
  360. group->getSegmentMan()->getPeerStats().size() == 1;
  361. const std::vector<SharedHandle<PeerStat> >& peerStats =
  362. group->getSegmentMan()->getFastestPeerStats();
  363. for(std::vector<SharedHandle<PeerStat> >::const_iterator i =
  364. peerStats.begin(), eoi = peerStats.end(); i != eoi; ++i) {
  365. if((*i)->getHostname().empty() || (*i)->getProtocol().empty()) {
  366. continue;
  367. }
  368. int speed = (*i)->getAvgDownloadSpeed();
  369. if (speed == 0) continue;
  370. SharedHandle<ServerStat> ss =
  371. requestGroupMan_->getOrCreateServerStat((*i)->getHostname(),
  372. (*i)->getProtocol());
  373. ss->increaseCounter();
  374. ss->updateDownloadSpeed(speed);
  375. if(singleConnection) {
  376. ss->updateSingleConnectionAvgSpeed(speed);
  377. }
  378. else {
  379. ss->updateMultiConnectionAvgSpeed(speed);
  380. }
  381. }
  382. }
  383. }
  384. }
  385. };
  386. } // namespace
  387. namespace {
  388. class FindStoppedRequestGroup {
  389. public:
  390. bool operator()(const SharedHandle<RequestGroup>& group) {
  391. return group->getNumCommand() == 0;
  392. }
  393. };
  394. } // namespace
  395. void RequestGroupMan::updateServerStat()
  396. {
  397. std::for_each(requestGroups_.begin(), requestGroups_.end(),
  398. CollectServerStat(this));
  399. }
  400. void RequestGroupMan::removeStoppedGroup(DownloadEngine* e)
  401. {
  402. size_t numPrev = requestGroups_.size();
  403. updateServerStat();
  404. std::for_each(requestGroups_.begin(), requestGroups_.end(),
  405. ProcessStoppedRequestGroup
  406. (e, downloadResults_, reservedGroups_));
  407. std::deque<SharedHandle<RequestGroup> >::iterator i =
  408. std::remove_if(requestGroups_.begin(),
  409. requestGroups_.end(),
  410. FindStoppedRequestGroup());
  411. if(i != requestGroups_.end()) {
  412. requestGroups_.erase(i, requestGroups_.end());
  413. }
  414. size_t numRemoved = numPrev-requestGroups_.size();
  415. if(numRemoved > 0) {
  416. A2_LOG_DEBUG(fmt("%lu RequestGroup(s) deleted.",
  417. static_cast<unsigned long>(numRemoved)));
  418. }
  419. }
  420. void RequestGroupMan::configureRequestGroup
  421. (const SharedHandle<RequestGroup>& requestGroup) const
  422. {
  423. const std::string& uriSelectorValue = option_->get(PREF_URI_SELECTOR);
  424. if(uriSelectorValue == V_FEEDBACK) {
  425. SharedHandle<URISelector> sel(new FeedbackURISelector(serverStatMan_));
  426. requestGroup->setURISelector(sel);
  427. } else if(uriSelectorValue == V_INORDER) {
  428. SharedHandle<URISelector> sel(new InorderURISelector());
  429. requestGroup->setURISelector(sel);
  430. } else if(uriSelectorValue == V_ADAPTIVE) {
  431. SharedHandle<URISelector> sel(new AdaptiveURISelector(serverStatMan_,
  432. requestGroup.get()));
  433. requestGroup->setURISelector(sel);
  434. }
  435. }
  436. namespace {
  437. void createInitialCommand(const SharedHandle<RequestGroup>& requestGroup,
  438. std::vector<Command*>& commands,
  439. DownloadEngine* e)
  440. {
  441. requestGroup->createInitialCommand(commands, e);
  442. }
  443. } // namespace
  444. void RequestGroupMan::fillRequestGroupFromReserver(DownloadEngine* e)
  445. {
  446. removeStoppedGroup(e);
  447. if(maxSimultaneousDownloads_ <= requestGroups_.size()) {
  448. return;
  449. }
  450. std::vector<SharedHandle<RequestGroup> > temp;
  451. unsigned int count = 0;
  452. size_t num = maxSimultaneousDownloads_-requestGroups_.size();
  453. while(count < num && !reservedGroups_.empty()) {
  454. SharedHandle<RequestGroup> groupToAdd = reservedGroups_.front();
  455. reservedGroups_.pop_front();
  456. std::vector<Command*> commands;
  457. try {
  458. if((rpc_ && groupToAdd->isPauseRequested()) ||
  459. !groupToAdd->isDependencyResolved()) {
  460. temp.push_back(groupToAdd);
  461. continue;
  462. }
  463. // Drop pieceStorage here because paused download holds its
  464. // reference.
  465. groupToAdd->dropPieceStorage();
  466. configureRequestGroup(groupToAdd);
  467. createInitialCommand(groupToAdd, commands, e);
  468. groupToAdd->setRequestGroupMan(this);
  469. if(commands.empty()) {
  470. requestQueueCheck();
  471. }
  472. requestGroups_.push_back(groupToAdd);
  473. ++count;
  474. e->addCommand(commands);
  475. commands.clear();
  476. } catch(RecoverableException& ex) {
  477. A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, ex);
  478. A2_LOG_DEBUG("Deleting temporal commands.");
  479. std::for_each(commands.begin(), commands.end(), Deleter());
  480. commands.clear();
  481. A2_LOG_DEBUG("Commands deleted");
  482. groupToAdd->setLastErrorCode(ex.getErrorCode());
  483. // We add groupToAdd to e in order to it is processed in
  484. // removeStoppedGroup().
  485. requestGroups_.push_back(groupToAdd);
  486. requestQueueCheck();
  487. }
  488. util::executeHookByOptName
  489. (groupToAdd, e->getOption(), PREF_ON_DOWNLOAD_START);
  490. }
  491. if(!temp.empty()) {
  492. reservedGroups_.insert(reservedGroups_.begin(), temp.begin(), temp.end());
  493. }
  494. if(count > 0) {
  495. e->setNoWait(true);
  496. e->setRefreshInterval(0);
  497. A2_LOG_DEBUG(fmt("%d RequestGroup(s) added.", count));
  498. }
  499. }
  500. void RequestGroupMan::save()
  501. {
  502. for(std::deque<SharedHandle<RequestGroup> >::const_iterator itr =
  503. requestGroups_.begin(), eoi = requestGroups_.end(); itr != eoi; ++itr) {
  504. if((*itr)->allDownloadFinished() &&
  505. !(*itr)->getDownloadContext()->isChecksumVerificationNeeded()) {
  506. (*itr)->removeControlFile();
  507. } else {
  508. try {
  509. (*itr)->saveControlFile();
  510. } catch(RecoverableException& e) {
  511. A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, e);
  512. }
  513. }
  514. }
  515. }
  516. void RequestGroupMan::closeFile()
  517. {
  518. for(std::deque<SharedHandle<RequestGroup> >::const_iterator itr =
  519. requestGroups_.begin(), eoi = requestGroups_.end(); itr != eoi; ++itr) {
  520. (*itr)->closeFile();
  521. }
  522. }
  523. RequestGroupMan::DownloadStat RequestGroupMan::getDownloadStat() const
  524. {
  525. size_t finished = 0;
  526. size_t error = removedErrorResult_;
  527. size_t inprogress = 0;
  528. size_t removed = 0;
  529. error_code::Value lastError = removedLastErrorResult_;
  530. for(std::deque<SharedHandle<DownloadResult> >::const_iterator itr =
  531. downloadResults_.begin(), eoi = downloadResults_.end();
  532. itr != eoi; ++itr) {
  533. if((*itr)->belongsTo != 0) {
  534. continue;
  535. }
  536. if((*itr)->result == error_code::FINISHED) {
  537. ++finished;
  538. } else if((*itr)->result == error_code::IN_PROGRESS) {
  539. ++inprogress;
  540. } else if((*itr)->result == error_code::REMOVED) {
  541. ++removed;
  542. } else {
  543. ++error;
  544. lastError = (*itr)->result;
  545. }
  546. }
  547. return DownloadStat(finished, error, inprogress, removed,
  548. reservedGroups_.size(),
  549. lastError);
  550. }
  551. void RequestGroupMan::showDownloadResults(OutputFile& o) const
  552. {
  553. static const std::string MARK_OK("OK");
  554. static const std::string MARK_ERR("ERR");
  555. static const std::string MARK_INPR("INPR");
  556. static const std::string MARK_RM("RM");
  557. // Download Results:
  558. // idx|stat|path/length
  559. // ===+====+=======================================================================
  560. o.printf("\n%s"
  561. "\ngid|stat|avg speed |path/URI"
  562. "\n===+====+===========+",
  563. _("Download Results:"));
  564. #ifdef __MINGW32__
  565. int pathRowSize = 58;
  566. #else // !__MINGW32__
  567. int pathRowSize = 59;
  568. #endif // !__MINGW32__
  569. std::string line(pathRowSize, '=');
  570. o.printf("%s\n", line.c_str());
  571. int ok = 0;
  572. int err = 0;
  573. int inpr = 0;
  574. int rm = 0;
  575. for(std::deque<SharedHandle<DownloadResult> >::const_iterator itr =
  576. downloadResults_.begin(), eoi = downloadResults_.end();
  577. itr != eoi; ++itr) {
  578. if((*itr)->belongsTo != 0) {
  579. continue;
  580. }
  581. std::string status;
  582. if((*itr)->result == error_code::FINISHED) {
  583. status = MARK_OK;
  584. ++ok;
  585. } else if((*itr)->result == error_code::IN_PROGRESS) {
  586. status = MARK_INPR;
  587. ++inpr;
  588. } else if((*itr)->result == error_code::REMOVED) {
  589. status = MARK_RM;
  590. ++rm;
  591. } else {
  592. status = MARK_ERR;
  593. ++err;
  594. }
  595. o.write(formatDownloadResult(status, *itr).c_str());
  596. o.write("\n");
  597. }
  598. if(ok > 0 || err > 0 || inpr > 0 || rm > 0) {
  599. o.printf("\n%s\n", _("Status Legend:"));
  600. if(ok > 0) {
  601. o.write(" (OK):download completed.");
  602. }
  603. if(err > 0) {
  604. o.write("(ERR):error occurred.");
  605. }
  606. if(inpr > 0) {
  607. o.write("(INPR):download in-progress.");
  608. }
  609. if(rm > 0) {
  610. o.write("(RM):download removed.");
  611. }
  612. o.write("\n");
  613. }
  614. }
  615. std::string RequestGroupMan::formatDownloadResult
  616. (const std::string& status,
  617. const DownloadResultHandle& downloadResult) const
  618. {
  619. std::stringstream o;
  620. o << std::setw(3) << downloadResult->gid << "|"
  621. << std::setw(4) << status << "|"
  622. << std::setw(11);
  623. if(downloadResult->sessionTime > 0) {
  624. o << util::abbrevSize
  625. (downloadResult->sessionDownloadLength*1000/downloadResult->sessionTime)+
  626. "B/s";
  627. } else {
  628. o << "n/a";
  629. }
  630. o << "|";
  631. const std::vector<SharedHandle<FileEntry> >& fileEntries =
  632. downloadResult->fileEntries;
  633. writeFilePath(fileEntries.begin(), fileEntries.end(), o,
  634. downloadResult->inMemoryDownload);
  635. return o.str();
  636. }
  637. namespace {
  638. template<typename StringInputIterator, typename FileEntryInputIterator>
  639. bool sameFilePathExists(StringInputIterator sfirst,
  640. StringInputIterator slast,
  641. FileEntryInputIterator ffirst,
  642. FileEntryInputIterator flast)
  643. {
  644. for(; ffirst != flast; ++ffirst) {
  645. if(std::binary_search(sfirst, slast, (*ffirst)->getPath())) {
  646. return true;
  647. }
  648. }
  649. return false;
  650. }
  651. } // namespace
  652. bool RequestGroupMan::isSameFileBeingDownloaded(RequestGroup* requestGroup) const
  653. {
  654. // TODO it may be good to use dedicated method rather than use
  655. // isPreLocalFileCheckEnabled
  656. if(!requestGroup->isPreLocalFileCheckEnabled()) {
  657. return false;
  658. }
  659. std::vector<std::string> files;
  660. for(std::deque<SharedHandle<RequestGroup> >::const_iterator itr =
  661. requestGroups_.begin(), eoi = requestGroups_.end(); itr != eoi; ++itr) {
  662. if((*itr).get() != requestGroup) {
  663. const std::vector<SharedHandle<FileEntry> >& entries =
  664. (*itr)->getDownloadContext()->getFileEntries();
  665. std::transform(entries.begin(), entries.end(),
  666. std::back_inserter(files),
  667. mem_fun_sh(&FileEntry::getPath));
  668. }
  669. }
  670. std::sort(files.begin(), files.end());
  671. const std::vector<SharedHandle<FileEntry> >& entries =
  672. requestGroup->getDownloadContext()->getFileEntries();
  673. return sameFilePathExists(files.begin(), files.end(),
  674. entries.begin(), entries.end());
  675. }
  676. void RequestGroupMan::halt()
  677. {
  678. for(std::deque<SharedHandle<RequestGroup> >::const_iterator i =
  679. requestGroups_.begin(), eoi = requestGroups_.end(); i != eoi; ++i) {
  680. (*i)->setHaltRequested(true);
  681. }
  682. }
  683. void RequestGroupMan::forceHalt()
  684. {
  685. for(std::deque<SharedHandle<RequestGroup> >::const_iterator i =
  686. requestGroups_.begin(), eoi = requestGroups_.end(); i != eoi; ++i) {
  687. (*i)->setForceHaltRequested(true);
  688. }
  689. }
  690. TransferStat RequestGroupMan::calculateStat()
  691. {
  692. TransferStat s;
  693. for(std::deque<SharedHandle<RequestGroup> >::const_iterator i =
  694. requestGroups_.begin(), eoi = requestGroups_.end(); i != eoi; ++i) {
  695. s += (*i)->calculateStat();
  696. }
  697. return s;
  698. }
  699. SharedHandle<DownloadResult>
  700. RequestGroupMan::findDownloadResult(a2_gid_t gid) const
  701. {
  702. for(std::deque<SharedHandle<DownloadResult> >::const_iterator i =
  703. downloadResults_.begin(), eoi = downloadResults_.end(); i != eoi; ++i) {
  704. if((*i)->gid == gid) {
  705. return *i;
  706. }
  707. }
  708. return SharedHandle<DownloadResult>();
  709. }
  710. bool RequestGroupMan::removeDownloadResult(a2_gid_t gid)
  711. {
  712. for(std::deque<SharedHandle<DownloadResult> >::iterator i =
  713. downloadResults_.begin(), eoi = downloadResults_.end(); i != eoi; ++i) {
  714. if((*i)->gid == gid) {
  715. downloadResults_.erase(i);
  716. return true;
  717. }
  718. }
  719. return false;
  720. }
  721. void RequestGroupMan::addDownloadResult(const SharedHandle<DownloadResult>& dr)
  722. {
  723. if(maxDownloadResult_ == 0) {
  724. if(!downloadResults_.empty()) {
  725. for(std::deque<SharedHandle<DownloadResult> >::iterator i =
  726. downloadResults_.begin(), eoi = downloadResults_.end(); i != eoi;
  727. ++i) {
  728. if((*i)->belongsTo == 0 && (*i)->result != error_code::FINISHED) {
  729. removedLastErrorResult_ = (*i)->result;
  730. ++removedErrorResult_;
  731. }
  732. }
  733. downloadResults_.clear();
  734. }
  735. if(dr->belongsTo == 0 && dr->result != error_code::FINISHED) {
  736. removedLastErrorResult_ = dr->result;
  737. ++removedErrorResult_;
  738. }
  739. } else {
  740. size_t curSize = downloadResults_.size();
  741. if(curSize >= maxDownloadResult_) {
  742. std::deque<SharedHandle<DownloadResult> >::iterator last =
  743. downloadResults_.begin()+curSize-maxDownloadResult_+1;
  744. for(std::deque<SharedHandle<DownloadResult> >::iterator i =
  745. downloadResults_.begin(); i != last; ++i) {
  746. if((*i)->belongsTo == 0 && (*i)->result != error_code::FINISHED) {
  747. removedLastErrorResult_ = (*i)->result;
  748. ++removedErrorResult_;
  749. }
  750. }
  751. downloadResults_.erase(downloadResults_.begin(), last);
  752. }
  753. downloadResults_.push_back(dr);
  754. }
  755. }
  756. void RequestGroupMan::purgeDownloadResult()
  757. {
  758. downloadResults_.clear();
  759. }
  760. SharedHandle<ServerStat>
  761. RequestGroupMan::findServerStat(const std::string& hostname,
  762. const std::string& protocol) const
  763. {
  764. return serverStatMan_->find(hostname, protocol);
  765. }
  766. SharedHandle<ServerStat>
  767. RequestGroupMan::getOrCreateServerStat(const std::string& hostname,
  768. const std::string& protocol)
  769. {
  770. SharedHandle<ServerStat> ss = findServerStat(hostname, protocol);
  771. if(!ss) {
  772. ss.reset(new ServerStat(hostname, protocol));
  773. addServerStat(ss);
  774. }
  775. return ss;
  776. }
  777. bool RequestGroupMan::addServerStat(const SharedHandle<ServerStat>& serverStat)
  778. {
  779. return serverStatMan_->add(serverStat);
  780. }
  781. bool RequestGroupMan::loadServerStat(const std::string& filename)
  782. {
  783. return serverStatMan_->load(filename);
  784. }
  785. bool RequestGroupMan::saveServerStat(const std::string& filename) const
  786. {
  787. return serverStatMan_->save(filename);
  788. }
  789. void RequestGroupMan::removeStaleServerStat(time_t timeout)
  790. {
  791. serverStatMan_->removeStaleServerStat(timeout);
  792. }
  793. bool RequestGroupMan::doesOverallDownloadSpeedExceed()
  794. {
  795. return maxOverallDownloadSpeedLimit_ > 0 &&
  796. maxOverallDownloadSpeedLimit_ < calculateStat().getDownloadSpeed();
  797. }
  798. bool RequestGroupMan::doesOverallUploadSpeedExceed()
  799. {
  800. return maxOverallUploadSpeedLimit_ > 0 &&
  801. maxOverallUploadSpeedLimit_ < calculateStat().getUploadSpeed();
  802. }
  803. void RequestGroupMan::getUsedHosts
  804. (std::vector<std::pair<size_t, std::string> >& usedHosts)
  805. {
  806. // vector of triplet which consists of use count, -download speed,
  807. // hostname. We want to sort by least used and faster download
  808. // speed. We use -download speed so that we can sort them using
  809. // operator<().
  810. std::vector<Triplet<size_t, int, std::string> > tempHosts;
  811. for(std::deque<SharedHandle<RequestGroup> >::const_iterator i =
  812. requestGroups_.begin(), eoi = requestGroups_.end(); i != eoi; ++i) {
  813. const std::deque<SharedHandle<Request> >& inFlightReqs =
  814. (*i)->getDownloadContext()->getFirstFileEntry()->getInFlightRequests();
  815. for(std::deque<SharedHandle<Request> >::const_iterator j =
  816. inFlightReqs.begin(), eoj = inFlightReqs.end(); j != eoj; ++j) {
  817. uri::UriStruct us;
  818. if(uri::parse(us, (*j)->getUri())) {
  819. std::vector<Triplet<size_t, int, std::string> >::iterator k;
  820. std::vector<Triplet<size_t, int, std::string> >::iterator eok =
  821. tempHosts.end();
  822. for(k = tempHosts.begin(); k != eok; ++k) {
  823. if((*k).third == us.host) {
  824. ++(*k).first;
  825. break;
  826. }
  827. }
  828. if(k == eok) {
  829. SharedHandle<ServerStat> ss = findServerStat(us.host, us.protocol);
  830. int invDlSpeed = (ss && ss->isOK()) ?
  831. -(static_cast<int>(ss->getDownloadSpeed())) : 0;
  832. tempHosts.push_back(makeTriplet(1, invDlSpeed, us.host));
  833. }
  834. }
  835. }
  836. }
  837. std::sort(tempHosts.begin(), tempHosts.end());
  838. std::transform(tempHosts.begin(), tempHosts.end(),
  839. std::back_inserter(usedHosts), Tuple2Pair<1, 3>());
  840. }
  841. } // namespace aria2