RequestGroupMan.cc 27 KB

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