RequestGroupMan.cc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  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 "BtProgressInfoFile.h"
  37. #include "RecoverableException.h"
  38. #include "RequestGroup.h"
  39. #include "LogFactory.h"
  40. #include "Logger.h"
  41. #include "DownloadEngine.h"
  42. #include "message.h"
  43. #include "a2functional.h"
  44. #include "DownloadResult.h"
  45. #include "DownloadContext.h"
  46. #include "ServerStatMan.h"
  47. #include "ServerStat.h"
  48. #include "PeerStat.h"
  49. #include "SegmentMan.h"
  50. #include "ServerStatURISelector.h"
  51. #include "InOrderURISelector.h"
  52. #include "Option.h"
  53. #include "prefs.h"
  54. #include <iomanip>
  55. #include <sstream>
  56. #include <ostream>
  57. #include <numeric>
  58. #include <algorithm>
  59. namespace aria2 {
  60. RequestGroupMan::RequestGroupMan(const RequestGroups& requestGroups,
  61. unsigned int maxSimultaneousDownloads,
  62. const Option* option):
  63. _requestGroups(requestGroups),
  64. _logger(LogFactory::getInstance()),
  65. _maxSimultaneousDownloads(maxSimultaneousDownloads),
  66. _gidCounter(0),
  67. _option(option),
  68. _serverStatMan(new ServerStatMan()) {}
  69. bool RequestGroupMan::downloadFinished()
  70. {
  71. if(!_reservedGroups.empty()) {
  72. return false;
  73. }
  74. for(RequestGroups::iterator itr = _requestGroups.begin();
  75. itr != _requestGroups.end(); ++itr) {
  76. if((*itr)->getNumCommand() > 0 || !(*itr)->downloadFinished()) {
  77. return false;
  78. }
  79. }
  80. return true;
  81. }
  82. void RequestGroupMan::addRequestGroup(const RequestGroupHandle& group)
  83. {
  84. _requestGroups.push_back(group);
  85. }
  86. void RequestGroupMan::addReservedGroup(const RequestGroups& groups)
  87. {
  88. _reservedGroups.insert(_reservedGroups.end(), groups.begin(), groups.end());
  89. }
  90. void RequestGroupMan::addReservedGroup(const RequestGroupHandle& group)
  91. {
  92. _reservedGroups.push_back(group);
  93. }
  94. size_t RequestGroupMan::countRequestGroup() const
  95. {
  96. return _requestGroups.size();
  97. }
  98. RequestGroupHandle RequestGroupMan::getRequestGroup(size_t index) const
  99. {
  100. if(index < _requestGroups.size()) {
  101. return _requestGroups[index];
  102. } else {
  103. return SharedHandle<RequestGroup>();
  104. }
  105. }
  106. const std::deque<SharedHandle<RequestGroup> >&
  107. RequestGroupMan::getRequestGroups() const
  108. {
  109. return _requestGroups;
  110. }
  111. class ProcessStoppedRequestGroup {
  112. private:
  113. std::deque<SharedHandle<RequestGroup> >& _reservedGroups;
  114. std::deque<SharedHandle<DownloadResult> >& _downloadResults;
  115. Logger* _logger;
  116. void saveSignature(const SharedHandle<RequestGroup>& group)
  117. {
  118. SharedHandle<Signature> sig =
  119. group->getDownloadContext()->getSignature();
  120. if(!sig.isNull() && !sig->getBody().empty()) {
  121. // filename of signature file is the path to download file followed by
  122. // ".sig".
  123. std::string signatureFile = group->getFilePath()+".sig";
  124. if(sig->save(signatureFile)) {
  125. _logger->notice(MSG_SIGNATURE_SAVED, signatureFile.c_str());
  126. } else {
  127. _logger->notice(MSG_SIGNATURE_NOT_SAVED, signatureFile.c_str());
  128. }
  129. }
  130. }
  131. public:
  132. ProcessStoppedRequestGroup
  133. (std::deque<SharedHandle<RequestGroup> >& reservedGroups,
  134. std::deque<SharedHandle<DownloadResult> >& downloadResults):
  135. _reservedGroups(reservedGroups),
  136. _downloadResults(downloadResults),
  137. _logger(LogFactory::getInstance()) {}
  138. void operator()(const SharedHandle<RequestGroup>& group)
  139. {
  140. if(group->getNumCommand() == 0) {
  141. try {
  142. group->closeFile();
  143. if(group->downloadFinished()) {
  144. group->reportDownloadFinished();
  145. if(group->allDownloadFinished()) {
  146. group->getProgressInfoFile()->removeFile();
  147. saveSignature(group);
  148. } else {
  149. group->getProgressInfoFile()->save();
  150. }
  151. RequestGroups nextGroups;
  152. group->postDownloadProcessing(nextGroups);
  153. if(!nextGroups.empty()) {
  154. _logger->debug("Adding %zu RequestGroups as a result of PostDownloadHandler.", nextGroups.size());
  155. _reservedGroups.insert(_reservedGroups.begin(),
  156. nextGroups.begin(), nextGroups.end());
  157. }
  158. } else {
  159. group->getProgressInfoFile()->save();
  160. }
  161. } catch(RecoverableException& ex) {
  162. _logger->error(EX_EXCEPTION_CAUGHT, ex);
  163. }
  164. group->releaseRuntimeResource();
  165. _downloadResults.push_back(group->createDownloadResult());
  166. }
  167. }
  168. };
  169. class CollectServerStat {
  170. private:
  171. RequestGroupMan* _requestGroupMan;
  172. public:
  173. CollectServerStat(RequestGroupMan* requestGroupMan):
  174. _requestGroupMan(requestGroupMan) {}
  175. void operator()(const SharedHandle<RequestGroup>& group)
  176. {
  177. if(group->getNumCommand() == 0) {
  178. // Collect statistics during download in PeerStats and update/register
  179. // ServerStatMan
  180. if(!group->getSegmentMan().isNull()) {
  181. const std::deque<SharedHandle<PeerStat> >& peerStats =
  182. group->getSegmentMan()->getPeerStats();
  183. for(std::deque<SharedHandle<PeerStat> >::const_iterator i =
  184. peerStats.begin(); i != peerStats.end(); ++i) {
  185. if((*i)->getHostname().empty() || (*i)->getProtocol().empty()) {
  186. continue;
  187. }
  188. SharedHandle<ServerStat> ss =
  189. _requestGroupMan->findServerStat((*i)->getHostname(),
  190. (*i)->getProtocol());
  191. if(ss.isNull()) {
  192. ss.reset(new ServerStat((*i)->getHostname(),
  193. (*i)->getProtocol()));
  194. _requestGroupMan->addServerStat(ss);
  195. }
  196. ss->updateDownloadSpeed((*i)->getAvgDownloadSpeed());
  197. }
  198. }
  199. }
  200. }
  201. };
  202. class FindStoppedRequestGroup {
  203. public:
  204. bool operator()(const SharedHandle<RequestGroup>& group) {
  205. return group->getNumCommand() == 0;
  206. }
  207. };
  208. void RequestGroupMan::updateServerStat()
  209. {
  210. std::for_each(_requestGroups.begin(), _requestGroups.end(),
  211. CollectServerStat(this));
  212. }
  213. void RequestGroupMan::removeStoppedGroup()
  214. {
  215. size_t numPrev = _requestGroups.size();
  216. updateServerStat();
  217. std::for_each(_requestGroups.begin(), _requestGroups.end(),
  218. ProcessStoppedRequestGroup(_reservedGroups, _downloadResults));
  219. _requestGroups.erase(std::remove_if(_requestGroups.begin(),
  220. _requestGroups.end(),
  221. FindStoppedRequestGroup()),
  222. _requestGroups.end());
  223. size_t numRemoved = numPrev-_requestGroups.size();
  224. if(numRemoved > 0) {
  225. _logger->debug("%zu RequestGroup(s) deleted.", numRemoved);
  226. }
  227. }
  228. void RequestGroupMan::configureRequestGroup
  229. (const SharedHandle<RequestGroup>& requestGroup) const
  230. {
  231. const std::string& uriSelectorValue = _option->get(PREF_URI_SELECTOR);
  232. if(uriSelectorValue == V_FEEDBACK) {
  233. requestGroup->setURISelector
  234. (SharedHandle<URISelector>(new ServerStatURISelector(_serverStatMan)));
  235. } else if(uriSelectorValue == V_INORDER) {
  236. requestGroup->setURISelector
  237. (SharedHandle<URISelector>(new InOrderURISelector()));
  238. }
  239. }
  240. void RequestGroupMan::fillRequestGroupFromReserver(DownloadEngine* e)
  241. {
  242. RequestGroups temp;
  243. removeStoppedGroup();
  244. unsigned int count = 0;
  245. for(int num = _maxSimultaneousDownloads-_requestGroups.size();
  246. num > 0 && _reservedGroups.size() > 0; --num) {
  247. RequestGroupHandle groupToAdd = _reservedGroups.front();
  248. _reservedGroups.pop_front();
  249. try {
  250. if(!groupToAdd->isDependencyResolved()) {
  251. temp.push_back(groupToAdd);
  252. continue;
  253. }
  254. configureRequestGroup(groupToAdd);
  255. Commands commands;
  256. groupToAdd->createInitialCommand(commands, e);
  257. _requestGroups.push_back(groupToAdd);
  258. ++count;
  259. e->addCommand(commands);
  260. } catch(RecoverableException& ex) {
  261. _logger->error(EX_EXCEPTION_CAUGHT, ex);
  262. _downloadResults.push_back(groupToAdd->createDownloadResult());
  263. }
  264. }
  265. _reservedGroups.insert(_reservedGroups.begin(), temp.begin(), temp.end());
  266. if(count > 0) {
  267. e->setNoWait(true);
  268. _logger->debug("%d RequestGroup(s) added.", count);
  269. }
  270. }
  271. void RequestGroupMan::getInitialCommands(std::deque<Command*>& commands,
  272. DownloadEngine* e)
  273. {
  274. for(RequestGroups::iterator itr = _requestGroups.begin();
  275. itr != _requestGroups.end();) {
  276. try {
  277. if((*itr)->isDependencyResolved()) {
  278. configureRequestGroup(*itr);
  279. (*itr)->createInitialCommand(commands, e);
  280. ++itr;
  281. } else {
  282. _reservedGroups.push_front((*itr));
  283. itr = _requestGroups.erase(itr);
  284. }
  285. } catch(RecoverableException& e) {
  286. _logger->error(EX_EXCEPTION_CAUGHT, e);
  287. _downloadResults.push_back((*itr)->createDownloadResult());
  288. itr = _requestGroups.erase(itr);
  289. }
  290. }
  291. }
  292. void RequestGroupMan::save()
  293. {
  294. for(RequestGroups::iterator itr = _requestGroups.begin();
  295. itr != _requestGroups.end(); ++itr) {
  296. if((*itr)->allDownloadFinished()) {
  297. (*itr)->getProgressInfoFile()->removeFile();
  298. } else {
  299. try {
  300. (*itr)->getProgressInfoFile()->save();
  301. } catch(RecoverableException& e) {
  302. _logger->error(EX_EXCEPTION_CAUGHT, e);
  303. }
  304. }
  305. }
  306. }
  307. void RequestGroupMan::closeFile()
  308. {
  309. for(RequestGroups::iterator itr = _requestGroups.begin();
  310. itr != _requestGroups.end(); ++itr) {
  311. (*itr)->closeFile();
  312. }
  313. }
  314. RequestGroupMan::DownloadStat RequestGroupMan::getDownloadStat() const
  315. {
  316. DownloadStat stat;
  317. size_t finished = 0;
  318. size_t error = 0;
  319. size_t inprogress = 0;
  320. for(std::deque<SharedHandle<DownloadResult> >::const_iterator itr = _downloadResults.begin();
  321. itr != _downloadResults.end(); ++itr) {
  322. if((*itr)->result == DownloadResult::FINISHED) {
  323. ++finished;
  324. } else {
  325. ++error;
  326. }
  327. }
  328. for(RequestGroups::const_iterator itr = _requestGroups.begin();
  329. itr != _requestGroups.end(); ++itr) {
  330. DownloadResultHandle result = (*itr)->createDownloadResult();
  331. if(result->result == DownloadResult::FINISHED) {
  332. ++finished;
  333. } else {
  334. ++inprogress;
  335. }
  336. }
  337. stat.setCompleted(finished);
  338. stat.setError(error);
  339. stat.setInProgress(inprogress);
  340. stat.setWaiting(_reservedGroups.size());
  341. return stat;
  342. }
  343. void RequestGroupMan::showDownloadResults(std::ostream& o) const
  344. {
  345. static const std::string MARK_OK("OK");
  346. static const std::string MARK_ERR("ERR");
  347. static const std::string MARK_INPR("INPR");
  348. // Download Results:
  349. // idx|stat|path/length
  350. // ===+====+=======================================================================
  351. o << "\n"
  352. <<_("Download Results:") << "\n"
  353. << "gid|stat|path/URI" << "\n"
  354. << "===+====+======================================================================" << "\n";
  355. for(std::deque<SharedHandle<DownloadResult> >::const_iterator itr = _downloadResults.begin();
  356. itr != _downloadResults.end(); ++itr) {
  357. o << formatDownloadResult((*itr)->result == DownloadResult::FINISHED ?
  358. MARK_OK : MARK_ERR, *itr) << "\n";
  359. }
  360. for(RequestGroups::const_iterator itr = _requestGroups.begin();
  361. itr != _requestGroups.end(); ++itr) {
  362. DownloadResultHandle result = (*itr)->createDownloadResult();
  363. o << formatDownloadResult(result->result == DownloadResult::FINISHED ?
  364. MARK_OK : MARK_INPR, result) << "\n";
  365. }
  366. o << "\n"
  367. << _("Status Legend:") << "\n"
  368. << " (OK):download completed.(ERR):error occurred.(INPR):download in-progress." << "\n";
  369. }
  370. std::string RequestGroupMan::formatDownloadResult(const std::string& status, const DownloadResultHandle& downloadResult) const
  371. {
  372. std::stringstream o;
  373. o << std::setw(3) << downloadResult->gid << "|"
  374. << std::setw(4) << status << "|";
  375. if(downloadResult->result == DownloadResult::FINISHED) {
  376. o << downloadResult->filePath;
  377. } else {
  378. if(downloadResult->numUri == 0) {
  379. if(downloadResult->filePath.empty()) {
  380. o << "n/a";
  381. } else {
  382. o << downloadResult->filePath;
  383. }
  384. } else {
  385. o << downloadResult->uri;
  386. if(downloadResult->numUri > 1) {
  387. o << " (" << downloadResult->numUri-1 << "more)";
  388. }
  389. }
  390. }
  391. return o.str();
  392. }
  393. bool RequestGroupMan::isSameFileBeingDownloaded(RequestGroup* requestGroup) const
  394. {
  395. // TODO it may be good to use dedicated method rather than use isPreLocalFileCheckEnabled
  396. if(!requestGroup->isPreLocalFileCheckEnabled()) {
  397. return false;
  398. }
  399. for(RequestGroups::const_iterator itr = _requestGroups.begin();
  400. itr != _requestGroups.end(); ++itr) {
  401. if((*itr).get() != requestGroup &&
  402. (*itr)->getFilePath() == requestGroup->getFilePath()) {
  403. return true;
  404. }
  405. }
  406. return false;
  407. }
  408. void RequestGroupMan::halt()
  409. {
  410. for(RequestGroups::const_iterator itr = _requestGroups.begin();
  411. itr != _requestGroups.end(); ++itr) {
  412. (*itr)->setHaltRequested(true);
  413. }
  414. }
  415. void RequestGroupMan::forceHalt()
  416. {
  417. for(RequestGroups::const_iterator itr = _requestGroups.begin();
  418. itr != _requestGroups.end(); ++itr) {
  419. (*itr)->setForceHaltRequested(true);
  420. }
  421. }
  422. TransferStat RequestGroupMan::calculateStat()
  423. {
  424. return std::accumulate(_requestGroups.begin(), _requestGroups.end(), TransferStat(),
  425. adopt2nd(std::plus<TransferStat>(), mem_fun_sh(&RequestGroup::calculateStat)));
  426. }
  427. const std::deque<SharedHandle<DownloadResult> >&
  428. RequestGroupMan::getDownloadResults() const
  429. {
  430. return _downloadResults;
  431. }
  432. SharedHandle<ServerStat>
  433. RequestGroupMan::findServerStat(const std::string& hostname,
  434. const std::string& protocol) const
  435. {
  436. return _serverStatMan->find(hostname, protocol);
  437. }
  438. bool RequestGroupMan::addServerStat(const SharedHandle<ServerStat>& serverStat)
  439. {
  440. return _serverStatMan->add(serverStat);
  441. }
  442. } // namespace aria2