RequestGroupMan.cc 28 KB

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