RequestGroupMan.cc 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  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. groupToAdd->releaseRuntimeResource(e);
  320. _downloadResults.push_back(groupToAdd->createDownloadResult());
  321. }
  322. }
  323. _reservedGroups.insert(_reservedGroups.begin(), temp.begin(), temp.end());
  324. if(count > 0) {
  325. e->setNoWait(true);
  326. _logger->debug("%d RequestGroup(s) added.", count);
  327. }
  328. }
  329. void RequestGroupMan::getInitialCommands(std::deque<Command*>& commands,
  330. DownloadEngine* e)
  331. {
  332. for(RequestGroups::iterator itr = _requestGroups.begin();
  333. itr != _requestGroups.end();) {
  334. try {
  335. if((*itr)->isDependencyResolved()) {
  336. configureRequestGroup(*itr);
  337. createInitialCommand(*itr, commands, e,
  338. _option->getAsBool(PREF_USE_HEAD));
  339. ++itr;
  340. } else {
  341. _reservedGroups.push_front((*itr));
  342. itr = _requestGroups.erase(itr);
  343. }
  344. } catch(RecoverableException& e) {
  345. _logger->error(EX_EXCEPTION_CAUGHT, e);
  346. _downloadResults.push_back((*itr)->createDownloadResult());
  347. itr = _requestGroups.erase(itr);
  348. }
  349. }
  350. }
  351. void RequestGroupMan::save()
  352. {
  353. for(RequestGroups::iterator itr = _requestGroups.begin();
  354. itr != _requestGroups.end(); ++itr) {
  355. if((*itr)->allDownloadFinished()) {
  356. (*itr)->getProgressInfoFile()->removeFile();
  357. } else {
  358. try {
  359. (*itr)->getProgressInfoFile()->save();
  360. } catch(RecoverableException& e) {
  361. _logger->error(EX_EXCEPTION_CAUGHT, e);
  362. }
  363. }
  364. }
  365. }
  366. void RequestGroupMan::closeFile()
  367. {
  368. for(RequestGroups::iterator itr = _requestGroups.begin();
  369. itr != _requestGroups.end(); ++itr) {
  370. (*itr)->closeFile();
  371. }
  372. }
  373. RequestGroupMan::DownloadStat RequestGroupMan::getDownloadStat() const
  374. {
  375. size_t finished = 0;
  376. size_t error = 0;
  377. size_t inprogress = 0;
  378. DownloadResult::RESULT lastError = DownloadResult::FINISHED;
  379. for(std::deque<SharedHandle<DownloadResult> >::const_iterator itr = _downloadResults.begin();
  380. itr != _downloadResults.end(); ++itr) {
  381. if((*itr)->result == DownloadResult::FINISHED) {
  382. ++finished;
  383. } else {
  384. ++error;
  385. lastError = (*itr)->result;
  386. }
  387. }
  388. for(RequestGroups::const_iterator itr = _requestGroups.begin();
  389. itr != _requestGroups.end(); ++itr) {
  390. DownloadResultHandle result = (*itr)->createDownloadResult();
  391. if(result->result == DownloadResult::FINISHED) {
  392. ++finished;
  393. } else {
  394. ++inprogress;
  395. }
  396. }
  397. return DownloadStat(finished, error, inprogress, _reservedGroups.size(),
  398. lastError);
  399. }
  400. void RequestGroupMan::showDownloadResults(std::ostream& o) const
  401. {
  402. static const std::string MARK_OK("OK");
  403. static const std::string MARK_ERR("ERR");
  404. static const std::string MARK_INPR("INPR");
  405. // Download Results:
  406. // idx|stat|path/length
  407. // ===+====+=======================================================================
  408. o << "\n"
  409. <<_("Download Results:") << "\n"
  410. << "gid|stat|avg speed |path/URI" << "\n"
  411. << "===+====+===========+==========================================================" << "\n";
  412. int ok = 0;
  413. int err = 0;
  414. int inpr = 0;
  415. for(std::deque<SharedHandle<DownloadResult> >::const_iterator itr = _downloadResults.begin();
  416. itr != _downloadResults.end(); ++itr) {
  417. std::string status;
  418. if((*itr)->result == DownloadResult::FINISHED) {
  419. status = MARK_OK;
  420. ++ok;
  421. } else if((*itr)->result == DownloadResult::IN_PROGRESS) {
  422. status = MARK_INPR;
  423. ++inpr;
  424. } else {
  425. status = MARK_ERR;
  426. ++err;
  427. }
  428. o << formatDownloadResult(status, *itr) << "\n";
  429. }
  430. for(RequestGroups::const_iterator itr = _requestGroups.begin();
  431. itr != _requestGroups.end(); ++itr) {
  432. DownloadResultHandle result = (*itr)->createDownloadResult();
  433. std::string status;
  434. if(result->result == DownloadResult::FINISHED) {
  435. status = MARK_OK;
  436. ++ok;
  437. } else {
  438. // Since this RequestGroup is not processed by ProcessStoppedRequestGroup,
  439. // its download stop time is not reseted.
  440. // Reset download stop time and assign sessionTime here.
  441. (*itr)->getDownloadContext()->resetDownloadStopTime();
  442. result->sessionTime =
  443. (*itr)->getDownloadContext()->calculateSessionTime();
  444. status = MARK_INPR;
  445. ++inpr;
  446. }
  447. o << formatDownloadResult(status, result) << "\n";
  448. }
  449. if(ok > 0 || err > 0 || inpr > 0) {
  450. o << "\n"
  451. << _("Status Legend:") << "\n";
  452. if(ok > 0) {
  453. o << " (OK):download completed.";
  454. }
  455. if(err > 0) {
  456. o << "(ERR):error occurred.";
  457. }
  458. if(inpr > 0) {
  459. o << "(INPR):download in-progress.";
  460. }
  461. o << "\n";
  462. }
  463. }
  464. std::string RequestGroupMan::formatDownloadResult(const std::string& status, const DownloadResultHandle& downloadResult) const
  465. {
  466. std::stringstream o;
  467. o << std::setw(3) << downloadResult->gid << "|"
  468. << std::setw(4) << status << "|"
  469. << std::setw(11);
  470. if(downloadResult->sessionTime > 0) {
  471. o << Util::abbrevSize
  472. (downloadResult->sessionDownloadLength*1000/downloadResult->sessionTime)+
  473. "B/s";
  474. } else {
  475. o << "n/a";
  476. }
  477. o << "|";
  478. if(downloadResult->result == DownloadResult::FINISHED) {
  479. o << downloadResult->filePath;
  480. } else {
  481. if(downloadResult->numUri == 0) {
  482. if(downloadResult->filePath.empty()) {
  483. o << "n/a";
  484. } else {
  485. o << downloadResult->filePath;
  486. }
  487. } else {
  488. o << downloadResult->uri;
  489. if(downloadResult->numUri > 1) {
  490. o << " (" << downloadResult->numUri-1 << "more)";
  491. }
  492. }
  493. }
  494. return o.str();
  495. }
  496. template<typename StringInputIterator, typename FileEntryInputIterator>
  497. static bool sameFilePathExists(StringInputIterator sfirst,
  498. StringInputIterator slast,
  499. FileEntryInputIterator ffirst,
  500. FileEntryInputIterator flast)
  501. {
  502. for(; ffirst != flast; ++ffirst) {
  503. if(std::binary_search(sfirst, slast, (*ffirst)->getPath())) {
  504. return true;
  505. }
  506. }
  507. return false;
  508. }
  509. bool RequestGroupMan::isSameFileBeingDownloaded(RequestGroup* requestGroup) const
  510. {
  511. // TODO it may be good to use dedicated method rather than use
  512. // isPreLocalFileCheckEnabled
  513. if(!requestGroup->isPreLocalFileCheckEnabled()) {
  514. return false;
  515. }
  516. std::deque<std::string> files;
  517. for(RequestGroups::const_iterator itr = _requestGroups.begin();
  518. itr != _requestGroups.end(); ++itr) {
  519. if((*itr).get() != requestGroup) {
  520. std::deque<SharedHandle<FileEntry> > entries =
  521. (*itr)->getDownloadContext()->getFileEntries();
  522. std::transform(entries.begin(), entries.end(),
  523. std::back_inserter(files),
  524. mem_fun_sh(&FileEntry::getPath));
  525. }
  526. }
  527. std::sort(files.begin(), files.end());
  528. std::deque<SharedHandle<FileEntry> > entries =
  529. requestGroup->getDownloadContext()->getFileEntries();
  530. return sameFilePathExists(files.begin(), files.end(),
  531. entries.begin(), entries.end());
  532. }
  533. void RequestGroupMan::halt()
  534. {
  535. for(RequestGroups::const_iterator itr = _requestGroups.begin();
  536. itr != _requestGroups.end(); ++itr) {
  537. (*itr)->setHaltRequested(true);
  538. }
  539. }
  540. void RequestGroupMan::forceHalt()
  541. {
  542. for(RequestGroups::const_iterator itr = _requestGroups.begin();
  543. itr != _requestGroups.end(); ++itr) {
  544. (*itr)->setForceHaltRequested(true);
  545. }
  546. }
  547. TransferStat RequestGroupMan::calculateStat()
  548. {
  549. TransferStat s;
  550. for(std::deque<SharedHandle<RequestGroup> >::const_iterator i =
  551. _requestGroups.begin(); i != _requestGroups.end(); ++i) {
  552. s += (*i)->calculateStat();
  553. }
  554. return s;
  555. }
  556. const std::deque<SharedHandle<DownloadResult> >&
  557. RequestGroupMan::getDownloadResults() const
  558. {
  559. return _downloadResults;
  560. }
  561. SharedHandle<ServerStat>
  562. RequestGroupMan::findServerStat(const std::string& hostname,
  563. const std::string& protocol) const
  564. {
  565. return _serverStatMan->find(hostname, protocol);
  566. }
  567. SharedHandle<ServerStat>
  568. RequestGroupMan::getOrCreateServerStat(const std::string& hostname,
  569. const std::string& protocol)
  570. {
  571. SharedHandle<ServerStat> ss = findServerStat(hostname, protocol);
  572. if(ss.isNull()) {
  573. ss.reset(new ServerStat(hostname, protocol));
  574. addServerStat(ss);
  575. }
  576. return ss;
  577. }
  578. bool RequestGroupMan::addServerStat(const SharedHandle<ServerStat>& serverStat)
  579. {
  580. return _serverStatMan->add(serverStat);
  581. }
  582. bool RequestGroupMan::loadServerStat(const std::string& filename)
  583. {
  584. std::ifstream in(filename.c_str(), std::ios::binary);
  585. if(!in) {
  586. _logger->error(MSG_OPENING_READABLE_SERVER_STAT_FILE_FAILED, filename.c_str());
  587. return false;
  588. }
  589. if(_serverStatMan->load(in)) {
  590. _logger->notice(MSG_SERVER_STAT_LOADED, filename.c_str());
  591. return true;
  592. } else {
  593. _logger->error(MSG_READING_SERVER_STAT_FILE_FAILED, filename.c_str());
  594. return false;
  595. }
  596. }
  597. bool RequestGroupMan::saveServerStat(const std::string& filename) const
  598. {
  599. std::string tempfile = filename+"__temp";
  600. std::ofstream out(tempfile.c_str(), std::ios::binary);
  601. if(!out) {
  602. _logger->error(MSG_OPENING_WRITABLE_SERVER_STAT_FILE_FAILED,
  603. tempfile.c_str());
  604. return false;
  605. }
  606. if (_serverStatMan->save(out)) {
  607. out.close();
  608. if (File(tempfile).renameTo(filename)) {
  609. _logger->notice(MSG_SERVER_STAT_SAVED, filename.c_str());
  610. return true;
  611. }
  612. }
  613. _logger->error(MSG_WRITING_SERVER_STAT_FILE_FAILED, filename.c_str());
  614. return false;
  615. }
  616. void RequestGroupMan::removeStaleServerStat(time_t timeout)
  617. {
  618. _serverStatMan->removeStaleServerStat(timeout);
  619. }
  620. bool RequestGroupMan::doesOverallDownloadSpeedExceed()
  621. {
  622. return _maxOverallDownloadSpeedLimit > 0 &&
  623. _maxOverallDownloadSpeedLimit < calculateStat().getDownloadSpeed();
  624. }
  625. bool RequestGroupMan::doesOverallUploadSpeedExceed()
  626. {
  627. return _maxOverallUploadSpeedLimit > 0 &&
  628. _maxOverallUploadSpeedLimit < calculateStat().getUploadSpeed();
  629. }
  630. } // namespace aria2