RequestGroupMan.cc 15 KB

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