RequestGroupMan.cc 29 KB

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