RequestGroupMan.cc 27 KB

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