RequestGroupMan.cc 27 KB

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