RequestGroupMan.cc 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915
  1. /* <!-- copyright */
  2. /*
  3. * aria2 - The high speed download utility
  4. *
  5. * Copyright (C) 2006 Tatsuhiro Tsujikawa
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. *
  21. * In addition, as a special exception, the copyright holders give
  22. * permission to link the code of portions of this program with the
  23. * OpenSSL library under certain conditions as described in each
  24. * individual source file, and distribute linked combinations
  25. * including the two.
  26. * You must obey the GNU General Public License in all respects
  27. * for all of the code used other than OpenSSL. If you modify
  28. * file(s) with this exception, you may extend this exception to your
  29. * version of the file(s), but you are not obligated to do so. If you
  30. * do not wish to do so, delete this exception statement from your
  31. * version. If you delete this exception statement from all source
  32. * files in the program, then also delete it here.
  33. */
  34. /* copyright --> */
  35. #include "RequestGroupMan.h"
  36. #include <unistd.h>
  37. #include <cstring>
  38. #include <iomanip>
  39. #include <sstream>
  40. #include <ostream>
  41. #include <fstream>
  42. #include <numeric>
  43. #include <algorithm>
  44. #include "BtProgressInfoFile.h"
  45. #include "RecoverableException.h"
  46. #include "RequestGroup.h"
  47. #include "LogFactory.h"
  48. #include "Logger.h"
  49. #include "DownloadEngine.h"
  50. #include "message.h"
  51. #include "a2functional.h"
  52. #include "DownloadResult.h"
  53. #include "DownloadContext.h"
  54. #include "ServerStatMan.h"
  55. #include "ServerStat.h"
  56. #include "PeerStat.h"
  57. #include "SegmentMan.h"
  58. #include "FeedbackURISelector.h"
  59. #include "InOrderURISelector.h"
  60. #include "AdaptiveURISelector.h"
  61. #include "Option.h"
  62. #include "prefs.h"
  63. #include "File.h"
  64. #include "util.h"
  65. #include "Command.h"
  66. #include "FileEntry.h"
  67. #include "StringFormat.h"
  68. #include "FileAllocationEntry.h"
  69. #include "CheckIntegrityEntry.h"
  70. #include "Segment.h"
  71. #include "DlAbortEx.h"
  72. namespace aria2 {
  73. RequestGroupMan::RequestGroupMan
  74. (const std::vector<SharedHandle<RequestGroup> >& requestGroups,
  75. unsigned int maxSimultaneousDownloads,
  76. const Option* option):
  77. reservedGroups_(requestGroups.begin(), requestGroups.end()),
  78. logger_(LogFactory::getInstance()),
  79. maxSimultaneousDownloads_(maxSimultaneousDownloads),
  80. option_(option),
  81. serverStatMan_(new ServerStatMan()),
  82. maxOverallDownloadSpeedLimit_
  83. (option->getAsInt(PREF_MAX_OVERALL_DOWNLOAD_LIMIT)),
  84. maxOverallUploadSpeedLimit_(option->getAsInt(PREF_MAX_OVERALL_UPLOAD_LIMIT)),
  85. xmlRpc_(option->getAsBool(PREF_ENABLE_XML_RPC)),
  86. queueCheck_(true)
  87. {}
  88. bool RequestGroupMan::downloadFinished()
  89. {
  90. #ifdef ENABLE_XML_RPC
  91. if(xmlRpc_) {
  92. return false;
  93. }
  94. #endif // ENABLE_XML_RPC
  95. return requestGroups_.empty() && reservedGroups_.empty();
  96. }
  97. void RequestGroupMan::addRequestGroup
  98. (const SharedHandle<RequestGroup>& group)
  99. {
  100. requestGroups_.push_back(group);
  101. }
  102. void RequestGroupMan::addReservedGroup
  103. (const std::vector<SharedHandle<RequestGroup> >& groups)
  104. {
  105. if(reservedGroups_.empty()) {
  106. requestQueueCheck();
  107. }
  108. reservedGroups_.insert(reservedGroups_.end(), groups.begin(), groups.end());
  109. }
  110. void RequestGroupMan::addReservedGroup
  111. (const SharedHandle<RequestGroup>& group)
  112. {
  113. if(reservedGroups_.empty()) {
  114. requestQueueCheck();
  115. }
  116. reservedGroups_.push_back(group);
  117. }
  118. void RequestGroupMan::insertReservedGroup
  119. (size_t pos, const std::vector<SharedHandle<RequestGroup> >& groups)
  120. {
  121. if(reservedGroups_.empty()) {
  122. requestQueueCheck();
  123. }
  124. reservedGroups_.insert
  125. (reservedGroups_.begin()+std::min(reservedGroups_.size(), pos),
  126. groups.begin(), groups.end());
  127. }
  128. void RequestGroupMan::insertReservedGroup
  129. (size_t pos, const SharedHandle<RequestGroup>& group)
  130. {
  131. if(reservedGroups_.empty()) {
  132. requestQueueCheck();
  133. }
  134. reservedGroups_.insert
  135. (reservedGroups_.begin()+std::min(reservedGroups_.size(), pos), group);
  136. }
  137. size_t RequestGroupMan::countRequestGroup() const
  138. {
  139. return requestGroups_.size();
  140. }
  141. SharedHandle<RequestGroup> RequestGroupMan::getRequestGroup(size_t index) const
  142. {
  143. if(index < requestGroups_.size()) {
  144. return requestGroups_[index];
  145. } else {
  146. return SharedHandle<RequestGroup>();
  147. }
  148. }
  149. template<typename Iterator>
  150. static Iterator findByGID(Iterator first, Iterator last, gid_t gid)
  151. {
  152. for(; first != last; ++first) {
  153. if((*first)->getGID() == gid) {
  154. return first;
  155. }
  156. }
  157. return first;
  158. }
  159. SharedHandle<RequestGroup>
  160. RequestGroupMan::findRequestGroup(gid_t gid) const
  161. {
  162. std::deque<SharedHandle<RequestGroup> >::const_iterator i =
  163. findByGID(requestGroups_.begin(), requestGroups_.end(), gid);
  164. if(i == requestGroups_.end()) {
  165. return SharedHandle<RequestGroup>();
  166. } else {
  167. return *i;
  168. }
  169. }
  170. SharedHandle<RequestGroup>
  171. RequestGroupMan::findReservedGroup(gid_t gid) const
  172. {
  173. std::deque<SharedHandle<RequestGroup> >::const_iterator i =
  174. findByGID(reservedGroups_.begin(), reservedGroups_.end(), gid);
  175. if(i == reservedGroups_.end()) {
  176. return SharedHandle<RequestGroup>();
  177. } else {
  178. return *i;
  179. }
  180. }
  181. size_t RequestGroupMan::changeReservedGroupPosition
  182. (gid_t gid, int pos, HOW how)
  183. {
  184. std::deque<SharedHandle<RequestGroup> >::iterator i =
  185. findByGID(reservedGroups_.begin(), reservedGroups_.end(), gid);
  186. if(i == reservedGroups_.end()) {
  187. throw DL_ABORT_EX
  188. (StringFormat("GID#%s not found in the waiting queue.",
  189. util::itos(gid).c_str()).str());
  190. }
  191. SharedHandle<RequestGroup> rg = *i;
  192. const size_t maxPos = reservedGroups_.size()-1;
  193. if(how == POS_SET) {
  194. if(pos < 0) {
  195. pos = 0;
  196. } else if(pos > 0) {
  197. pos = std::min(maxPos, (size_t)pos);
  198. }
  199. } else if(how == POS_CUR) {
  200. size_t abspos = std::distance(reservedGroups_.begin(), i);
  201. if(pos < 0) {
  202. int dist = -std::distance(reservedGroups_.begin(), i);
  203. pos = abspos+std::max(pos, dist);
  204. } else if(pos > 0) {
  205. int dist = std::distance(i, reservedGroups_.end())-1;
  206. pos = abspos+std::min(pos, dist);
  207. } else {
  208. pos = abspos;
  209. }
  210. } else if(how == POS_END) {
  211. if(pos >= 0) {
  212. pos = maxPos;
  213. } else {
  214. pos = maxPos-std::min(maxPos, (size_t)-pos);
  215. }
  216. }
  217. if(std::distance(reservedGroups_.begin(), i) < pos) {
  218. std::rotate(i, i+1, reservedGroups_.begin()+pos+1);
  219. } else {
  220. std::rotate(reservedGroups_.begin()+pos, i, i+1);
  221. }
  222. return pos;
  223. }
  224. bool RequestGroupMan::removeReservedGroup(gid_t gid)
  225. {
  226. std::deque<SharedHandle<RequestGroup> >::iterator i =
  227. findByGID(reservedGroups_.begin(), reservedGroups_.end(), gid);
  228. if(i == reservedGroups_.end()) {
  229. return false;
  230. } else {
  231. reservedGroups_.erase(i);
  232. return true;
  233. }
  234. }
  235. static void executeHook(const std::string& command, gid_t gid)
  236. {
  237. LogFactory::getInstance()->info("Executing user command: %s %s",
  238. command.c_str(), util::itos(gid).c_str());
  239. #ifndef __MINGW32__
  240. pid_t cpid = fork();
  241. if(cpid == -1) {
  242. LogFactory::getInstance()->error("fork() failed."
  243. " Cannot execute user command.");
  244. } else if(cpid == 0) {
  245. execl(command.c_str(), command.c_str(), util::itos(gid).c_str(),
  246. reinterpret_cast<char*>(0));
  247. perror(("Could not execute user command: "+command).c_str());
  248. exit(EXIT_FAILURE);
  249. }
  250. #else
  251. PROCESS_INFORMATION pi;
  252. STARTUPINFO si;
  253. memset(&si, 0, sizeof (si));
  254. si.cb = sizeof(STARTUPINFO);
  255. memset(&pi, 0, sizeof (pi));
  256. std::string cmdline = command;
  257. strappend(cmdline, " ", util::itos(gid));
  258. DWORD rc = CreateProcess(
  259. NULL,
  260. (LPSTR)cmdline.c_str(),
  261. NULL,
  262. NULL,
  263. true,
  264. NULL,
  265. NULL,
  266. 0,
  267. &si,
  268. &pi);
  269. if(!rc)
  270. LogFactory::getInstance()->error("CreateProcess() failed."
  271. " Cannot execute user command.");
  272. #endif
  273. }
  274. static void executeHookByOptName
  275. (const SharedHandle<RequestGroup>& group, const Option* option,
  276. const std::string& opt)
  277. {
  278. if(!option->blank(opt)) {
  279. executeHook(option->get(opt), group->getGID());
  280. }
  281. }
  282. static void executeStopHook
  283. (const SharedHandle<DownloadResult>& result, const Option* option)
  284. {
  285. if(result->result == downloadresultcode::FINISHED &&
  286. !option->blank(PREF_ON_DOWNLOAD_COMPLETE)) {
  287. executeHook(option->get(PREF_ON_DOWNLOAD_COMPLETE), result->gid);
  288. } else if(result->result != downloadresultcode::IN_PROGRESS &&
  289. !option->blank(PREF_ON_DOWNLOAD_ERROR)) {
  290. executeHook(option->get(PREF_ON_DOWNLOAD_ERROR), result->gid);
  291. } else if(!option->blank(PREF_ON_DOWNLOAD_STOP)) {
  292. executeHook(option->get(PREF_ON_DOWNLOAD_STOP), result->gid);
  293. }
  294. }
  295. class ProcessStoppedRequestGroup {
  296. private:
  297. DownloadEngine* e_;
  298. std::deque<SharedHandle<DownloadResult> >& downloadResults_;
  299. std::deque<SharedHandle<RequestGroup> >& reservedGroups_;
  300. Logger* logger_;
  301. void saveSignature(const SharedHandle<RequestGroup>& group)
  302. {
  303. SharedHandle<Signature> sig =
  304. group->getDownloadContext()->getSignature();
  305. if(!sig.isNull() && !sig->getBody().empty()) {
  306. // filename of signature file is the path to download file followed by
  307. // ".sig".
  308. std::string signatureFile = group->getFirstFilePath()+".sig";
  309. if(sig->save(signatureFile)) {
  310. logger_->notice(MSG_SIGNATURE_SAVED, signatureFile.c_str());
  311. } else {
  312. logger_->notice(MSG_SIGNATURE_NOT_SAVED, signatureFile.c_str());
  313. }
  314. }
  315. }
  316. public:
  317. ProcessStoppedRequestGroup
  318. (DownloadEngine* e,
  319. std::deque<SharedHandle<DownloadResult> >& downloadResults,
  320. std::deque<SharedHandle<RequestGroup> >& reservedGroups):
  321. e_(e),
  322. downloadResults_(downloadResults),
  323. reservedGroups_(reservedGroups),
  324. logger_(LogFactory::getInstance()) {}
  325. void operator()(const SharedHandle<RequestGroup>& group)
  326. {
  327. if(group->getNumCommand() == 0) {
  328. const SharedHandle<DownloadContext>& dctx = group->getDownloadContext();
  329. // DownloadContext::resetDownloadStopTime() is only called when
  330. // download completed. If
  331. // DownloadContext::getDownloadStopTime().isZero() is true, then
  332. // there is a possibility that the download is error or
  333. // in-progress and resetDownloadStopTime() is not called. So
  334. // call it here.
  335. if(dctx->getDownloadStopTime().isZero()) {
  336. dctx->resetDownloadStopTime();
  337. }
  338. try {
  339. group->closeFile();
  340. if(group->downloadFinished() &&
  341. !group->getDownloadContext()->isChecksumVerificationNeeded()) {
  342. group->setPauseRequested(false);
  343. group->applyLastModifiedTimeToLocalFiles();
  344. group->reportDownloadFinished();
  345. if(group->allDownloadFinished()) {
  346. group->removeControlFile();
  347. saveSignature(group);
  348. } else {
  349. group->saveControlFile();
  350. }
  351. std::vector<SharedHandle<RequestGroup> > nextGroups;
  352. group->postDownloadProcessing(nextGroups);
  353. if(!nextGroups.empty()) {
  354. if(logger_->debug()) {
  355. logger_->debug
  356. ("Adding %lu RequestGroups as a result of PostDownloadHandler.",
  357. static_cast<unsigned long>(nextGroups.size()));
  358. }
  359. e_->getRequestGroupMan()->insertReservedGroup(0, nextGroups);
  360. }
  361. } else {
  362. group->saveControlFile();
  363. }
  364. } catch(RecoverableException& ex) {
  365. logger_->error(EX_EXCEPTION_CAUGHT, ex);
  366. }
  367. if(group->isPauseRequested()) {
  368. reservedGroups_.push_front(group);
  369. } else {
  370. downloadResults_.push_back(group->createDownloadResult());
  371. }
  372. group->releaseRuntimeResource(e_);
  373. if(group->isPauseRequested()) {
  374. group->setForceHaltRequested(false);
  375. executeHookByOptName(group, e_->getOption(), PREF_ON_DOWNLOAD_PAUSE);
  376. // TODO Should we have to prepend spend uris to remaining uris
  377. // in case PREF_REUSE_URI is disabed?
  378. } else {
  379. executeStopHook(downloadResults_.back(), e_->getOption());
  380. }
  381. }
  382. }
  383. };
  384. class CollectServerStat {
  385. private:
  386. RequestGroupMan* requestGroupMan_;
  387. public:
  388. CollectServerStat(RequestGroupMan* requestGroupMan):
  389. requestGroupMan_(requestGroupMan) {}
  390. void operator()(const SharedHandle<RequestGroup>& group)
  391. {
  392. if(group->getNumCommand() == 0) {
  393. // Collect statistics during download in PeerStats and update/register
  394. // ServerStatMan
  395. if(!group->getSegmentMan().isNull()) {
  396. bool singleConnection =
  397. group->getSegmentMan()->getPeerStats().size() == 1;
  398. const std::vector<SharedHandle<PeerStat> >& peerStats =
  399. group->getSegmentMan()->getFastestPeerStats();
  400. for(std::vector<SharedHandle<PeerStat> >::const_iterator i =
  401. peerStats.begin(), eoi = peerStats.end(); i != eoi; ++i) {
  402. if((*i)->getHostname().empty() || (*i)->getProtocol().empty()) {
  403. continue;
  404. }
  405. int speed = (*i)->getAvgDownloadSpeed();
  406. if (speed == 0) continue;
  407. SharedHandle<ServerStat> ss =
  408. requestGroupMan_->getOrCreateServerStat((*i)->getHostname(),
  409. (*i)->getProtocol());
  410. ss->increaseCounter();
  411. ss->updateDownloadSpeed(speed);
  412. if(singleConnection) {
  413. ss->updateSingleConnectionAvgSpeed(speed);
  414. }
  415. else {
  416. ss->updateMultiConnectionAvgSpeed(speed);
  417. }
  418. }
  419. }
  420. }
  421. }
  422. };
  423. class FindStoppedRequestGroup {
  424. public:
  425. bool operator()(const SharedHandle<RequestGroup>& group) {
  426. return group->getNumCommand() == 0;
  427. }
  428. };
  429. void RequestGroupMan::updateServerStat()
  430. {
  431. std::for_each(requestGroups_.begin(), requestGroups_.end(),
  432. CollectServerStat(this));
  433. }
  434. void RequestGroupMan::removeStoppedGroup(DownloadEngine* e)
  435. {
  436. size_t numPrev = requestGroups_.size();
  437. updateServerStat();
  438. std::for_each(requestGroups_.begin(), requestGroups_.end(),
  439. ProcessStoppedRequestGroup
  440. (e, downloadResults_, reservedGroups_));
  441. std::deque<SharedHandle<RequestGroup> >::iterator i =
  442. std::remove_if(requestGroups_.begin(),
  443. requestGroups_.end(),
  444. FindStoppedRequestGroup());
  445. if(i != requestGroups_.end()) {
  446. requestGroups_.erase(i, requestGroups_.end());
  447. }
  448. size_t numRemoved = numPrev-requestGroups_.size();
  449. if(numRemoved > 0) {
  450. if(logger_->debug()) {
  451. logger_->debug("%lu RequestGroup(s) deleted.",
  452. static_cast<unsigned long>(numRemoved));
  453. }
  454. }
  455. }
  456. void RequestGroupMan::configureRequestGroup
  457. (const SharedHandle<RequestGroup>& requestGroup) const
  458. {
  459. const std::string& uriSelectorValue = option_->get(PREF_URI_SELECTOR);
  460. if(uriSelectorValue == V_FEEDBACK) {
  461. requestGroup->setURISelector
  462. (SharedHandle<URISelector>(new FeedbackURISelector(serverStatMan_)));
  463. } else if(uriSelectorValue == V_INORDER) {
  464. requestGroup->setURISelector
  465. (SharedHandle<URISelector>(new InOrderURISelector()));
  466. } else if(uriSelectorValue == V_ADAPTIVE) {
  467. requestGroup->setURISelector
  468. (SharedHandle<URISelector>(new AdaptiveURISelector(serverStatMan_,
  469. requestGroup.get())));
  470. }
  471. }
  472. static void createInitialCommand(const SharedHandle<RequestGroup>& requestGroup,
  473. std::vector<Command*>& commands,
  474. DownloadEngine* e)
  475. {
  476. requestGroup->createInitialCommand(commands, e);
  477. }
  478. void RequestGroupMan::fillRequestGroupFromReserver(DownloadEngine* e)
  479. {
  480. removeStoppedGroup(e);
  481. if(maxSimultaneousDownloads_ <= requestGroups_.size()) {
  482. return;
  483. }
  484. std::vector<SharedHandle<RequestGroup> > temp;
  485. unsigned int count = 0;
  486. size_t num = maxSimultaneousDownloads_-requestGroups_.size();
  487. while(count < num && !reservedGroups_.empty()) {
  488. SharedHandle<RequestGroup> groupToAdd = reservedGroups_.front();
  489. reservedGroups_.pop_front();
  490. std::vector<Command*> commands;
  491. try {
  492. if(groupToAdd->isPauseRequested()||!groupToAdd->isDependencyResolved()) {
  493. temp.push_back(groupToAdd);
  494. continue;
  495. }
  496. // Drop pieceStorage here because paused download holds its
  497. // reference.
  498. groupToAdd->dropPieceStorage();
  499. configureRequestGroup(groupToAdd);
  500. createInitialCommand(groupToAdd, commands, e);
  501. groupToAdd->setRequestGroupMan(this);
  502. if(commands.empty()) {
  503. requestQueueCheck();
  504. }
  505. requestGroups_.push_back(groupToAdd);
  506. ++count;
  507. e->addCommand(commands);
  508. commands.clear();
  509. executeHookByOptName(groupToAdd, e->getOption(), PREF_ON_DOWNLOAD_START);
  510. } catch(RecoverableException& ex) {
  511. logger_->error(EX_EXCEPTION_CAUGHT, ex);
  512. if(logger_->debug()) {
  513. logger_->debug("Deleting temporal commands.");
  514. }
  515. std::for_each(commands.begin(), commands.end(), Deleter());
  516. commands.clear();
  517. if(logger_->debug()) {
  518. logger_->debug("Commands deleted");
  519. }
  520. groupToAdd->releaseRuntimeResource(e);
  521. downloadResults_.push_back(groupToAdd->createDownloadResult());
  522. }
  523. }
  524. if(!temp.empty()) {
  525. reservedGroups_.insert(reservedGroups_.begin(), temp.begin(), temp.end());
  526. }
  527. if(count > 0) {
  528. e->setNoWait(true);
  529. if(logger_->debug()) {
  530. logger_->debug("%d RequestGroup(s) added.", count);
  531. }
  532. }
  533. }
  534. void RequestGroupMan::save()
  535. {
  536. for(std::deque<SharedHandle<RequestGroup> >::const_iterator itr =
  537. requestGroups_.begin(), eoi = requestGroups_.end(); itr != eoi; ++itr) {
  538. if((*itr)->allDownloadFinished() &&
  539. !(*itr)->getDownloadContext()->isChecksumVerificationNeeded()) {
  540. (*itr)->removeControlFile();
  541. } else {
  542. try {
  543. (*itr)->saveControlFile();
  544. } catch(RecoverableException& e) {
  545. logger_->error(EX_EXCEPTION_CAUGHT, e);
  546. }
  547. }
  548. }
  549. }
  550. void RequestGroupMan::closeFile()
  551. {
  552. for(std::deque<SharedHandle<RequestGroup> >::const_iterator itr =
  553. requestGroups_.begin(), eoi = requestGroups_.end(); itr != eoi; ++itr) {
  554. (*itr)->closeFile();
  555. }
  556. }
  557. RequestGroupMan::DownloadStat RequestGroupMan::getDownloadStat() const
  558. {
  559. size_t finished = 0;
  560. size_t error = 0;
  561. size_t inprogress = 0;
  562. downloadresultcode::RESULT lastError = downloadresultcode::FINISHED;
  563. for(std::deque<SharedHandle<DownloadResult> >::const_iterator itr =
  564. downloadResults_.begin(), eoi = downloadResults_.end();
  565. itr != eoi; ++itr) {
  566. if((*itr)->result == downloadresultcode::FINISHED) {
  567. ++finished;
  568. } else {
  569. ++error;
  570. lastError = (*itr)->result;
  571. }
  572. }
  573. for(std::deque<SharedHandle<RequestGroup> >::const_iterator itr =
  574. requestGroups_.begin(), eoi = requestGroups_.end(); itr != eoi; ++itr) {
  575. DownloadResultHandle result = (*itr)->createDownloadResult();
  576. if(result->result == downloadresultcode::FINISHED) {
  577. ++finished;
  578. } else {
  579. ++inprogress;
  580. }
  581. }
  582. return DownloadStat(finished, error, inprogress, reservedGroups_.size(),
  583. lastError);
  584. }
  585. void RequestGroupMan::showDownloadResults(std::ostream& o) const
  586. {
  587. static const std::string MARK_OK("OK");
  588. static const std::string MARK_ERR("ERR");
  589. static const std::string MARK_INPR("INPR");
  590. // Download Results:
  591. // idx|stat|path/length
  592. // ===+====+=======================================================================
  593. o << "\n"
  594. <<_("Download Results:") << "\n"
  595. << "gid|stat|avg speed |path/URI" << "\n"
  596. << "===+====+===========+";
  597. #ifdef __MINGW32__
  598. int pathRowSize = 58;
  599. #else // !__MINGW32__
  600. int pathRowSize = 59;
  601. #endif // !__MINGW32__
  602. o << std::setfill('=') << std::setw(pathRowSize) << '=' << "\n";
  603. int ok = 0;
  604. int err = 0;
  605. int inpr = 0;
  606. for(std::deque<SharedHandle<DownloadResult> >::const_iterator itr =
  607. downloadResults_.begin(), eoi = downloadResults_.end();
  608. itr != eoi; ++itr) {
  609. std::string status;
  610. if((*itr)->result == downloadresultcode::FINISHED) {
  611. status = MARK_OK;
  612. ++ok;
  613. } else if((*itr)->result == downloadresultcode::IN_PROGRESS) {
  614. status = MARK_INPR;
  615. ++inpr;
  616. } else {
  617. status = MARK_ERR;
  618. ++err;
  619. }
  620. o << formatDownloadResult(status, *itr) << "\n";
  621. }
  622. for(std::deque<SharedHandle<RequestGroup> >::const_iterator itr =
  623. requestGroups_.begin(), eoi = requestGroups_.end(); itr != eoi; ++itr) {
  624. DownloadResultHandle result = (*itr)->createDownloadResult();
  625. std::string status;
  626. if(result->result == downloadresultcode::FINISHED) {
  627. status = MARK_OK;
  628. ++ok;
  629. } else {
  630. // Since this RequestGroup is not processed by ProcessStoppedRequestGroup,
  631. // its download stop time is not reseted.
  632. // Reset download stop time and assign sessionTime here.
  633. (*itr)->getDownloadContext()->resetDownloadStopTime();
  634. result->sessionTime =
  635. (*itr)->getDownloadContext()->calculateSessionTime();
  636. status = MARK_INPR;
  637. ++inpr;
  638. }
  639. o << formatDownloadResult(status, result) << "\n";
  640. }
  641. for(std::deque<SharedHandle<RequestGroup> >::const_iterator itr =
  642. reservedGroups_.begin(), eoi = reservedGroups_.end();
  643. itr != eoi; ++itr) {
  644. if(!(*itr)->isPauseRequested()) {
  645. continue;
  646. }
  647. SharedHandle<DownloadResult> result = (*itr)->createDownloadResult();
  648. ++inpr;
  649. o << formatDownloadResult(MARK_INPR, result) << "\n";
  650. }
  651. if(ok > 0 || err > 0 || inpr > 0) {
  652. o << "\n"
  653. << _("Status Legend:") << "\n";
  654. if(ok > 0) {
  655. o << " (OK):download completed.";
  656. }
  657. if(err > 0) {
  658. o << "(ERR):error occurred.";
  659. }
  660. if(inpr > 0) {
  661. o << "(INPR):download in-progress.";
  662. }
  663. o << "\n";
  664. }
  665. }
  666. std::string RequestGroupMan::formatDownloadResult(const std::string& status, const DownloadResultHandle& downloadResult) const
  667. {
  668. std::stringstream o;
  669. o << std::setw(3) << downloadResult->gid << "|"
  670. << std::setw(4) << status << "|"
  671. << std::setw(11);
  672. if(downloadResult->sessionTime > 0) {
  673. o << util::abbrevSize
  674. (downloadResult->sessionDownloadLength*1000/downloadResult->sessionTime)+
  675. "B/s";
  676. } else {
  677. o << "n/a";
  678. }
  679. o << "|";
  680. const std::vector<SharedHandle<FileEntry> >& fileEntries =
  681. downloadResult->fileEntries;
  682. writeFilePath(fileEntries.begin(), fileEntries.end(), o,
  683. downloadResult->inMemoryDownload);
  684. return o.str();
  685. }
  686. template<typename StringInputIterator, typename FileEntryInputIterator>
  687. static bool sameFilePathExists(StringInputIterator sfirst,
  688. StringInputIterator slast,
  689. FileEntryInputIterator ffirst,
  690. FileEntryInputIterator flast)
  691. {
  692. for(; ffirst != flast; ++ffirst) {
  693. if(std::binary_search(sfirst, slast, (*ffirst)->getPath())) {
  694. return true;
  695. }
  696. }
  697. return false;
  698. }
  699. bool RequestGroupMan::isSameFileBeingDownloaded(RequestGroup* requestGroup) const
  700. {
  701. // TODO it may be good to use dedicated method rather than use
  702. // isPreLocalFileCheckEnabled
  703. if(!requestGroup->isPreLocalFileCheckEnabled()) {
  704. return false;
  705. }
  706. std::vector<std::string> files;
  707. for(std::deque<SharedHandle<RequestGroup> >::const_iterator itr =
  708. requestGroups_.begin(), eoi = requestGroups_.end(); itr != eoi; ++itr) {
  709. if((*itr).get() != requestGroup) {
  710. const std::vector<SharedHandle<FileEntry> >& entries =
  711. (*itr)->getDownloadContext()->getFileEntries();
  712. std::transform(entries.begin(), entries.end(),
  713. std::back_inserter(files),
  714. mem_fun_sh(&FileEntry::getPath));
  715. }
  716. }
  717. std::sort(files.begin(), files.end());
  718. const std::vector<SharedHandle<FileEntry> >& entries =
  719. requestGroup->getDownloadContext()->getFileEntries();
  720. return sameFilePathExists(files.begin(), files.end(),
  721. entries.begin(), entries.end());
  722. }
  723. void RequestGroupMan::halt()
  724. {
  725. for(std::deque<SharedHandle<RequestGroup> >::const_iterator i =
  726. requestGroups_.begin(), eoi = requestGroups_.end(); i != eoi; ++i) {
  727. (*i)->setHaltRequested(true);
  728. }
  729. }
  730. void RequestGroupMan::forceHalt()
  731. {
  732. for(std::deque<SharedHandle<RequestGroup> >::const_iterator i =
  733. requestGroups_.begin(), eoi = requestGroups_.end(); i != eoi; ++i) {
  734. (*i)->setForceHaltRequested(true);
  735. }
  736. }
  737. TransferStat RequestGroupMan::calculateStat()
  738. {
  739. TransferStat s;
  740. for(std::deque<SharedHandle<RequestGroup> >::const_iterator i =
  741. requestGroups_.begin(), eoi = requestGroups_.end(); i != eoi; ++i) {
  742. s += (*i)->calculateStat();
  743. }
  744. return s;
  745. }
  746. SharedHandle<DownloadResult>
  747. RequestGroupMan::findDownloadResult(gid_t gid) const
  748. {
  749. for(std::deque<SharedHandle<DownloadResult> >::const_iterator i =
  750. downloadResults_.begin(), eoi = downloadResults_.end(); i != eoi; ++i) {
  751. if((*i)->gid == gid) {
  752. return *i;
  753. }
  754. }
  755. return SharedHandle<DownloadResult>();
  756. }
  757. void RequestGroupMan::purgeDownloadResult()
  758. {
  759. downloadResults_.clear();
  760. }
  761. SharedHandle<ServerStat>
  762. RequestGroupMan::findServerStat(const std::string& hostname,
  763. const std::string& protocol) const
  764. {
  765. return serverStatMan_->find(hostname, protocol);
  766. }
  767. SharedHandle<ServerStat>
  768. RequestGroupMan::getOrCreateServerStat(const std::string& hostname,
  769. const std::string& protocol)
  770. {
  771. SharedHandle<ServerStat> ss = findServerStat(hostname, protocol);
  772. if(ss.isNull()) {
  773. ss.reset(new ServerStat(hostname, protocol));
  774. addServerStat(ss);
  775. }
  776. return ss;
  777. }
  778. bool RequestGroupMan::addServerStat(const SharedHandle<ServerStat>& serverStat)
  779. {
  780. return serverStatMan_->add(serverStat);
  781. }
  782. bool RequestGroupMan::loadServerStat(const std::string& filename)
  783. {
  784. std::ifstream in(filename.c_str(), std::ios::binary);
  785. if(!in) {
  786. logger_->error(MSG_OPENING_READABLE_SERVER_STAT_FILE_FAILED, filename.c_str());
  787. return false;
  788. }
  789. if(serverStatMan_->load(in)) {
  790. logger_->notice(MSG_SERVER_STAT_LOADED, filename.c_str());
  791. return true;
  792. } else {
  793. logger_->error(MSG_READING_SERVER_STAT_FILE_FAILED, filename.c_str());
  794. return false;
  795. }
  796. }
  797. bool RequestGroupMan::saveServerStat(const std::string& filename) const
  798. {
  799. std::string tempfile = filename;
  800. tempfile += "__temp";
  801. {
  802. std::ofstream out(tempfile.c_str(), std::ios::binary);
  803. if(!out) {
  804. logger_->error(MSG_OPENING_WRITABLE_SERVER_STAT_FILE_FAILED,
  805. filename.c_str());
  806. return false;
  807. }
  808. if(!serverStatMan_->save(out)) {
  809. logger_->error(MSG_WRITING_SERVER_STAT_FILE_FAILED, filename.c_str());
  810. return false;
  811. }
  812. }
  813. if(File(tempfile).renameTo(filename)) {
  814. logger_->notice(MSG_SERVER_STAT_SAVED, filename.c_str());
  815. return true;
  816. } else {
  817. logger_->error(MSG_WRITING_SERVER_STAT_FILE_FAILED, filename.c_str());
  818. return false;
  819. }
  820. }
  821. void RequestGroupMan::removeStaleServerStat(time_t timeout)
  822. {
  823. serverStatMan_->removeStaleServerStat(timeout);
  824. }
  825. bool RequestGroupMan::doesOverallDownloadSpeedExceed()
  826. {
  827. return maxOverallDownloadSpeedLimit_ > 0 &&
  828. maxOverallDownloadSpeedLimit_ < calculateStat().getDownloadSpeed();
  829. }
  830. bool RequestGroupMan::doesOverallUploadSpeedExceed()
  831. {
  832. return maxOverallUploadSpeedLimit_ > 0 &&
  833. maxOverallUploadSpeedLimit_ < calculateStat().getUploadSpeed();
  834. }
  835. void RequestGroupMan::getUsedHosts(std::vector<std::string>& usedHosts)
  836. {
  837. Request r;
  838. for(std::deque<SharedHandle<RequestGroup> >::const_iterator i =
  839. requestGroups_.begin(), eoi = requestGroups_.end(); i != eoi; ++i) {
  840. const std::deque<SharedHandle<Request> >& inFlightReqs =
  841. (*i)->getDownloadContext()->getFirstFileEntry()->getInFlightRequests();
  842. for(std::deque<SharedHandle<Request> >::const_iterator j =
  843. inFlightReqs.begin(), eoj = inFlightReqs.end(); j != eoj; ++j) {
  844. if(r.setUri((*j)->getUri())) {
  845. usedHosts.push_back(r.getHost());
  846. }
  847. }
  848. }
  849. }
  850. } // namespace aria2