AdaptiveURISelector.cc 12 KB

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