RequestGroupMan.cc 28 KB

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