RequestGroupMan.cc 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845
  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. namespace aria2 {
  69. RequestGroupMan::RequestGroupMan
  70. (const std::vector<SharedHandle<RequestGroup> >& requestGroups,
  71. unsigned int maxSimultaneousDownloads,
  72. const Option* option):
  73. _reservedGroups(requestGroups.begin(), requestGroups.end()),
  74. _logger(LogFactory::getInstance()),
  75. _maxSimultaneousDownloads(maxSimultaneousDownloads),
  76. _gidCounter(0),
  77. _option(option),
  78. _serverStatMan(new ServerStatMan()),
  79. _maxOverallDownloadSpeedLimit
  80. (option->getAsInt(PREF_MAX_OVERALL_DOWNLOAD_LIMIT)),
  81. _maxOverallUploadSpeedLimit(option->getAsInt(PREF_MAX_OVERALL_UPLOAD_LIMIT)),
  82. _xmlRpc(option->getAsBool(PREF_ENABLE_XML_RPC)),
  83. _queueCheck(true)
  84. {}
  85. bool RequestGroupMan::downloadFinished()
  86. {
  87. #ifdef ENABLE_XML_RPC
  88. if(_xmlRpc) {
  89. return false;
  90. }
  91. #endif // ENABLE_XML_RPC
  92. return _requestGroups.empty() && _reservedGroups.empty();
  93. }
  94. void RequestGroupMan::addRequestGroup
  95. (const SharedHandle<RequestGroup>& group)
  96. {
  97. _requestGroups.push_back(group);
  98. }
  99. void RequestGroupMan::addReservedGroup
  100. (const std::vector<SharedHandle<RequestGroup> >& groups)
  101. {
  102. _reservedGroups.insert(_reservedGroups.end(), groups.begin(), groups.end());
  103. }
  104. void RequestGroupMan::addReservedGroup
  105. (const SharedHandle<RequestGroup>& group)
  106. {
  107. _reservedGroups.push_back(group);
  108. }
  109. void RequestGroupMan::insertReservedGroup
  110. (size_t pos, const std::vector<SharedHandle<RequestGroup> >& groups)
  111. {
  112. _reservedGroups.insert
  113. (_reservedGroups.begin()+std::min(_reservedGroups.size(), pos),
  114. groups.begin(), groups.end());
  115. }
  116. void RequestGroupMan::insertReservedGroup
  117. (size_t pos, const SharedHandle<RequestGroup>& group)
  118. {
  119. _reservedGroups.insert
  120. (_reservedGroups.begin()+std::min(_reservedGroups.size(), pos), group);
  121. }
  122. size_t RequestGroupMan::countRequestGroup() const
  123. {
  124. return _requestGroups.size();
  125. }
  126. SharedHandle<RequestGroup> RequestGroupMan::getRequestGroup(size_t index) const
  127. {
  128. if(index < _requestGroups.size()) {
  129. return _requestGroups[index];
  130. } else {
  131. return SharedHandle<RequestGroup>();
  132. }
  133. }
  134. template<typename Iterator>
  135. static Iterator findByGID(Iterator first, Iterator last, int32_t gid)
  136. {
  137. for(; first != last; ++first) {
  138. if((*first)->getGID() == gid) {
  139. return first;
  140. }
  141. }
  142. return first;
  143. }
  144. SharedHandle<RequestGroup>
  145. RequestGroupMan::findRequestGroup(int32_t gid) const
  146. {
  147. std::deque<SharedHandle<RequestGroup> >::const_iterator i =
  148. findByGID(_requestGroups.begin(), _requestGroups.end(), gid);
  149. if(i == _requestGroups.end()) {
  150. return SharedHandle<RequestGroup>();
  151. } else {
  152. return *i;
  153. }
  154. }
  155. SharedHandle<RequestGroup>
  156. RequestGroupMan::findReservedGroup(int32_t gid) const
  157. {
  158. std::deque<SharedHandle<RequestGroup> >::const_iterator i =
  159. findByGID(_reservedGroups.begin(), _reservedGroups.end(), gid);
  160. if(i == _reservedGroups.end()) {
  161. return SharedHandle<RequestGroup>();
  162. } else {
  163. return *i;
  164. }
  165. }
  166. size_t RequestGroupMan::changeReservedGroupPosition
  167. (int32_t gid, int pos, HOW how)
  168. {
  169. std::deque<SharedHandle<RequestGroup> >::iterator i =
  170. findByGID(_reservedGroups.begin(), _reservedGroups.end(), gid);
  171. if(i == _reservedGroups.end()) {
  172. throw DL_ABORT_EX
  173. (StringFormat("GID#%d not found in the waiting queue.", gid).str());
  174. }
  175. SharedHandle<RequestGroup> rg = *i;
  176. const size_t maxPos = _reservedGroups.size()-1;
  177. if(how == POS_SET) {
  178. if(pos < 0) {
  179. pos = 0;
  180. } else if(pos > 0) {
  181. pos = std::min(maxPos, (size_t)pos);
  182. }
  183. } else if(how == POS_CUR) {
  184. size_t abspos = std::distance(_reservedGroups.begin(), i);
  185. if(pos < 0) {
  186. int dist = -std::distance(_reservedGroups.begin(), i);
  187. pos = abspos+std::max(pos, dist);
  188. } else if(pos > 0) {
  189. int dist = std::distance(i, _reservedGroups.end())-1;
  190. pos = abspos+std::min(pos, dist);
  191. } else {
  192. pos = abspos;
  193. }
  194. } else if(how == POS_END) {
  195. if(pos >= 0) {
  196. pos = maxPos;
  197. } else {
  198. pos = maxPos-std::min(maxPos, (size_t)-pos);
  199. }
  200. }
  201. if(std::distance(_reservedGroups.begin(), i) < pos) {
  202. std::rotate(i, i+1, _reservedGroups.begin()+pos+1);
  203. } else {
  204. std::rotate(_reservedGroups.begin()+pos, i, i+1);
  205. }
  206. return pos;
  207. }
  208. bool RequestGroupMan::removeReservedGroup(int32_t gid)
  209. {
  210. std::deque<SharedHandle<RequestGroup> >::iterator i =
  211. findByGID(_reservedGroups.begin(), _reservedGroups.end(), gid);
  212. if(i == _reservedGroups.end()) {
  213. return false;
  214. } else {
  215. _reservedGroups.erase(i);
  216. return true;
  217. }
  218. }
  219. static void executeHook(const std::string& command, int gid)
  220. {
  221. LogFactory::getInstance()->info("Executing user command: %s %d",
  222. command.c_str(), gid);
  223. #ifndef __MINGW32__
  224. pid_t cpid = fork();
  225. if(cpid == -1) {
  226. LogFactory::getInstance()->error("fork() failed."
  227. " Cannot execute user command.");
  228. } else if(cpid == 0) {
  229. execl(command.c_str(), command.c_str(), util::itos(gid).c_str(),
  230. reinterpret_cast<char*>(0));
  231. perror(("Could not execute user command: "+command).c_str());
  232. exit(EXIT_FAILURE);
  233. }
  234. #else
  235. PROCESS_INFORMATION pi;
  236. STARTUPINFO si;
  237. memset(&si, 0, sizeof (si));
  238. si.cb = sizeof(STARTUPINFO);
  239. memset(&pi, 0, sizeof (pi));
  240. std::string cmdline = command;
  241. strappend(cmdline, " ", util::itos(gid));
  242. DWORD rc = CreateProcess(
  243. NULL,
  244. (LPSTR)cmdline.c_str(),
  245. NULL,
  246. NULL,
  247. true,
  248. NULL,
  249. NULL,
  250. 0,
  251. &si,
  252. &pi);
  253. if(!rc)
  254. LogFactory::getInstance()->error("CreateProcess() failed."
  255. " Cannot execute user command.");
  256. #endif
  257. }
  258. static void executeStartHook
  259. (const SharedHandle<RequestGroup>& group, const Option* option)
  260. {
  261. if(!option->blank(PREF_ON_DOWNLOAD_START)) {
  262. executeHook(option->get(PREF_ON_DOWNLOAD_START), group->getGID());
  263. }
  264. }
  265. static void executeStopHook
  266. (const SharedHandle<DownloadResult>& result, const Option* option)
  267. {
  268. if(result->result == downloadresultcode::FINISHED &&
  269. !option->blank(PREF_ON_DOWNLOAD_COMPLETE)) {
  270. executeHook(option->get(PREF_ON_DOWNLOAD_COMPLETE), result->gid);
  271. } else if(result->result != downloadresultcode::IN_PROGRESS &&
  272. !option->blank(PREF_ON_DOWNLOAD_ERROR)) {
  273. executeHook(option->get(PREF_ON_DOWNLOAD_ERROR), result->gid);
  274. } else if(!option->blank(PREF_ON_DOWNLOAD_STOP)) {
  275. executeHook(option->get(PREF_ON_DOWNLOAD_STOP), result->gid);
  276. }
  277. }
  278. class ProcessStoppedRequestGroup {
  279. private:
  280. DownloadEngine* _e;
  281. std::deque<SharedHandle<RequestGroup> >& _reservedGroups;
  282. std::deque<SharedHandle<DownloadResult> >& _downloadResults;
  283. Logger* _logger;
  284. void saveSignature(const SharedHandle<RequestGroup>& group)
  285. {
  286. SharedHandle<Signature> sig =
  287. group->getDownloadContext()->getSignature();
  288. if(!sig.isNull() && !sig->getBody().empty()) {
  289. // filename of signature file is the path to download file followed by
  290. // ".sig".
  291. std::string signatureFile = group->getFirstFilePath()+".sig";
  292. if(sig->save(signatureFile)) {
  293. _logger->notice(MSG_SIGNATURE_SAVED, signatureFile.c_str());
  294. } else {
  295. _logger->notice(MSG_SIGNATURE_NOT_SAVED, signatureFile.c_str());
  296. }
  297. }
  298. }
  299. public:
  300. ProcessStoppedRequestGroup
  301. (DownloadEngine* e,
  302. std::deque<SharedHandle<RequestGroup> >& reservedGroups,
  303. std::deque<SharedHandle<DownloadResult> >& downloadResults):
  304. _e(e),
  305. _reservedGroups(reservedGroups),
  306. _downloadResults(downloadResults),
  307. _logger(LogFactory::getInstance()) {}
  308. void operator()(const SharedHandle<RequestGroup>& group)
  309. {
  310. if(group->getNumCommand() == 0) {
  311. try {
  312. group->closeFile();
  313. if(group->downloadFinished()) {
  314. group->applyLastModifiedTimeToLocalFiles();
  315. group->reportDownloadFinished();
  316. if(group->allDownloadFinished()) {
  317. group->removeControlFile();
  318. saveSignature(group);
  319. } else {
  320. group->saveControlFile();
  321. }
  322. std::vector<SharedHandle<RequestGroup> > nextGroups;
  323. group->postDownloadProcessing(nextGroups);
  324. if(!nextGroups.empty()) {
  325. if(_logger->debug()) {
  326. _logger->debug
  327. ("Adding %lu RequestGroups as a result of PostDownloadHandler.",
  328. static_cast<unsigned long>(nextGroups.size()));
  329. }
  330. _reservedGroups.insert(_reservedGroups.begin(),
  331. nextGroups.begin(), nextGroups.end());
  332. }
  333. } else {
  334. group->saveControlFile();
  335. }
  336. } catch(RecoverableException& ex) {
  337. _logger->error(EX_EXCEPTION_CAUGHT, ex);
  338. }
  339. group->releaseRuntimeResource(_e);
  340. _downloadResults.push_back(group->createDownloadResult());
  341. executeStopHook(_downloadResults.back(), _e->option);
  342. }
  343. }
  344. };
  345. class CollectServerStat {
  346. private:
  347. RequestGroupMan* _requestGroupMan;
  348. public:
  349. CollectServerStat(RequestGroupMan* requestGroupMan):
  350. _requestGroupMan(requestGroupMan) {}
  351. void operator()(const SharedHandle<RequestGroup>& group)
  352. {
  353. if(group->getNumCommand() == 0) {
  354. // Collect statistics during download in PeerStats and update/register
  355. // ServerStatMan
  356. if(!group->getSegmentMan().isNull()) {
  357. bool singleConnection =
  358. group->getSegmentMan()->getPeerStats().size() == 1;
  359. const std::vector<SharedHandle<PeerStat> >& peerStats =
  360. group->getSegmentMan()->getFastestPeerStats();
  361. for(std::vector<SharedHandle<PeerStat> >::const_iterator i =
  362. peerStats.begin(), eoi = peerStats.end(); i != eoi; ++i) {
  363. if((*i)->getHostname().empty() || (*i)->getProtocol().empty()) {
  364. continue;
  365. }
  366. int speed = (*i)->getAvgDownloadSpeed();
  367. if (speed == 0) continue;
  368. SharedHandle<ServerStat> ss =
  369. _requestGroupMan->getOrCreateServerStat((*i)->getHostname(),
  370. (*i)->getProtocol());
  371. ss->increaseCounter();
  372. ss->updateDownloadSpeed(speed);
  373. if(singleConnection) {
  374. ss->updateSingleConnectionAvgSpeed(speed);
  375. }
  376. else {
  377. ss->updateMultiConnectionAvgSpeed(speed);
  378. }
  379. }
  380. }
  381. }
  382. }
  383. };
  384. class FindStoppedRequestGroup {
  385. public:
  386. bool operator()(const SharedHandle<RequestGroup>& group) {
  387. return group->getNumCommand() == 0;
  388. }
  389. };
  390. void RequestGroupMan::updateServerStat()
  391. {
  392. std::for_each(_requestGroups.begin(), _requestGroups.end(),
  393. CollectServerStat(this));
  394. }
  395. void RequestGroupMan::removeStoppedGroup(DownloadEngine* e)
  396. {
  397. size_t numPrev = _requestGroups.size();
  398. updateServerStat();
  399. std::for_each(_requestGroups.begin(), _requestGroups.end(),
  400. ProcessStoppedRequestGroup(e, _reservedGroups,
  401. _downloadResults));
  402. std::deque<SharedHandle<RequestGroup> >::iterator i =
  403. std::remove_if(_requestGroups.begin(),
  404. _requestGroups.end(),
  405. FindStoppedRequestGroup());
  406. if(i != _requestGroups.end()) {
  407. _requestGroups.erase(i, _requestGroups.end());
  408. }
  409. size_t numRemoved = numPrev-_requestGroups.size();
  410. if(numRemoved > 0) {
  411. if(_logger->debug()) {
  412. _logger->debug("%lu RequestGroup(s) deleted.",
  413. static_cast<unsigned long>(numRemoved));
  414. }
  415. }
  416. }
  417. void RequestGroupMan::configureRequestGroup
  418. (const SharedHandle<RequestGroup>& requestGroup) const
  419. {
  420. const std::string& uriSelectorValue = _option->get(PREF_URI_SELECTOR);
  421. if(uriSelectorValue == V_FEEDBACK) {
  422. requestGroup->setURISelector
  423. (SharedHandle<URISelector>(new FeedbackURISelector(_serverStatMan)));
  424. } else if(uriSelectorValue == V_INORDER) {
  425. requestGroup->setURISelector
  426. (SharedHandle<URISelector>(new InOrderURISelector()));
  427. } else if(uriSelectorValue == V_ADAPTIVE) {
  428. requestGroup->setURISelector
  429. (SharedHandle<URISelector>(new AdaptiveURISelector(_serverStatMan,
  430. requestGroup.get())));
  431. }
  432. }
  433. static void createInitialCommand(const SharedHandle<RequestGroup>& requestGroup,
  434. std::vector<Command*>& commands,
  435. DownloadEngine* e)
  436. {
  437. requestGroup->createInitialCommand(commands, e);
  438. }
  439. void RequestGroupMan::fillRequestGroupFromReserver(DownloadEngine* e)
  440. {
  441. removeStoppedGroup(e);
  442. if(_maxSimultaneousDownloads <= _requestGroups.size()) {
  443. return;
  444. }
  445. std::vector<SharedHandle<RequestGroup> > temp;
  446. unsigned int count = 0;
  447. size_t num = _maxSimultaneousDownloads-_requestGroups.size();
  448. while(count < num && !_reservedGroups.empty()) {
  449. SharedHandle<RequestGroup> groupToAdd = _reservedGroups.front();
  450. _reservedGroups.pop_front();
  451. std::vector<Command*> commands;
  452. try {
  453. if(!groupToAdd->isDependencyResolved()) {
  454. temp.push_back(groupToAdd);
  455. continue;
  456. }
  457. configureRequestGroup(groupToAdd);
  458. createInitialCommand(groupToAdd, commands, e);
  459. groupToAdd->setRequestGroupMan(this);
  460. _requestGroups.push_back(groupToAdd);
  461. ++count;
  462. e->addCommand(commands);
  463. commands.clear();
  464. executeStartHook(groupToAdd, e->option);
  465. } catch(RecoverableException& ex) {
  466. _logger->error(EX_EXCEPTION_CAUGHT, ex);
  467. if(_logger->debug()) {
  468. _logger->debug("Deleting temporal commands.");
  469. }
  470. std::for_each(commands.begin(), commands.end(), Deleter());
  471. commands.clear();
  472. if(_logger->debug()) {
  473. _logger->debug("Commands deleted");
  474. }
  475. groupToAdd->releaseRuntimeResource(e);
  476. _downloadResults.push_back(groupToAdd->createDownloadResult());
  477. }
  478. }
  479. if(!temp.empty()) {
  480. _reservedGroups.insert(_reservedGroups.begin(), temp.begin(), temp.end());
  481. }
  482. if(count > 0) {
  483. e->setNoWait(true);
  484. if(_logger->debug()) {
  485. _logger->debug("%d RequestGroup(s) added.", count);
  486. }
  487. }
  488. }
  489. void RequestGroupMan::save()
  490. {
  491. for(std::deque<SharedHandle<RequestGroup> >::const_iterator itr =
  492. _requestGroups.begin(), eoi = _requestGroups.end(); itr != eoi; ++itr) {
  493. if((*itr)->allDownloadFinished()) {
  494. (*itr)->removeControlFile();
  495. } else {
  496. try {
  497. (*itr)->saveControlFile();
  498. } catch(RecoverableException& e) {
  499. _logger->error(EX_EXCEPTION_CAUGHT, e);
  500. }
  501. }
  502. }
  503. }
  504. void RequestGroupMan::closeFile()
  505. {
  506. for(std::deque<SharedHandle<RequestGroup> >::const_iterator itr =
  507. _requestGroups.begin(), eoi = _requestGroups.end(); itr != eoi; ++itr) {
  508. (*itr)->closeFile();
  509. }
  510. }
  511. RequestGroupMan::DownloadStat RequestGroupMan::getDownloadStat() const
  512. {
  513. size_t finished = 0;
  514. size_t error = 0;
  515. size_t inprogress = 0;
  516. downloadresultcode::RESULT lastError = downloadresultcode::FINISHED;
  517. for(std::deque<SharedHandle<DownloadResult> >::const_iterator itr =
  518. _downloadResults.begin(), eoi = _downloadResults.end();
  519. itr != eoi; ++itr) {
  520. if((*itr)->result == downloadresultcode::FINISHED) {
  521. ++finished;
  522. } else {
  523. ++error;
  524. lastError = (*itr)->result;
  525. }
  526. }
  527. for(std::deque<SharedHandle<RequestGroup> >::const_iterator itr =
  528. _requestGroups.begin(), eoi = _requestGroups.end(); itr != eoi; ++itr) {
  529. DownloadResultHandle result = (*itr)->createDownloadResult();
  530. if(result->result == downloadresultcode::FINISHED) {
  531. ++finished;
  532. } else {
  533. ++inprogress;
  534. }
  535. }
  536. return DownloadStat(finished, error, inprogress, _reservedGroups.size(),
  537. lastError);
  538. }
  539. void RequestGroupMan::showDownloadResults(std::ostream& o) const
  540. {
  541. static const std::string MARK_OK("OK");
  542. static const std::string MARK_ERR("ERR");
  543. static const std::string MARK_INPR("INPR");
  544. // Download Results:
  545. // idx|stat|path/length
  546. // ===+====+=======================================================================
  547. o << "\n"
  548. <<_("Download Results:") << "\n"
  549. << "gid|stat|avg speed |path/URI" << "\n"
  550. << "===+====+===========+";
  551. #ifdef __MINGW32__
  552. int pathRowSize = 58;
  553. #else // !__MINGW32__
  554. int pathRowSize = 59;
  555. #endif // !__MINGW32__
  556. o << std::setfill('=') << std::setw(pathRowSize) << '=' << "\n";
  557. int ok = 0;
  558. int err = 0;
  559. int inpr = 0;
  560. for(std::deque<SharedHandle<DownloadResult> >::const_iterator itr =
  561. _downloadResults.begin(), eoi = _downloadResults.end();
  562. itr != eoi; ++itr) {
  563. std::string status;
  564. if((*itr)->result == downloadresultcode::FINISHED) {
  565. status = MARK_OK;
  566. ++ok;
  567. } else if((*itr)->result == downloadresultcode::IN_PROGRESS) {
  568. status = MARK_INPR;
  569. ++inpr;
  570. } else {
  571. status = MARK_ERR;
  572. ++err;
  573. }
  574. o << formatDownloadResult(status, *itr) << "\n";
  575. }
  576. for(std::deque<SharedHandle<RequestGroup> >::const_iterator itr =
  577. _requestGroups.begin(), eoi = _requestGroups.end(); itr != eoi; ++itr) {
  578. DownloadResultHandle result = (*itr)->createDownloadResult();
  579. std::string status;
  580. if(result->result == downloadresultcode::FINISHED) {
  581. status = MARK_OK;
  582. ++ok;
  583. } else {
  584. // Since this RequestGroup is not processed by ProcessStoppedRequestGroup,
  585. // its download stop time is not reseted.
  586. // Reset download stop time and assign sessionTime here.
  587. (*itr)->getDownloadContext()->resetDownloadStopTime();
  588. result->sessionTime =
  589. (*itr)->getDownloadContext()->calculateSessionTime();
  590. status = MARK_INPR;
  591. ++inpr;
  592. }
  593. o << formatDownloadResult(status, result) << "\n";
  594. }
  595. if(ok > 0 || err > 0 || inpr > 0) {
  596. o << "\n"
  597. << _("Status Legend:") << "\n";
  598. if(ok > 0) {
  599. o << " (OK):download completed.";
  600. }
  601. if(err > 0) {
  602. o << "(ERR):error occurred.";
  603. }
  604. if(inpr > 0) {
  605. o << "(INPR):download in-progress.";
  606. }
  607. o << "\n";
  608. }
  609. }
  610. std::string RequestGroupMan::formatDownloadResult(const std::string& status, const DownloadResultHandle& downloadResult) const
  611. {
  612. std::stringstream o;
  613. o << std::setw(3) << downloadResult->gid << "|"
  614. << std::setw(4) << status << "|"
  615. << std::setw(11);
  616. if(downloadResult->sessionTime > 0) {
  617. o << util::abbrevSize
  618. (downloadResult->sessionDownloadLength*1000/downloadResult->sessionTime)+
  619. "B/s";
  620. } else {
  621. o << "n/a";
  622. }
  623. o << "|";
  624. const std::vector<SharedHandle<FileEntry> >& fileEntries =
  625. downloadResult->fileEntries;
  626. writeFilePath(fileEntries.begin(), fileEntries.end(), o,
  627. downloadResult->inMemoryDownload);
  628. return o.str();
  629. }
  630. template<typename StringInputIterator, typename FileEntryInputIterator>
  631. static bool sameFilePathExists(StringInputIterator sfirst,
  632. StringInputIterator slast,
  633. FileEntryInputIterator ffirst,
  634. FileEntryInputIterator flast)
  635. {
  636. for(; ffirst != flast; ++ffirst) {
  637. if(std::binary_search(sfirst, slast, (*ffirst)->getPath())) {
  638. return true;
  639. }
  640. }
  641. return false;
  642. }
  643. bool RequestGroupMan::isSameFileBeingDownloaded(RequestGroup* requestGroup) const
  644. {
  645. // TODO it may be good to use dedicated method rather than use
  646. // isPreLocalFileCheckEnabled
  647. if(!requestGroup->isPreLocalFileCheckEnabled()) {
  648. return false;
  649. }
  650. std::vector<std::string> files;
  651. for(std::deque<SharedHandle<RequestGroup> >::const_iterator itr =
  652. _requestGroups.begin(), eoi = _requestGroups.end(); itr != eoi; ++itr) {
  653. if((*itr).get() != requestGroup) {
  654. const std::vector<SharedHandle<FileEntry> >& entries =
  655. (*itr)->getDownloadContext()->getFileEntries();
  656. std::transform(entries.begin(), entries.end(),
  657. std::back_inserter(files),
  658. mem_fun_sh(&FileEntry::getPath));
  659. }
  660. }
  661. std::sort(files.begin(), files.end());
  662. const std::vector<SharedHandle<FileEntry> >& entries =
  663. requestGroup->getDownloadContext()->getFileEntries();
  664. return sameFilePathExists(files.begin(), files.end(),
  665. entries.begin(), entries.end());
  666. }
  667. void RequestGroupMan::halt()
  668. {
  669. for(std::deque<SharedHandle<RequestGroup> >::const_iterator i =
  670. _requestGroups.begin(), eoi = _requestGroups.end(); i != eoi; ++i) {
  671. (*i)->setHaltRequested(true);
  672. }
  673. }
  674. void RequestGroupMan::forceHalt()
  675. {
  676. for(std::deque<SharedHandle<RequestGroup> >::const_iterator i =
  677. _requestGroups.begin(), eoi = _requestGroups.end(); i != eoi; ++i) {
  678. (*i)->setForceHaltRequested(true);
  679. }
  680. }
  681. TransferStat RequestGroupMan::calculateStat()
  682. {
  683. TransferStat s;
  684. for(std::deque<SharedHandle<RequestGroup> >::const_iterator i =
  685. _requestGroups.begin(), eoi = _requestGroups.end(); i != eoi; ++i) {
  686. s += (*i)->calculateStat();
  687. }
  688. return s;
  689. }
  690. SharedHandle<DownloadResult>
  691. RequestGroupMan::findDownloadResult(int32_t gid) const
  692. {
  693. for(std::deque<SharedHandle<DownloadResult> >::const_iterator i =
  694. _downloadResults.begin(), eoi = _downloadResults.end(); i != eoi; ++i) {
  695. if((*i)->gid == gid) {
  696. return *i;
  697. }
  698. }
  699. return SharedHandle<DownloadResult>();
  700. }
  701. void RequestGroupMan::purgeDownloadResult()
  702. {
  703. _downloadResults.clear();
  704. }
  705. SharedHandle<ServerStat>
  706. RequestGroupMan::findServerStat(const std::string& hostname,
  707. const std::string& protocol) const
  708. {
  709. return _serverStatMan->find(hostname, protocol);
  710. }
  711. SharedHandle<ServerStat>
  712. RequestGroupMan::getOrCreateServerStat(const std::string& hostname,
  713. const std::string& protocol)
  714. {
  715. SharedHandle<ServerStat> ss = findServerStat(hostname, protocol);
  716. if(ss.isNull()) {
  717. ss.reset(new ServerStat(hostname, protocol));
  718. addServerStat(ss);
  719. }
  720. return ss;
  721. }
  722. bool RequestGroupMan::addServerStat(const SharedHandle<ServerStat>& serverStat)
  723. {
  724. return _serverStatMan->add(serverStat);
  725. }
  726. bool RequestGroupMan::loadServerStat(const std::string& filename)
  727. {
  728. std::ifstream in(filename.c_str(), std::ios::binary);
  729. if(!in) {
  730. _logger->error(MSG_OPENING_READABLE_SERVER_STAT_FILE_FAILED, filename.c_str());
  731. return false;
  732. }
  733. if(_serverStatMan->load(in)) {
  734. _logger->notice(MSG_SERVER_STAT_LOADED, filename.c_str());
  735. return true;
  736. } else {
  737. _logger->error(MSG_READING_SERVER_STAT_FILE_FAILED, filename.c_str());
  738. return false;
  739. }
  740. }
  741. bool RequestGroupMan::saveServerStat(const std::string& filename) const
  742. {
  743. std::string tempfile = filename;
  744. tempfile += "__temp";
  745. {
  746. std::ofstream out(tempfile.c_str(), std::ios::binary);
  747. if(!out) {
  748. _logger->error(MSG_OPENING_WRITABLE_SERVER_STAT_FILE_FAILED,
  749. filename.c_str());
  750. return false;
  751. }
  752. if(!_serverStatMan->save(out)) {
  753. _logger->error(MSG_WRITING_SERVER_STAT_FILE_FAILED, filename.c_str());
  754. return false;
  755. }
  756. }
  757. if(File(tempfile).renameTo(filename)) {
  758. _logger->notice(MSG_SERVER_STAT_SAVED, filename.c_str());
  759. return true;
  760. } else {
  761. _logger->error(MSG_WRITING_SERVER_STAT_FILE_FAILED, filename.c_str());
  762. return false;
  763. }
  764. }
  765. void RequestGroupMan::removeStaleServerStat(time_t timeout)
  766. {
  767. _serverStatMan->removeStaleServerStat(timeout);
  768. }
  769. bool RequestGroupMan::doesOverallDownloadSpeedExceed()
  770. {
  771. return _maxOverallDownloadSpeedLimit > 0 &&
  772. _maxOverallDownloadSpeedLimit < calculateStat().getDownloadSpeed();
  773. }
  774. bool RequestGroupMan::doesOverallUploadSpeedExceed()
  775. {
  776. return _maxOverallUploadSpeedLimit > 0 &&
  777. _maxOverallUploadSpeedLimit < calculateStat().getUploadSpeed();
  778. }
  779. } // namespace aria2