RequestGroupMan.cc 29 KB

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