AdaptiveURISelector.cc 12 KB

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