AdaptiveURISelector.cc 12 KB

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