RequestGroupMan.cc 34 KB

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