RequestGroupMan.cc 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732
  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 <iomanip>
  37. #include <sstream>
  38. #include <ostream>
  39. #include <fstream>
  40. #include <numeric>
  41. #include <algorithm>
  42. #include "BtProgressInfoFile.h"
  43. #include "RecoverableException.h"
  44. #include "RequestGroup.h"
  45. #include "LogFactory.h"
  46. #include "Logger.h"
  47. #include "DownloadEngine.h"
  48. #include "message.h"
  49. #include "a2functional.h"
  50. #include "DownloadResult.h"
  51. #include "DownloadContext.h"
  52. #include "ServerStatMan.h"
  53. #include "ServerStat.h"
  54. #include "PeerStat.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. namespace aria2 {
  66. RequestGroupMan::RequestGroupMan(const RequestGroups& requestGroups,
  67. unsigned int maxSimultaneousDownloads,
  68. const Option* option):
  69. _requestGroups(requestGroups),
  70. _logger(LogFactory::getInstance()),
  71. _maxSimultaneousDownloads(maxSimultaneousDownloads),
  72. _gidCounter(0),
  73. _option(option),
  74. _serverStatMan(new ServerStatMan()),
  75. _maxOverallDownloadSpeedLimit
  76. (option->getAsInt(PREF_MAX_OVERALL_DOWNLOAD_LIMIT)),
  77. _maxOverallUploadSpeedLimit(option->getAsInt(PREF_MAX_OVERALL_UPLOAD_LIMIT))
  78. {}
  79. bool RequestGroupMan::downloadFinished()
  80. {
  81. if(_option->getAsBool(PREF_ENABLE_HTTP_SERVER)) {
  82. return false;
  83. }
  84. if(!_reservedGroups.empty()) {
  85. return false;
  86. }
  87. for(RequestGroups::iterator itr = _requestGroups.begin();
  88. itr != _requestGroups.end(); ++itr) {
  89. if((*itr)->getNumCommand() > 0 || !(*itr)->downloadFinished()) {
  90. return false;
  91. }
  92. }
  93. return true;
  94. }
  95. void RequestGroupMan::addRequestGroup(const RequestGroupHandle& group)
  96. {
  97. _requestGroups.push_back(group);
  98. }
  99. void RequestGroupMan::addReservedGroup(const RequestGroups& groups)
  100. {
  101. _reservedGroups.insert(_reservedGroups.end(), groups.begin(), groups.end());
  102. }
  103. void RequestGroupMan::addReservedGroup(const RequestGroupHandle& group)
  104. {
  105. _reservedGroups.push_back(group);
  106. }
  107. size_t RequestGroupMan::countRequestGroup() const
  108. {
  109. return _requestGroups.size();
  110. }
  111. RequestGroupHandle RequestGroupMan::getRequestGroup(size_t index) const
  112. {
  113. if(index < _requestGroups.size()) {
  114. return _requestGroups[index];
  115. } else {
  116. return SharedHandle<RequestGroup>();
  117. }
  118. }
  119. const std::deque<SharedHandle<RequestGroup> >&
  120. RequestGroupMan::getRequestGroups() const
  121. {
  122. return _requestGroups;
  123. }
  124. template<typename Iterator>
  125. static Iterator findByGID(Iterator first, Iterator last, int32_t gid)
  126. {
  127. for(; first != last; ++first) {
  128. if((*first)->getGID() == gid) {
  129. return first;
  130. }
  131. }
  132. return first;
  133. }
  134. SharedHandle<RequestGroup>
  135. RequestGroupMan::findRequestGroup(int32_t gid) const
  136. {
  137. std::deque<SharedHandle<RequestGroup> >::const_iterator i =
  138. findByGID(_requestGroups.begin(), _requestGroups.end(), gid);
  139. if(i == _requestGroups.end()) {
  140. return SharedHandle<RequestGroup>();
  141. } else {
  142. return *i;
  143. }
  144. }
  145. const std::deque<SharedHandle<RequestGroup> >&
  146. RequestGroupMan::getReservedGroups() const
  147. {
  148. return _reservedGroups;
  149. }
  150. SharedHandle<RequestGroup>
  151. RequestGroupMan::findReservedGroup(int32_t gid) const
  152. {
  153. std::deque<SharedHandle<RequestGroup> >::const_iterator i =
  154. findByGID(_reservedGroups.begin(), _reservedGroups.end(), gid);
  155. if(i == _reservedGroups.end()) {
  156. return SharedHandle<RequestGroup>();
  157. } else {
  158. return *i;
  159. }
  160. }
  161. bool RequestGroupMan::removeReservedGroup(int32_t gid)
  162. {
  163. std::deque<SharedHandle<RequestGroup> >::iterator i =
  164. findByGID(_reservedGroups.begin(), _reservedGroups.end(), gid);
  165. if(i == _reservedGroups.end()) {
  166. return false;
  167. } else {
  168. _reservedGroups.erase(i);
  169. return true;
  170. }
  171. }
  172. class ProcessStoppedRequestGroup {
  173. private:
  174. DownloadEngine* _e;
  175. std::deque<SharedHandle<RequestGroup> >& _reservedGroups;
  176. std::deque<SharedHandle<DownloadResult> >& _downloadResults;
  177. Logger* _logger;
  178. void saveSignature(const SharedHandle<RequestGroup>& group)
  179. {
  180. SharedHandle<Signature> sig =
  181. group->getDownloadContext()->getSignature();
  182. if(!sig.isNull() && !sig->getBody().empty()) {
  183. // filename of signature file is the path to download file followed by
  184. // ".sig".
  185. std::string signatureFile = group->getFilePath()+".sig";
  186. if(sig->save(signatureFile)) {
  187. _logger->notice(MSG_SIGNATURE_SAVED, signatureFile.c_str());
  188. } else {
  189. _logger->notice(MSG_SIGNATURE_NOT_SAVED, signatureFile.c_str());
  190. }
  191. }
  192. }
  193. public:
  194. ProcessStoppedRequestGroup
  195. (DownloadEngine* e,
  196. std::deque<SharedHandle<RequestGroup> >& reservedGroups,
  197. std::deque<SharedHandle<DownloadResult> >& downloadResults):
  198. _e(e),
  199. _reservedGroups(reservedGroups),
  200. _downloadResults(downloadResults),
  201. _logger(LogFactory::getInstance()) {}
  202. void operator()(const SharedHandle<RequestGroup>& group)
  203. {
  204. if(group->getNumCommand() == 0) {
  205. try {
  206. group->closeFile();
  207. if(group->downloadFinished()) {
  208. group->applyLastModifiedTimeToLocalFiles();
  209. group->reportDownloadFinished();
  210. if(group->allDownloadFinished()) {
  211. group->getProgressInfoFile()->removeFile();
  212. saveSignature(group);
  213. } else {
  214. group->getProgressInfoFile()->save();
  215. }
  216. RequestGroups nextGroups;
  217. group->postDownloadProcessing(nextGroups);
  218. if(!nextGroups.empty()) {
  219. _logger->debug
  220. ("Adding %lu RequestGroups as a result of PostDownloadHandler.",
  221. static_cast<unsigned long>(nextGroups.size()));
  222. _reservedGroups.insert(_reservedGroups.begin(),
  223. nextGroups.begin(), nextGroups.end());
  224. }
  225. } else {
  226. group->getProgressInfoFile()->save();
  227. }
  228. } catch(RecoverableException& ex) {
  229. _logger->error(EX_EXCEPTION_CAUGHT, ex);
  230. }
  231. group->releaseRuntimeResource(_e);
  232. _downloadResults.push_back(group->createDownloadResult());
  233. }
  234. }
  235. };
  236. class CollectServerStat {
  237. private:
  238. RequestGroupMan* _requestGroupMan;
  239. public:
  240. CollectServerStat(RequestGroupMan* requestGroupMan):
  241. _requestGroupMan(requestGroupMan) {}
  242. void operator()(const SharedHandle<RequestGroup>& group)
  243. {
  244. if(group->getNumCommand() == 0) {
  245. // Collect statistics during download in PeerStats and update/register
  246. // ServerStatMan
  247. if(!group->getSegmentMan().isNull()) {
  248. const std::deque<SharedHandle<PeerStat> >& peerStats =
  249. group->getSegmentMan()->getPeerStats();
  250. for(std::deque<SharedHandle<PeerStat> >::const_iterator i =
  251. peerStats.begin(); i != peerStats.end(); ++i) {
  252. if((*i)->getHostname().empty() || (*i)->getProtocol().empty()) {
  253. continue;
  254. }
  255. int speed = (*i)->getAvgDownloadSpeed();
  256. if (speed == 0) continue;
  257. SharedHandle<ServerStat> ss =
  258. _requestGroupMan->getOrCreateServerStat((*i)->getHostname(),
  259. (*i)->getProtocol());
  260. ss->increaseCounter();
  261. ss->updateDownloadSpeed(speed);
  262. if(peerStats.size() == 1) {
  263. ss->updateSingleConnectionAvgSpeed(speed);
  264. }
  265. else {
  266. ss->updateMultiConnectionAvgSpeed(speed);
  267. }
  268. }
  269. }
  270. }
  271. }
  272. };
  273. class FindStoppedRequestGroup {
  274. public:
  275. bool operator()(const SharedHandle<RequestGroup>& group) {
  276. return group->getNumCommand() == 0;
  277. }
  278. };
  279. void RequestGroupMan::updateServerStat()
  280. {
  281. std::for_each(_requestGroups.begin(), _requestGroups.end(),
  282. CollectServerStat(this));
  283. }
  284. void RequestGroupMan::removeStoppedGroup(DownloadEngine* e)
  285. {
  286. size_t numPrev = _requestGroups.size();
  287. updateServerStat();
  288. std::for_each(_requestGroups.begin(), _requestGroups.end(),
  289. ProcessStoppedRequestGroup(e, _reservedGroups,
  290. _downloadResults));
  291. _requestGroups.erase(std::remove_if(_requestGroups.begin(),
  292. _requestGroups.end(),
  293. FindStoppedRequestGroup()),
  294. _requestGroups.end());
  295. size_t numRemoved = numPrev-_requestGroups.size();
  296. if(numRemoved > 0) {
  297. _logger->debug("%lu RequestGroup(s) deleted.",
  298. static_cast<unsigned long>(numRemoved));
  299. }
  300. }
  301. void RequestGroupMan::configureRequestGroup
  302. (const SharedHandle<RequestGroup>& requestGroup) const
  303. {
  304. const std::string& uriSelectorValue = _option->get(PREF_URI_SELECTOR);
  305. if(uriSelectorValue == V_FEEDBACK) {
  306. requestGroup->setURISelector
  307. (SharedHandle<URISelector>(new FeedbackURISelector(_serverStatMan)));
  308. } else if(uriSelectorValue == V_INORDER) {
  309. requestGroup->setURISelector
  310. (SharedHandle<URISelector>(new InOrderURISelector()));
  311. } else if(uriSelectorValue == V_ADAPTIVE) {
  312. requestGroup->setURISelector
  313. (SharedHandle<URISelector>(new AdaptiveURISelector(_serverStatMan,
  314. requestGroup.get())));
  315. }
  316. }
  317. static void createInitialCommand(const SharedHandle<RequestGroup>& requestGroup,
  318. std::deque<Command*>& commands,
  319. DownloadEngine* e,
  320. bool useHead)
  321. {
  322. requestGroup->createInitialCommand(commands, e,
  323. useHead ?
  324. Request::METHOD_HEAD :
  325. Request::METHOD_GET);
  326. }
  327. void RequestGroupMan::fillRequestGroupFromReserver(DownloadEngine* e)
  328. {
  329. RequestGroups temp;
  330. removeStoppedGroup(e);
  331. unsigned int count = 0;
  332. for(int num = _maxSimultaneousDownloads-_requestGroups.size();
  333. num > 0 && !_reservedGroups.empty(); --num) {
  334. RequestGroupHandle groupToAdd = _reservedGroups.front();
  335. _reservedGroups.pop_front();
  336. try {
  337. if(!groupToAdd->isDependencyResolved()) {
  338. temp.push_back(groupToAdd);
  339. continue;
  340. }
  341. configureRequestGroup(groupToAdd);
  342. Commands commands;
  343. createInitialCommand(groupToAdd, commands, e,
  344. _option->getAsBool(PREF_USE_HEAD)||
  345. _option->getAsBool(PREF_DRY_RUN));
  346. _requestGroups.push_back(groupToAdd);
  347. ++count;
  348. e->addCommand(commands);
  349. } catch(RecoverableException& ex) {
  350. _logger->error(EX_EXCEPTION_CAUGHT, ex);
  351. groupToAdd->releaseRuntimeResource(e);
  352. _downloadResults.push_back(groupToAdd->createDownloadResult());
  353. }
  354. }
  355. _reservedGroups.insert(_reservedGroups.begin(), temp.begin(), temp.end());
  356. if(count > 0) {
  357. e->setNoWait(true);
  358. _logger->debug("%d RequestGroup(s) added.", count);
  359. }
  360. }
  361. void RequestGroupMan::getInitialCommands(std::deque<Command*>& commands,
  362. DownloadEngine* e)
  363. {
  364. for(RequestGroups::iterator itr = _requestGroups.begin();
  365. itr != _requestGroups.end();) {
  366. try {
  367. if((*itr)->isDependencyResolved()) {
  368. configureRequestGroup(*itr);
  369. createInitialCommand(*itr, commands, e,
  370. _option->getAsBool(PREF_USE_HEAD));
  371. ++itr;
  372. } else {
  373. _reservedGroups.push_front((*itr));
  374. itr = _requestGroups.erase(itr);
  375. }
  376. } catch(RecoverableException& e) {
  377. _logger->error(EX_EXCEPTION_CAUGHT, e);
  378. _downloadResults.push_back((*itr)->createDownloadResult());
  379. itr = _requestGroups.erase(itr);
  380. }
  381. }
  382. }
  383. void RequestGroupMan::save()
  384. {
  385. for(RequestGroups::iterator itr = _requestGroups.begin();
  386. itr != _requestGroups.end(); ++itr) {
  387. if((*itr)->allDownloadFinished()) {
  388. (*itr)->getProgressInfoFile()->removeFile();
  389. } else {
  390. try {
  391. (*itr)->getProgressInfoFile()->save();
  392. } catch(RecoverableException& e) {
  393. _logger->error(EX_EXCEPTION_CAUGHT, e);
  394. }
  395. }
  396. }
  397. }
  398. void RequestGroupMan::closeFile()
  399. {
  400. for(RequestGroups::iterator itr = _requestGroups.begin();
  401. itr != _requestGroups.end(); ++itr) {
  402. (*itr)->closeFile();
  403. }
  404. }
  405. RequestGroupMan::DownloadStat RequestGroupMan::getDownloadStat() const
  406. {
  407. size_t finished = 0;
  408. size_t error = 0;
  409. size_t inprogress = 0;
  410. DownloadResult::RESULT lastError = DownloadResult::FINISHED;
  411. for(std::deque<SharedHandle<DownloadResult> >::const_iterator itr = _downloadResults.begin();
  412. itr != _downloadResults.end(); ++itr) {
  413. if((*itr)->result == DownloadResult::FINISHED) {
  414. ++finished;
  415. } else {
  416. ++error;
  417. lastError = (*itr)->result;
  418. }
  419. }
  420. for(RequestGroups::const_iterator itr = _requestGroups.begin();
  421. itr != _requestGroups.end(); ++itr) {
  422. DownloadResultHandle result = (*itr)->createDownloadResult();
  423. if(result->result == DownloadResult::FINISHED) {
  424. ++finished;
  425. } else {
  426. ++inprogress;
  427. }
  428. }
  429. return DownloadStat(finished, error, inprogress, _reservedGroups.size(),
  430. lastError);
  431. }
  432. void RequestGroupMan::showDownloadResults(std::ostream& o) const
  433. {
  434. static const std::string MARK_OK("OK");
  435. static const std::string MARK_ERR("ERR");
  436. static const std::string MARK_INPR("INPR");
  437. // Download Results:
  438. // idx|stat|path/length
  439. // ===+====+=======================================================================
  440. o << "\n"
  441. <<_("Download Results:") << "\n"
  442. << "gid|stat|avg speed |path/URI" << "\n"
  443. << "===+====+===========+==========================================================" << "\n";
  444. int ok = 0;
  445. int err = 0;
  446. int inpr = 0;
  447. for(std::deque<SharedHandle<DownloadResult> >::const_iterator itr = _downloadResults.begin();
  448. itr != _downloadResults.end(); ++itr) {
  449. std::string status;
  450. if((*itr)->result == DownloadResult::FINISHED) {
  451. status = MARK_OK;
  452. ++ok;
  453. } else if((*itr)->result == DownloadResult::IN_PROGRESS) {
  454. status = MARK_INPR;
  455. ++inpr;
  456. } else {
  457. status = MARK_ERR;
  458. ++err;
  459. }
  460. o << formatDownloadResult(status, *itr) << "\n";
  461. }
  462. for(RequestGroups::const_iterator itr = _requestGroups.begin();
  463. itr != _requestGroups.end(); ++itr) {
  464. DownloadResultHandle result = (*itr)->createDownloadResult();
  465. std::string status;
  466. if(result->result == DownloadResult::FINISHED) {
  467. status = MARK_OK;
  468. ++ok;
  469. } else {
  470. // Since this RequestGroup is not processed by ProcessStoppedRequestGroup,
  471. // its download stop time is not reseted.
  472. // Reset download stop time and assign sessionTime here.
  473. (*itr)->getDownloadContext()->resetDownloadStopTime();
  474. result->sessionTime =
  475. (*itr)->getDownloadContext()->calculateSessionTime();
  476. status = MARK_INPR;
  477. ++inpr;
  478. }
  479. o << formatDownloadResult(status, result) << "\n";
  480. }
  481. if(ok > 0 || err > 0 || inpr > 0) {
  482. o << "\n"
  483. << _("Status Legend:") << "\n";
  484. if(ok > 0) {
  485. o << " (OK):download completed.";
  486. }
  487. if(err > 0) {
  488. o << "(ERR):error occurred.";
  489. }
  490. if(inpr > 0) {
  491. o << "(INPR):download in-progress.";
  492. }
  493. o << "\n";
  494. }
  495. }
  496. std::string RequestGroupMan::formatDownloadResult(const std::string& status, const DownloadResultHandle& downloadResult) const
  497. {
  498. std::stringstream o;
  499. o << std::setw(3) << downloadResult->gid << "|"
  500. << std::setw(4) << status << "|"
  501. << std::setw(11);
  502. if(downloadResult->sessionTime > 0) {
  503. o << Util::abbrevSize
  504. (downloadResult->sessionDownloadLength*1000/downloadResult->sessionTime)+
  505. "B/s";
  506. } else {
  507. o << "n/a";
  508. }
  509. o << "|";
  510. if(downloadResult->result == DownloadResult::FINISHED) {
  511. o << downloadResult->filePath;
  512. } else {
  513. if(downloadResult->numUri == 0) {
  514. if(downloadResult->filePath.empty()) {
  515. o << "n/a";
  516. } else {
  517. o << downloadResult->filePath;
  518. }
  519. } else {
  520. o << downloadResult->uri;
  521. if(downloadResult->numUri > 1) {
  522. o << " (" << downloadResult->numUri-1 << "more)";
  523. }
  524. }
  525. }
  526. return o.str();
  527. }
  528. template<typename StringInputIterator, typename FileEntryInputIterator>
  529. static bool sameFilePathExists(StringInputIterator sfirst,
  530. StringInputIterator slast,
  531. FileEntryInputIterator ffirst,
  532. FileEntryInputIterator flast)
  533. {
  534. for(; ffirst != flast; ++ffirst) {
  535. if(std::binary_search(sfirst, slast, (*ffirst)->getPath())) {
  536. return true;
  537. }
  538. }
  539. return false;
  540. }
  541. bool RequestGroupMan::isSameFileBeingDownloaded(RequestGroup* requestGroup) const
  542. {
  543. // TODO it may be good to use dedicated method rather than use
  544. // isPreLocalFileCheckEnabled
  545. if(!requestGroup->isPreLocalFileCheckEnabled()) {
  546. return false;
  547. }
  548. std::deque<std::string> files;
  549. for(RequestGroups::const_iterator itr = _requestGroups.begin();
  550. itr != _requestGroups.end(); ++itr) {
  551. if((*itr).get() != requestGroup) {
  552. std::deque<SharedHandle<FileEntry> > entries =
  553. (*itr)->getDownloadContext()->getFileEntries();
  554. std::transform(entries.begin(), entries.end(),
  555. std::back_inserter(files),
  556. mem_fun_sh(&FileEntry::getPath));
  557. }
  558. }
  559. std::sort(files.begin(), files.end());
  560. std::deque<SharedHandle<FileEntry> > entries =
  561. requestGroup->getDownloadContext()->getFileEntries();
  562. return sameFilePathExists(files.begin(), files.end(),
  563. entries.begin(), entries.end());
  564. }
  565. void RequestGroupMan::halt()
  566. {
  567. for(RequestGroups::const_iterator itr = _requestGroups.begin();
  568. itr != _requestGroups.end(); ++itr) {
  569. (*itr)->setHaltRequested(true);
  570. }
  571. }
  572. void RequestGroupMan::forceHalt()
  573. {
  574. for(RequestGroups::const_iterator itr = _requestGroups.begin();
  575. itr != _requestGroups.end(); ++itr) {
  576. (*itr)->setForceHaltRequested(true);
  577. }
  578. }
  579. TransferStat RequestGroupMan::calculateStat()
  580. {
  581. TransferStat s;
  582. for(std::deque<SharedHandle<RequestGroup> >::const_iterator i =
  583. _requestGroups.begin(); i != _requestGroups.end(); ++i) {
  584. s += (*i)->calculateStat();
  585. }
  586. return s;
  587. }
  588. const std::deque<SharedHandle<DownloadResult> >&
  589. RequestGroupMan::getDownloadResults() const
  590. {
  591. return _downloadResults;
  592. }
  593. SharedHandle<DownloadResult>
  594. RequestGroupMan::findDownloadResult(int32_t gid) const
  595. {
  596. for(std::deque<SharedHandle<DownloadResult> >::const_iterator i =
  597. _downloadResults.begin(); i != _downloadResults.end(); ++i) {
  598. if((*i)->gid == gid) {
  599. return *i;
  600. }
  601. }
  602. return SharedHandle<DownloadResult>();
  603. }
  604. SharedHandle<ServerStat>
  605. RequestGroupMan::findServerStat(const std::string& hostname,
  606. const std::string& protocol) const
  607. {
  608. return _serverStatMan->find(hostname, protocol);
  609. }
  610. SharedHandle<ServerStat>
  611. RequestGroupMan::getOrCreateServerStat(const std::string& hostname,
  612. const std::string& protocol)
  613. {
  614. SharedHandle<ServerStat> ss = findServerStat(hostname, protocol);
  615. if(ss.isNull()) {
  616. ss.reset(new ServerStat(hostname, protocol));
  617. addServerStat(ss);
  618. }
  619. return ss;
  620. }
  621. bool RequestGroupMan::addServerStat(const SharedHandle<ServerStat>& serverStat)
  622. {
  623. return _serverStatMan->add(serverStat);
  624. }
  625. bool RequestGroupMan::loadServerStat(const std::string& filename)
  626. {
  627. std::ifstream in(filename.c_str(), std::ios::binary);
  628. if(!in) {
  629. _logger->error(MSG_OPENING_READABLE_SERVER_STAT_FILE_FAILED, filename.c_str());
  630. return false;
  631. }
  632. if(_serverStatMan->load(in)) {
  633. _logger->notice(MSG_SERVER_STAT_LOADED, filename.c_str());
  634. return true;
  635. } else {
  636. _logger->error(MSG_READING_SERVER_STAT_FILE_FAILED, filename.c_str());
  637. return false;
  638. }
  639. }
  640. bool RequestGroupMan::saveServerStat(const std::string& filename) const
  641. {
  642. std::string tempfile = filename+"__temp";
  643. std::ofstream out(tempfile.c_str(), std::ios::binary);
  644. if(!out) {
  645. _logger->error(MSG_OPENING_WRITABLE_SERVER_STAT_FILE_FAILED,
  646. tempfile.c_str());
  647. return false;
  648. }
  649. if (_serverStatMan->save(out)) {
  650. out.close();
  651. if (File(tempfile).renameTo(filename)) {
  652. _logger->notice(MSG_SERVER_STAT_SAVED, filename.c_str());
  653. return true;
  654. }
  655. }
  656. _logger->error(MSG_WRITING_SERVER_STAT_FILE_FAILED, filename.c_str());
  657. return false;
  658. }
  659. void RequestGroupMan::removeStaleServerStat(time_t timeout)
  660. {
  661. _serverStatMan->removeStaleServerStat(timeout);
  662. }
  663. bool RequestGroupMan::doesOverallDownloadSpeedExceed()
  664. {
  665. return _maxOverallDownloadSpeedLimit > 0 &&
  666. _maxOverallDownloadSpeedLimit < calculateStat().getDownloadSpeed();
  667. }
  668. bool RequestGroupMan::doesOverallUploadSpeedExceed()
  669. {
  670. return _maxOverallUploadSpeedLimit > 0 &&
  671. _maxOverallUploadSpeedLimit < calculateStat().getUploadSpeed();
  672. }
  673. } // namespace aria2