AdaptiveURISelector.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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. namespace aria2 {
  52. /* In that URI Selector, select method returns one of the bests
  53. * mirrors for first and reserved connections. For supplementary
  54. * ones, it returns mirrors which has not been tested yet, and
  55. * if each of them already tested, returns mirrors which has to
  56. * be tested again. Otherwise, it doesn't return anymore mirrors.
  57. */
  58. AdaptiveURISelector::AdaptiveURISelector
  59. (const SharedHandle<ServerStatMan>& serverStatMan, RequestGroup* requestGroup):
  60. _serverStatMan(serverStatMan),
  61. _requestGroup(requestGroup),
  62. _logger(LogFactory::getInstance())
  63. {
  64. resetCounters();
  65. }
  66. AdaptiveURISelector::~AdaptiveURISelector() {}
  67. std::string AdaptiveURISelector::select(std::deque<std::string>& uris)
  68. {
  69. _logger->debug("AdaptiveURISelector: called %d",
  70. _requestGroup->getNumConnection());
  71. if (uris.empty() && _requestGroup->getNumConnection() <= 1) {
  72. // here we know the download will fail, trying to find previously
  73. // failed uris that may succeed with more permissive values
  74. mayRetryWithIncreasedTimeout(uris);
  75. }
  76. std::string selected = selectOne(uris);
  77. if(selected != A2STR::NIL)
  78. uris.erase(std::find(uris.begin(), uris.end(), selected));
  79. return selected;
  80. }
  81. void AdaptiveURISelector::mayRetryWithIncreasedTimeout
  82. (std::deque<std::string>& uris)
  83. {
  84. if (_requestGroup->getTimeout()*2 >= MAX_TIMEOUT) return;
  85. _requestGroup->setTimeout(_requestGroup->getTimeout()*2);
  86. // looking for retries
  87. std::deque<URIResult> timeouts;
  88. _requestGroup->extractURIResult(timeouts, DownloadResult::TIME_OUT);
  89. std::transform(timeouts.begin(), timeouts.end(), std::back_inserter(uris),
  90. std::mem_fun_ref(&URIResult::getURI));
  91. for(std::deque<std::string>::const_iterator i = uris.begin(); i != uris.end();
  92. ++i) {
  93. _logger->debug("AdaptiveURISelector: will retry server with increased"
  94. " timeout (%d s): %s",
  95. _requestGroup->getTimeout(), (*i).c_str());
  96. }
  97. }
  98. std::string AdaptiveURISelector::selectOne(const std::deque<std::string>& uris)
  99. {
  100. if(uris.empty()) {
  101. return A2STR::NIL;
  102. } else {
  103. const unsigned int numPieces =
  104. _requestGroup->getDownloadContext()->getNumPieces();
  105. bool reservedContext = numPieces > 0 &&
  106. _nbConnections > std::min(numPieces,
  107. _requestGroup->getNumConcurrentCommand());
  108. bool selectBest = numPieces == 0 || reservedContext;
  109. if(numPieces > 0)
  110. ++_nbConnections;
  111. /* At least, 3 mirrors must be tested */
  112. if(getNbTestedServers(uris) < 3) {
  113. std::string notTested = getFirstNotTestedUri(uris);
  114. if(notTested != A2STR::NIL) {
  115. _logger->debug("AdaptiveURISelector: choosing the first non tested"
  116. " mirror: %s", notTested.c_str());
  117. --_nbServerToEvaluate;
  118. return notTested;
  119. }
  120. }
  121. if(!selectBest && _nbConnections > 1 && _nbServerToEvaluate > 0) {
  122. _nbServerToEvaluate--;
  123. std::string notTested = getFirstNotTestedUri(uris);
  124. if(notTested != A2STR::NIL) {
  125. /* Here we return the first untested mirror */
  126. _logger->debug("AdaptiveURISelector: choosing non tested mirror %s for"
  127. " connection #%d", notTested.c_str(), _nbConnections);
  128. return notTested;
  129. } else {
  130. /* Here we return a mirror which need to be tested again */
  131. std::string toReTest = getFirstToTestUri(uris);
  132. if(toReTest != A2STR::NIL) {
  133. _logger->debug("AdaptiveURISelector: choosing mirror %s which has not"
  134. " been tested recently for connection #%d",
  135. toReTest.c_str(), _nbConnections);
  136. return toReTest;
  137. } else {
  138. return getBestMirror(uris);
  139. }
  140. }
  141. }
  142. else {
  143. return getBestMirror(uris);
  144. }
  145. }
  146. }
  147. std::string AdaptiveURISelector::getBestMirror
  148. (const std::deque<std::string>& uris) const
  149. {
  150. /* Here we return one of the bests mirrors */
  151. unsigned int max = getMaxDownloadSpeed(uris);
  152. unsigned int min = max-(int)(max*0.25);
  153. std::deque<std::string> bests = getUrisBySpeed(uris, min);
  154. if (bests.size() < 2) {
  155. std::string uri = getMaxDownloadSpeedUri(uris);
  156. _logger->debug("AdaptiveURISelector: choosing the best mirror :"
  157. " %.2fKB/s %s (other mirrors are at least 25%% slower)",
  158. (float) max/1024, uri.c_str());
  159. return uri;
  160. } else {
  161. std::string uri = selectRandomUri(bests);
  162. _logger->debug("AdaptiveURISelector: choosing randomly one of the best"
  163. " mirrors (range [%.2fKB/s, %.2fKB/s]): %s",
  164. (float) min/1024, (float) max/1024, uri.c_str());
  165. return uri;
  166. }
  167. }
  168. void AdaptiveURISelector::resetCounters()
  169. {
  170. _nbConnections = 1;
  171. _nbServerToEvaluate =
  172. _requestGroup->getOption()->getAsInt(PREF_METALINK_SERVERS) - 1;
  173. }
  174. void AdaptiveURISelector::tuneDownloadCommand
  175. (const std::deque<std::string>& uris, DownloadCommand* command)
  176. {
  177. adjustLowestSpeedLimit(uris, command);
  178. }
  179. void AdaptiveURISelector::adjustLowestSpeedLimit
  180. (const std::deque<std::string>& uris, DownloadCommand* command) const
  181. {
  182. unsigned int lowest =
  183. _requestGroup->getOption()->getAsInt(PREF_LOWEST_SPEED_LIMIT);
  184. if (lowest > 0) {
  185. unsigned int low_lowest = 4 * 1024;
  186. unsigned int max = getMaxDownloadSpeed(uris);
  187. if (max > 0 && lowest > max / 4) {
  188. _logger->notice("Lowering lowest-speed-limit since known max speed is too"
  189. " near (new:%d was:%d max:%d)", max / 4, lowest, max);
  190. command->setLowestDownloadSpeedLimit(max / 4);
  191. } else if (max == 0 && lowest > low_lowest) {
  192. _logger->notice("Lowering lowest-speed-limit since we have no clue about"
  193. " available speed (now:%d was:%d)", low_lowest, lowest);
  194. command->setLowestDownloadSpeedLimit(low_lowest);
  195. }
  196. }
  197. }
  198. static unsigned int getUriMaxSpeed(SharedHandle<ServerStat> ss)
  199. {
  200. return std::max(ss->getSingleConnectionAvgSpeed(),
  201. ss->getMultiConnectionAvgSpeed());
  202. }
  203. unsigned int AdaptiveURISelector::getMaxDownloadSpeed
  204. (const std::deque<std::string>& uris) const
  205. {
  206. std::string uri = getMaxDownloadSpeedUri(uris);
  207. if(uri == A2STR::NIL)
  208. return 0;
  209. return getUriMaxSpeed(getServerStats(uri));
  210. }
  211. std::string AdaptiveURISelector::getMaxDownloadSpeedUri
  212. (const std::deque<std::string>& uris) const
  213. {
  214. int max = -1;
  215. std::string uri = A2STR::NIL;
  216. for(std::deque<std::string>::const_iterator i = uris.begin();
  217. i != uris.end(); ++i) {
  218. SharedHandle<ServerStat> ss = getServerStats(*i);
  219. if(ss.isNull())
  220. continue;
  221. if((int)ss->getSingleConnectionAvgSpeed() > max) {
  222. max = ss->getSingleConnectionAvgSpeed();
  223. uri = (*i);
  224. }
  225. if((int)ss->getMultiConnectionAvgSpeed() > max) {
  226. max = ss->getMultiConnectionAvgSpeed();
  227. uri = (*i);
  228. }
  229. }
  230. return uri;
  231. }
  232. std::deque<std::string> AdaptiveURISelector::getUrisBySpeed
  233. (const std::deque<std::string>& uris, unsigned int min) const
  234. {
  235. std::deque<std::string> bests;
  236. for(std::deque<std::string>::const_iterator i = uris.begin();
  237. i != uris.end(); ++i) {
  238. SharedHandle<ServerStat> ss = getServerStats(*i);
  239. if(ss.isNull())
  240. continue;
  241. if(ss->getSingleConnectionAvgSpeed() > min ||
  242. ss->getMultiConnectionAvgSpeed() > min) {
  243. bests.push_back(*i);
  244. }
  245. }
  246. return bests;
  247. }
  248. std::string AdaptiveURISelector::selectRandomUri
  249. (const std::deque<std::string>& uris) const
  250. {
  251. int pos = SimpleRandomizer::getInstance()->getRandomNumber(uris.size());
  252. std::deque<std::string>::const_iterator i = uris.begin();
  253. i = i+pos;
  254. return *i;
  255. }
  256. std::string AdaptiveURISelector::getFirstNotTestedUri
  257. (const std::deque<std::string>& uris) const
  258. {
  259. for(std::deque<std::string>::const_iterator i = uris.begin();
  260. i != uris.end(); ++i) {
  261. SharedHandle<ServerStat> ss = getServerStats(*i);
  262. if(ss.isNull())
  263. return *i;
  264. }
  265. return A2STR::NIL;
  266. }
  267. std::string AdaptiveURISelector::getFirstToTestUri
  268. (const std::deque<std::string>& uris) const
  269. {
  270. unsigned int counter;
  271. int power;
  272. for(std::deque<std::string>::const_iterator i = uris.begin();
  273. i != uris.end(); ++i) {
  274. SharedHandle<ServerStat> ss = getServerStats(*i);
  275. if(ss.isNull())
  276. continue;
  277. counter = ss->getCounter();
  278. if(counter > 8)
  279. continue;
  280. power = (int)pow(2.0, (float)counter);
  281. /* We test the mirror another time if it has not been
  282. * tested since 2^counter days */
  283. if(ss->getLastUpdated().difference() > power*24*60*60) {
  284. return *i;
  285. }
  286. }
  287. return A2STR::NIL;
  288. }
  289. SharedHandle<ServerStat> AdaptiveURISelector::getServerStats
  290. (const std::string& uri) const
  291. {
  292. Request r;
  293. r.setUrl(uri);
  294. return _serverStatMan->find(r.getHost(), r.getProtocol());
  295. }
  296. unsigned int AdaptiveURISelector::getNbTestedServers
  297. (const std::deque<std::string>& uris) const
  298. {
  299. unsigned int counter = 0;
  300. for(std::deque<std::string>::const_iterator i = uris.begin();
  301. i != uris.end(); ++i) {
  302. SharedHandle<ServerStat> ss = getServerStats(*i);
  303. if(ss.isNull())
  304. ++counter;
  305. }
  306. return uris.size() - counter;
  307. }
  308. } // namespace aria2