RequestGroupMan.cc 30 KB

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