RequestGroupMan.cc 25 KB

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