RequestGroupMan.cc 20 KB

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