RequestGroupMan.cc 23 KB

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