RequestGroupMan.cc 23 KB

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