AdaptiveURISelector.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. /* <!-- copyright */
  2. /*
  3. * aria2 - The high speed download utility
  4. *
  5. * Copyright (C) 2006 Tatsuhiro Tsujikawa
  6. * Copyright (C) 2008 Aurelien Lefebvre, Mandriva
  7. *
  8. * This program is free software; you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation; either version 2 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program; if not, write to the Free Software
  20. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  21. *
  22. * In addition, as a special exception, the copyright holders give
  23. * permission to link the code of portions of this program with the
  24. * OpenSSL library under certain conditions as described in each
  25. * individual source file, and distribute linked combinations
  26. * including the two.
  27. * You must obey the GNU General Public License in all respects
  28. * for all of the code used other than OpenSSL. If you modify
  29. * file(s) with this exception, you may extend this exception to your
  30. * version of the file(s), but you are not obligated to do so. If you
  31. * do not wish to do so, delete this exception statement from your
  32. * version. If you delete this exception statement from all source
  33. * files in the program, then also delete it here.
  34. */
  35. /* copyright --> */
  36. #include "AdaptiveURISelector.h"
  37. #include <cstdlib>
  38. #include <cmath>
  39. #include <algorithm>
  40. #include "DownloadCommand.h"
  41. #include "DownloadContext.h"
  42. #include "ServerStatMan.h"
  43. #include "ServerStat.h"
  44. #include "RequestGroup.h"
  45. #include "LogFactory.h"
  46. #include "A2STR.h"
  47. #include "prefs.h"
  48. #include "Option.h"
  49. #include "SimpleRandomizer.h"
  50. #include "SocketCore.h"
  51. #include "FileEntry.h"
  52. namespace aria2 {
  53. /* In that URI Selector, select method returns one of the bests
  54. * mirrors for first and reserved connections. For supplementary
  55. * ones, it returns mirrors which has not been tested yet, and
  56. * if each of them already tested, returns mirrors which has to
  57. * be tested again. Otherwise, it doesn't return anymore mirrors.
  58. */
  59. AdaptiveURISelector::AdaptiveURISelector
  60. (const SharedHandle<ServerStatMan>& serverStatMan, RequestGroup* requestGroup):
  61. _serverStatMan(serverStatMan),
  62. _requestGroup(requestGroup),
  63. _logger(LogFactory::getInstance())
  64. {
  65. resetCounters();
  66. }
  67. AdaptiveURISelector::~AdaptiveURISelector() {}
  68. std::string AdaptiveURISelector::select(FileEntry* fileEntry)
  69. {
  70. _logger->debug("AdaptiveURISelector: called %d",
  71. _requestGroup->getNumConnection());
  72. std::deque<std::string>& uris = fileEntry->getRemainingUris();
  73. if (uris.empty() && _requestGroup->getNumConnection() <= 1) {
  74. // here we know the download will fail, trying to find previously
  75. // failed uris that may succeed with more permissive values
  76. mayRetryWithIncreasedTimeout(fileEntry);
  77. }
  78. std::string selected = selectOne(uris);
  79. if(selected != A2STR::NIL)
  80. uris.erase(std::find(uris.begin(), uris.end(), selected));
  81. return selected;
  82. }
  83. void AdaptiveURISelector::mayRetryWithIncreasedTimeout(FileEntry* fileEntry)
  84. {
  85. if (_requestGroup->getTimeout()*2 >= MAX_TIMEOUT) return;
  86. _requestGroup->setTimeout(_requestGroup->getTimeout()*2);
  87. std::deque<std::string>& uris = fileEntry->getRemainingUris();
  88. // looking for retries
  89. std::deque<URIResult> timeouts;
  90. fileEntry->extractURIResult(timeouts, downloadresultcode::TIME_OUT);
  91. std::transform(timeouts.begin(), timeouts.end(), std::back_inserter(uris),
  92. std::mem_fun_ref(&URIResult::getURI));
  93. for(std::deque<std::string>::const_iterator i = uris.begin(); i != uris.end();
  94. ++i) {
  95. _logger->debug("AdaptiveURISelector: will retry server with increased"
  96. " timeout (%d s): %s",
  97. _requestGroup->getTimeout(), (*i).c_str());
  98. }
  99. }
  100. std::string AdaptiveURISelector::selectOne(const std::deque<std::string>& uris)
  101. {
  102. if(uris.empty()) {
  103. return A2STR::NIL;
  104. } else {
  105. const unsigned int numPieces =
  106. _requestGroup->getDownloadContext()->getNumPieces();
  107. bool reservedContext = numPieces > 0 &&
  108. _nbConnections > std::min(numPieces,
  109. _requestGroup->getNumConcurrentCommand());
  110. bool selectBest = numPieces == 0 || reservedContext;
  111. if(numPieces > 0)
  112. ++_nbConnections;
  113. /* At least, 3 mirrors must be tested */
  114. if(getNbTestedServers(uris) < 3) {
  115. std::string notTested = getFirstNotTestedUri(uris);
  116. if(notTested != A2STR::NIL) {
  117. _logger->debug("AdaptiveURISelector: choosing the first non tested"
  118. " mirror: %s", notTested.c_str());
  119. --_nbServerToEvaluate;
  120. return notTested;
  121. }
  122. }
  123. if(!selectBest && _nbConnections > 1 && _nbServerToEvaluate > 0) {
  124. _nbServerToEvaluate--;
  125. std::string notTested = getFirstNotTestedUri(uris);
  126. if(notTested != A2STR::NIL) {
  127. /* Here we return the first untested mirror */
  128. _logger->debug("AdaptiveURISelector: choosing non tested mirror %s for"
  129. " connection #%d", notTested.c_str(), _nbConnections);
  130. return notTested;
  131. } else {
  132. /* Here we return a mirror which need to be tested again */
  133. std::string toReTest = getFirstToTestUri(uris);
  134. if(toReTest != A2STR::NIL) {
  135. _logger->debug("AdaptiveURISelector: choosing mirror %s which has not"
  136. " been tested recently for connection #%d",
  137. toReTest.c_str(), _nbConnections);
  138. return toReTest;
  139. } else {
  140. return getBestMirror(uris);
  141. }
  142. }
  143. }
  144. else {
  145. return getBestMirror(uris);
  146. }
  147. }
  148. }
  149. std::string AdaptiveURISelector::getBestMirror
  150. (const std::deque<std::string>& uris) const
  151. {
  152. /* Here we return one of the bests mirrors */
  153. unsigned int max = getMaxDownloadSpeed(uris);
  154. unsigned int min = max-(int)(max*0.25);
  155. std::deque<std::string> bests = getUrisBySpeed(uris, min);
  156. if (bests.size() < 2) {
  157. std::string uri = getMaxDownloadSpeedUri(uris);
  158. _logger->debug("AdaptiveURISelector: choosing the best mirror :"
  159. " %.2fKB/s %s (other mirrors are at least 25%% slower)",
  160. (float) max/1024, uri.c_str());
  161. return uri;
  162. } else {
  163. std::string uri = selectRandomUri(bests);
  164. _logger->debug("AdaptiveURISelector: choosing randomly one of the best"
  165. " mirrors (range [%.2fKB/s, %.2fKB/s]): %s",
  166. (float) min/1024, (float) max/1024, uri.c_str());
  167. return uri;
  168. }
  169. }
  170. void AdaptiveURISelector::resetCounters()
  171. {
  172. _nbConnections = 1;
  173. _nbServerToEvaluate =
  174. _requestGroup->getOption()->getAsInt(PREF_METALINK_SERVERS) - 1;
  175. }
  176. void AdaptiveURISelector::tuneDownloadCommand
  177. (const std::deque<std::string>& uris, DownloadCommand* command)
  178. {
  179. adjustLowestSpeedLimit(uris, command);
  180. }
  181. void AdaptiveURISelector::adjustLowestSpeedLimit
  182. (const std::deque<std::string>& uris, DownloadCommand* command) const
  183. {
  184. unsigned int lowest =
  185. _requestGroup->getOption()->getAsInt(PREF_LOWEST_SPEED_LIMIT);
  186. if (lowest > 0) {
  187. unsigned int low_lowest = 4 * 1024;
  188. unsigned int max = getMaxDownloadSpeed(uris);
  189. if (max > 0 && lowest > max / 4) {
  190. _logger->notice("Lowering lowest-speed-limit since known max speed is too"
  191. " near (new:%d was:%d max:%d)", max / 4, lowest, max);
  192. command->setLowestDownloadSpeedLimit(max / 4);
  193. } else if (max == 0 && lowest > low_lowest) {
  194. _logger->notice("Lowering lowest-speed-limit since we have no clue about"
  195. " available speed (now:%d was:%d)", low_lowest, lowest);
  196. command->setLowestDownloadSpeedLimit(low_lowest);
  197. }
  198. }
  199. }
  200. static unsigned int getUriMaxSpeed(SharedHandle<ServerStat> ss)
  201. {
  202. return std::max(ss->getSingleConnectionAvgSpeed(),
  203. ss->getMultiConnectionAvgSpeed());
  204. }
  205. unsigned int AdaptiveURISelector::getMaxDownloadSpeed
  206. (const std::deque<std::string>& uris) const
  207. {
  208. std::string uri = getMaxDownloadSpeedUri(uris);
  209. if(uri == A2STR::NIL)
  210. return 0;
  211. return getUriMaxSpeed(getServerStats(uri));
  212. }
  213. std::string AdaptiveURISelector::getMaxDownloadSpeedUri
  214. (const std::deque<std::string>& uris) const
  215. {
  216. int max = -1;
  217. std::string uri = A2STR::NIL;
  218. for(std::deque<std::string>::const_iterator i = uris.begin();
  219. i != uris.end(); ++i) {
  220. SharedHandle<ServerStat> ss = getServerStats(*i);
  221. if(ss.isNull())
  222. continue;
  223. if((int)ss->getSingleConnectionAvgSpeed() > max) {
  224. max = ss->getSingleConnectionAvgSpeed();
  225. uri = (*i);
  226. }
  227. if((int)ss->getMultiConnectionAvgSpeed() > max) {
  228. max = ss->getMultiConnectionAvgSpeed();
  229. uri = (*i);
  230. }
  231. }
  232. return uri;
  233. }
  234. std::deque<std::string> AdaptiveURISelector::getUrisBySpeed
  235. (const std::deque<std::string>& uris, unsigned int min) const
  236. {
  237. std::deque<std::string> bests;
  238. for(std::deque<std::string>::const_iterator i = uris.begin();
  239. i != uris.end(); ++i) {
  240. SharedHandle<ServerStat> ss = getServerStats(*i);
  241. if(ss.isNull())
  242. continue;
  243. if(ss->getSingleConnectionAvgSpeed() > min ||
  244. ss->getMultiConnectionAvgSpeed() > min) {
  245. bests.push_back(*i);
  246. }
  247. }
  248. return bests;
  249. }
  250. std::string AdaptiveURISelector::selectRandomUri
  251. (const std::deque<std::string>& uris) const
  252. {
  253. int pos = SimpleRandomizer::getInstance()->getRandomNumber(uris.size());
  254. std::deque<std::string>::const_iterator i = uris.begin();
  255. i = i+pos;
  256. return *i;
  257. }
  258. std::string AdaptiveURISelector::getFirstNotTestedUri
  259. (const std::deque<std::string>& uris) const
  260. {
  261. for(std::deque<std::string>::const_iterator i = uris.begin();
  262. i != uris.end(); ++i) {
  263. SharedHandle<ServerStat> ss = getServerStats(*i);
  264. if(ss.isNull())
  265. return *i;
  266. }
  267. return A2STR::NIL;
  268. }
  269. std::string AdaptiveURISelector::getFirstToTestUri
  270. (const std::deque<std::string>& uris) const
  271. {
  272. unsigned int counter;
  273. int power;
  274. for(std::deque<std::string>::const_iterator i = uris.begin();
  275. i != uris.end(); ++i) {
  276. SharedHandle<ServerStat> ss = getServerStats(*i);
  277. if(ss.isNull())
  278. continue;
  279. counter = ss->getCounter();
  280. if(counter > 8)
  281. continue;
  282. power = (int)pow(2.0, (float)counter);
  283. /* We test the mirror another time if it has not been
  284. * tested since 2^counter days */
  285. if(ss->getLastUpdated().difference() > power*24*60*60) {
  286. return *i;
  287. }
  288. }
  289. return A2STR::NIL;
  290. }
  291. SharedHandle<ServerStat> AdaptiveURISelector::getServerStats
  292. (const std::string& uri) const
  293. {
  294. Request r;
  295. r.setUrl(uri);
  296. return _serverStatMan->find(r.getHost(), r.getProtocol());
  297. }
  298. unsigned int AdaptiveURISelector::getNbTestedServers
  299. (const std::deque<std::string>& uris) const
  300. {
  301. unsigned int counter = 0;
  302. for(std::deque<std::string>::const_iterator i = uris.begin();
  303. i != uris.end(); ++i) {
  304. SharedHandle<ServerStat> ss = getServerStats(*i);
  305. if(ss.isNull())
  306. ++counter;
  307. }
  308. return uris.size() - counter;
  309. }
  310. } // namespace aria2