RequestGroupMan.cc 30 KB

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