AdaptiveURISelector.cc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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
  69. (FileEntry* fileEntry,
  70. const std::vector<std::pair<size_t, std::string> >& usedHosts)
  71. {
  72. if(logger_->debug()) {
  73. logger_->debug("AdaptiveURISelector: called %d",
  74. requestGroup_->getNumConnection());
  75. }
  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, downloadresultcode::TIME_OUT);
  95. std::transform(timeouts.begin(), timeouts.end(), std::back_inserter(uris),
  96. std::mem_fun_ref(&URIResult::getURI));
  97. if(logger_->debug()) {
  98. for(std::deque<std::string>::const_iterator i = uris.begin(),
  99. eoi = uris.end(); i != eoi; ++i) {
  100. logger_->debug("AdaptiveURISelector: will retry server with increased"
  101. " timeout (%d s): %s",
  102. requestGroup_->getTimeout(), (*i).c_str());
  103. }
  104. }
  105. }
  106. std::string AdaptiveURISelector::selectOne(const std::deque<std::string>& uris)
  107. {
  108. if(uris.empty()) {
  109. return A2STR::NIL;
  110. } else {
  111. const unsigned int numPieces =
  112. requestGroup_->getDownloadContext()->getNumPieces();
  113. bool reservedContext = numPieces > 0 &&
  114. nbConnections_ > std::min(numPieces,
  115. requestGroup_->getNumConcurrentCommand());
  116. bool selectBest = numPieces == 0 || reservedContext;
  117. if(numPieces > 0)
  118. ++nbConnections_;
  119. /* At least, 3 mirrors must be tested */
  120. if(getNbTestedServers(uris) < 3) {
  121. std::string notTested = getFirstNotTestedUri(uris);
  122. if(notTested != A2STR::NIL) {
  123. if(logger_->debug()) {
  124. logger_->debug("AdaptiveURISelector: choosing the first non tested"
  125. " mirror: %s", notTested.c_str());
  126. }
  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. if(logger_->debug()) {
  137. logger_->debug("AdaptiveURISelector: choosing non tested mirror %s"
  138. " for connection #%d",
  139. notTested.c_str(), nbConnections_);
  140. }
  141. return notTested;
  142. } else {
  143. /* Here we return a mirror which need to be tested again */
  144. std::string toReTest = getFirstToTestUri(uris);
  145. if(toReTest != A2STR::NIL) {
  146. if(logger_->debug()) {
  147. logger_->debug("AdaptiveURISelector: choosing mirror %s which has"
  148. " not been tested recently for connection #%d",
  149. toReTest.c_str(), nbConnections_);
  150. }
  151. return toReTest;
  152. } else {
  153. return getBestMirror(uris);
  154. }
  155. }
  156. }
  157. else {
  158. return getBestMirror(uris);
  159. }
  160. }
  161. }
  162. std::string AdaptiveURISelector::getBestMirror
  163. (const std::deque<std::string>& uris) const
  164. {
  165. /* Here we return one of the bests mirrors */
  166. unsigned int max = getMaxDownloadSpeed(uris);
  167. unsigned int min = max-(int)(max*0.25);
  168. std::deque<std::string> bests = getUrisBySpeed(uris, min);
  169. if (bests.size() < 2) {
  170. std::string uri = getMaxDownloadSpeedUri(uris);
  171. if(logger_->debug()) {
  172. logger_->debug("AdaptiveURISelector: choosing the best mirror :"
  173. " %.2fKB/s %s (other mirrors are at least 25%% slower)",
  174. (float) max/1024, uri.c_str());
  175. }
  176. return uri;
  177. } else {
  178. std::string uri = selectRandomUri(bests);
  179. if(logger_->debug()) {
  180. logger_->debug("AdaptiveURISelector: choosing randomly one of the best"
  181. " mirrors (range [%.2fKB/s, %.2fKB/s]): %s",
  182. (float) min/1024, (float) max/1024, uri.c_str());
  183. }
  184. return uri;
  185. }
  186. }
  187. void AdaptiveURISelector::resetCounters()
  188. {
  189. nbConnections_ = 1;
  190. nbServerToEvaluate_ =
  191. requestGroup_->getOption()->getAsInt(PREF_METALINK_SERVERS) - 1;
  192. }
  193. void AdaptiveURISelector::tuneDownloadCommand
  194. (const std::deque<std::string>& uris, DownloadCommand* command)
  195. {
  196. adjustLowestSpeedLimit(uris, command);
  197. }
  198. void AdaptiveURISelector::adjustLowestSpeedLimit
  199. (const std::deque<std::string>& uris, DownloadCommand* command) const
  200. {
  201. unsigned int lowest =
  202. requestGroup_->getOption()->getAsInt(PREF_LOWEST_SPEED_LIMIT);
  203. if (lowest > 0) {
  204. unsigned int low_lowest = 4 * 1024;
  205. unsigned int max = getMaxDownloadSpeed(uris);
  206. if (max > 0 && lowest > max / 4) {
  207. logger_->notice("Lowering lowest-speed-limit since known max speed is too"
  208. " near (new:%d was:%d max:%d)", max / 4, lowest, max);
  209. command->setLowestDownloadSpeedLimit(max / 4);
  210. } else if (max == 0 && lowest > low_lowest) {
  211. logger_->notice("Lowering lowest-speed-limit since we have no clue about"
  212. " available speed (now:%d was:%d)", low_lowest, lowest);
  213. command->setLowestDownloadSpeedLimit(low_lowest);
  214. }
  215. }
  216. }
  217. static unsigned int getUriMaxSpeed(SharedHandle<ServerStat> ss)
  218. {
  219. return std::max(ss->getSingleConnectionAvgSpeed(),
  220. ss->getMultiConnectionAvgSpeed());
  221. }
  222. unsigned int AdaptiveURISelector::getMaxDownloadSpeed
  223. (const std::deque<std::string>& uris) const
  224. {
  225. std::string uri = getMaxDownloadSpeedUri(uris);
  226. if(uri == A2STR::NIL)
  227. return 0;
  228. return getUriMaxSpeed(getServerStats(uri));
  229. }
  230. std::string AdaptiveURISelector::getMaxDownloadSpeedUri
  231. (const std::deque<std::string>& uris) const
  232. {
  233. int max = -1;
  234. std::string uri = A2STR::NIL;
  235. for(std::deque<std::string>::const_iterator i = uris.begin(),
  236. eoi = uris.end(); i != eoi; ++i) {
  237. SharedHandle<ServerStat> ss = getServerStats(*i);
  238. if(ss.isNull())
  239. continue;
  240. if((int)ss->getSingleConnectionAvgSpeed() > max) {
  241. max = ss->getSingleConnectionAvgSpeed();
  242. uri = (*i);
  243. }
  244. if((int)ss->getMultiConnectionAvgSpeed() > max) {
  245. max = ss->getMultiConnectionAvgSpeed();
  246. uri = (*i);
  247. }
  248. }
  249. return uri;
  250. }
  251. std::deque<std::string> AdaptiveURISelector::getUrisBySpeed
  252. (const std::deque<std::string>& uris, unsigned int min) const
  253. {
  254. std::deque<std::string> bests;
  255. for(std::deque<std::string>::const_iterator i = uris.begin(),
  256. eoi = uris.end(); i != eoi; ++i) {
  257. SharedHandle<ServerStat> ss = getServerStats(*i);
  258. if(ss.isNull())
  259. continue;
  260. if(ss->getSingleConnectionAvgSpeed() > min ||
  261. ss->getMultiConnectionAvgSpeed() > min) {
  262. bests.push_back(*i);
  263. }
  264. }
  265. return bests;
  266. }
  267. std::string AdaptiveURISelector::selectRandomUri
  268. (const std::deque<std::string>& uris) const
  269. {
  270. int pos = SimpleRandomizer::getInstance()->getRandomNumber(uris.size());
  271. std::deque<std::string>::const_iterator i = uris.begin();
  272. i = i+pos;
  273. return *i;
  274. }
  275. std::string AdaptiveURISelector::getFirstNotTestedUri
  276. (const std::deque<std::string>& uris) const
  277. {
  278. for(std::deque<std::string>::const_iterator i = uris.begin(),
  279. eoi = uris.end(); i != eoi; ++i) {
  280. SharedHandle<ServerStat> ss = getServerStats(*i);
  281. if(ss.isNull())
  282. return *i;
  283. }
  284. return A2STR::NIL;
  285. }
  286. std::string AdaptiveURISelector::getFirstToTestUri
  287. (const std::deque<std::string>& uris) const
  288. {
  289. unsigned int counter;
  290. int power;
  291. for(std::deque<std::string>::const_iterator i = uris.begin(),
  292. eoi = uris.end(); i != eoi; ++i) {
  293. SharedHandle<ServerStat> ss = getServerStats(*i);
  294. if(ss.isNull())
  295. continue;
  296. counter = ss->getCounter();
  297. if(counter > 8)
  298. continue;
  299. power = (int)pow(2.0, (float)counter);
  300. /* We test the mirror another time if it has not been
  301. * tested since 2^counter days */
  302. if(ss->getLastUpdated().difference() > power*24*60*60) {
  303. return *i;
  304. }
  305. }
  306. return A2STR::NIL;
  307. }
  308. SharedHandle<ServerStat> AdaptiveURISelector::getServerStats
  309. (const std::string& uri) const
  310. {
  311. Request r;
  312. r.setUri(uri);
  313. return serverStatMan_->find(r.getHost(), r.getProtocol());
  314. }
  315. unsigned int AdaptiveURISelector::getNbTestedServers
  316. (const std::deque<std::string>& uris) const
  317. {
  318. unsigned int counter = 0;
  319. for(std::deque<std::string>::const_iterator i = uris.begin(),
  320. eoi = uris.end(); i != eoi; ++i) {
  321. SharedHandle<ServerStat> ss = getServerStats(*i);
  322. if(ss.isNull())
  323. ++counter;
  324. }
  325. return uris.size() - counter;
  326. }
  327. } // namespace aria2