RequestGroupMan.cc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  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->applyLastModifiedTimeToLocalFiles();
  147. group->reportDownloadFinished();
  148. if(group->allDownloadFinished()) {
  149. group->getProgressInfoFile()->removeFile();
  150. saveSignature(group);
  151. } else {
  152. group->getProgressInfoFile()->save();
  153. }
  154. RequestGroups nextGroups;
  155. group->postDownloadProcessing(nextGroups);
  156. if(!nextGroups.empty()) {
  157. _logger->debug
  158. ("Adding %lu RequestGroups as a result of PostDownloadHandler.",
  159. static_cast<unsigned long>(nextGroups.size()));
  160. _reservedGroups.insert(_reservedGroups.begin(),
  161. nextGroups.begin(), nextGroups.end());
  162. }
  163. } else {
  164. group->getProgressInfoFile()->save();
  165. }
  166. } catch(RecoverableException& ex) {
  167. _logger->error(EX_EXCEPTION_CAUGHT, ex);
  168. }
  169. group->releaseRuntimeResource();
  170. _downloadResults.push_back(group->createDownloadResult());
  171. }
  172. }
  173. };
  174. class CollectServerStat {
  175. private:
  176. RequestGroupMan* _requestGroupMan;
  177. public:
  178. CollectServerStat(RequestGroupMan* requestGroupMan):
  179. _requestGroupMan(requestGroupMan) {}
  180. void operator()(const SharedHandle<RequestGroup>& group)
  181. {
  182. if(group->getNumCommand() == 0) {
  183. // Collect statistics during download in PeerStats and update/register
  184. // ServerStatMan
  185. if(!group->getSegmentMan().isNull()) {
  186. const std::deque<SharedHandle<PeerStat> >& peerStats =
  187. group->getSegmentMan()->getPeerStats();
  188. for(std::deque<SharedHandle<PeerStat> >::const_iterator i =
  189. peerStats.begin(); i != peerStats.end(); ++i) {
  190. if((*i)->getHostname().empty() || (*i)->getProtocol().empty()) {
  191. continue;
  192. }
  193. SharedHandle<ServerStat> ss =
  194. _requestGroupMan->getOrCreateServerStat((*i)->getHostname(),
  195. (*i)->getProtocol());
  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("%lu RequestGroup(s) deleted.",
  226. static_cast<unsigned long>(numRemoved));
  227. }
  228. }
  229. void RequestGroupMan::configureRequestGroup
  230. (const SharedHandle<RequestGroup>& requestGroup) const
  231. {
  232. const std::string& uriSelectorValue = _option->get(PREF_URI_SELECTOR);
  233. if(uriSelectorValue == V_FEEDBACK) {
  234. requestGroup->setURISelector
  235. (SharedHandle<URISelector>(new ServerStatURISelector(_serverStatMan)));
  236. } else if(uriSelectorValue == V_INORDER) {
  237. requestGroup->setURISelector
  238. (SharedHandle<URISelector>(new InOrderURISelector()));
  239. }
  240. }
  241. void RequestGroupMan::fillRequestGroupFromReserver(DownloadEngine* e)
  242. {
  243. RequestGroups temp;
  244. removeStoppedGroup();
  245. unsigned int count = 0;
  246. for(int num = _maxSimultaneousDownloads-_requestGroups.size();
  247. num > 0 && _reservedGroups.size() > 0; --num) {
  248. RequestGroupHandle groupToAdd = _reservedGroups.front();
  249. _reservedGroups.pop_front();
  250. try {
  251. if(!groupToAdd->isDependencyResolved()) {
  252. temp.push_back(groupToAdd);
  253. continue;
  254. }
  255. configureRequestGroup(groupToAdd);
  256. Commands commands;
  257. groupToAdd->createInitialCommand(commands, e);
  258. _requestGroups.push_back(groupToAdd);
  259. ++count;
  260. e->addCommand(commands);
  261. } catch(RecoverableException& ex) {
  262. _logger->error(EX_EXCEPTION_CAUGHT, ex);
  263. _downloadResults.push_back(groupToAdd->createDownloadResult());
  264. }
  265. }
  266. _reservedGroups.insert(_reservedGroups.begin(), temp.begin(), temp.end());
  267. if(count > 0) {
  268. e->setNoWait(true);
  269. _logger->debug("%d RequestGroup(s) added.", count);
  270. }
  271. }
  272. void RequestGroupMan::getInitialCommands(std::deque<Command*>& commands,
  273. DownloadEngine* e)
  274. {
  275. for(RequestGroups::iterator itr = _requestGroups.begin();
  276. itr != _requestGroups.end();) {
  277. try {
  278. if((*itr)->isDependencyResolved()) {
  279. configureRequestGroup(*itr);
  280. (*itr)->createInitialCommand(commands, e);
  281. ++itr;
  282. } else {
  283. _reservedGroups.push_front((*itr));
  284. itr = _requestGroups.erase(itr);
  285. }
  286. } catch(RecoverableException& e) {
  287. _logger->error(EX_EXCEPTION_CAUGHT, e);
  288. _downloadResults.push_back((*itr)->createDownloadResult());
  289. itr = _requestGroups.erase(itr);
  290. }
  291. }
  292. }
  293. void RequestGroupMan::save()
  294. {
  295. for(RequestGroups::iterator itr = _requestGroups.begin();
  296. itr != _requestGroups.end(); ++itr) {
  297. if((*itr)->allDownloadFinished()) {
  298. (*itr)->getProgressInfoFile()->removeFile();
  299. } else {
  300. try {
  301. (*itr)->getProgressInfoFile()->save();
  302. } catch(RecoverableException& e) {
  303. _logger->error(EX_EXCEPTION_CAUGHT, e);
  304. }
  305. }
  306. }
  307. }
  308. void RequestGroupMan::closeFile()
  309. {
  310. for(RequestGroups::iterator itr = _requestGroups.begin();
  311. itr != _requestGroups.end(); ++itr) {
  312. (*itr)->closeFile();
  313. }
  314. }
  315. RequestGroupMan::DownloadStat RequestGroupMan::getDownloadStat() const
  316. {
  317. DownloadStat stat;
  318. size_t finished = 0;
  319. size_t error = 0;
  320. size_t inprogress = 0;
  321. for(std::deque<SharedHandle<DownloadResult> >::const_iterator itr = _downloadResults.begin();
  322. itr != _downloadResults.end(); ++itr) {
  323. if((*itr)->result == DownloadResult::FINISHED) {
  324. ++finished;
  325. } else {
  326. ++error;
  327. }
  328. }
  329. for(RequestGroups::const_iterator itr = _requestGroups.begin();
  330. itr != _requestGroups.end(); ++itr) {
  331. DownloadResultHandle result = (*itr)->createDownloadResult();
  332. if(result->result == DownloadResult::FINISHED) {
  333. ++finished;
  334. } else {
  335. ++inprogress;
  336. }
  337. }
  338. stat.setCompleted(finished);
  339. stat.setError(error);
  340. stat.setInProgress(inprogress);
  341. stat.setWaiting(_reservedGroups.size());
  342. return stat;
  343. }
  344. void RequestGroupMan::showDownloadResults(std::ostream& o) const
  345. {
  346. static const std::string MARK_OK("OK");
  347. static const std::string MARK_ERR("ERR");
  348. static const std::string MARK_INPR("INPR");
  349. // Download Results:
  350. // idx|stat|path/length
  351. // ===+====+=======================================================================
  352. o << "\n"
  353. <<_("Download Results:") << "\n"
  354. << "gid|stat|path/URI" << "\n"
  355. << "===+====+======================================================================" << "\n";
  356. for(std::deque<SharedHandle<DownloadResult> >::const_iterator itr = _downloadResults.begin();
  357. itr != _downloadResults.end(); ++itr) {
  358. o << formatDownloadResult((*itr)->result == DownloadResult::FINISHED ?
  359. MARK_OK : MARK_ERR, *itr) << "\n";
  360. }
  361. for(RequestGroups::const_iterator itr = _requestGroups.begin();
  362. itr != _requestGroups.end(); ++itr) {
  363. DownloadResultHandle result = (*itr)->createDownloadResult();
  364. o << formatDownloadResult(result->result == DownloadResult::FINISHED ?
  365. MARK_OK : MARK_INPR, result) << "\n";
  366. }
  367. o << "\n"
  368. << _("Status Legend:") << "\n"
  369. << " (OK):download completed.(ERR):error occurred.(INPR):download in-progress." << "\n";
  370. }
  371. std::string RequestGroupMan::formatDownloadResult(const std::string& status, const DownloadResultHandle& downloadResult) const
  372. {
  373. std::stringstream o;
  374. o << std::setw(3) << downloadResult->gid << "|"
  375. << std::setw(4) << status << "|";
  376. if(downloadResult->result == DownloadResult::FINISHED) {
  377. o << downloadResult->filePath;
  378. } else {
  379. if(downloadResult->numUri == 0) {
  380. if(downloadResult->filePath.empty()) {
  381. o << "n/a";
  382. } else {
  383. o << downloadResult->filePath;
  384. }
  385. } else {
  386. o << downloadResult->uri;
  387. if(downloadResult->numUri > 1) {
  388. o << " (" << downloadResult->numUri-1 << "more)";
  389. }
  390. }
  391. }
  392. return o.str();
  393. }
  394. bool RequestGroupMan::isSameFileBeingDownloaded(RequestGroup* requestGroup) const
  395. {
  396. // TODO it may be good to use dedicated method rather than use isPreLocalFileCheckEnabled
  397. if(!requestGroup->isPreLocalFileCheckEnabled()) {
  398. return false;
  399. }
  400. for(RequestGroups::const_iterator itr = _requestGroups.begin();
  401. itr != _requestGroups.end(); ++itr) {
  402. if((*itr).get() != requestGroup &&
  403. (*itr)->getFilePath() == requestGroup->getFilePath()) {
  404. return true;
  405. }
  406. }
  407. return false;
  408. }
  409. void RequestGroupMan::halt()
  410. {
  411. for(RequestGroups::const_iterator itr = _requestGroups.begin();
  412. itr != _requestGroups.end(); ++itr) {
  413. (*itr)->setHaltRequested(true);
  414. }
  415. }
  416. void RequestGroupMan::forceHalt()
  417. {
  418. for(RequestGroups::const_iterator itr = _requestGroups.begin();
  419. itr != _requestGroups.end(); ++itr) {
  420. (*itr)->setForceHaltRequested(true);
  421. }
  422. }
  423. TransferStat RequestGroupMan::calculateStat()
  424. {
  425. return std::accumulate(_requestGroups.begin(), _requestGroups.end(), TransferStat(),
  426. adopt2nd(std::plus<TransferStat>(), mem_fun_sh(&RequestGroup::calculateStat)));
  427. }
  428. const std::deque<SharedHandle<DownloadResult> >&
  429. RequestGroupMan::getDownloadResults() const
  430. {
  431. return _downloadResults;
  432. }
  433. SharedHandle<ServerStat>
  434. RequestGroupMan::findServerStat(const std::string& hostname,
  435. const std::string& protocol) const
  436. {
  437. return _serverStatMan->find(hostname, protocol);
  438. }
  439. SharedHandle<ServerStat>
  440. RequestGroupMan::getOrCreateServerStat(const std::string& hostname,
  441. const std::string& protocol)
  442. {
  443. SharedHandle<ServerStat> ss = findServerStat(hostname, protocol);
  444. if(ss.isNull()) {
  445. ss.reset(new ServerStat(hostname, protocol));
  446. addServerStat(ss);
  447. }
  448. return ss;
  449. }
  450. bool RequestGroupMan::addServerStat(const SharedHandle<ServerStat>& serverStat)
  451. {
  452. return _serverStatMan->add(serverStat);
  453. }
  454. bool RequestGroupMan::loadServerStat(const std::string& filename)
  455. {
  456. std::ifstream in(filename.c_str());
  457. if(!in) {
  458. _logger->error(MSG_OPENING_READABLE_SERVER_STAT_FILE_FAILED, filename.c_str());
  459. return false;
  460. }
  461. if(_serverStatMan->load(in)) {
  462. _logger->notice(MSG_SERVER_STAT_LOADED, filename.c_str());
  463. return true;
  464. } else {
  465. _logger->error(MSG_READING_SERVER_STAT_FILE_FAILED, filename.c_str());
  466. return false;
  467. }
  468. }
  469. bool RequestGroupMan::saveServerStat(const std::string& filename) const
  470. {
  471. std::string tempfile = filename+"__temp";
  472. std::ofstream out(tempfile.c_str());
  473. if(!out) {
  474. _logger->error(MSG_OPENING_WRITABLE_SERVER_STAT_FILE_FAILED,
  475. tempfile.c_str());
  476. return false;
  477. }
  478. if(_serverStatMan->save(out) && File(tempfile).renameTo(filename)) {
  479. _logger->notice(MSG_SERVER_STAT_SAVED, filename.c_str());
  480. return true;
  481. } else {
  482. _logger->error(MSG_WRITING_SERVER_STAT_FILE_FAILED, filename.c_str());
  483. return false;
  484. }
  485. }
  486. void RequestGroupMan::removeStaleServerStat(time_t timeout)
  487. {
  488. _serverStatMan->removeStaleServerStat(timeout);
  489. }
  490. } // namespace aria2