AdaptiveURISelector.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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 std::shared_ptr<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_fn(&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 size_t numPieces =
  114. requestGroup_->getDownloadContext()->getNumPieces();
  115. bool reservedContext = numPieces > 0 &&
  116. static_cast<size_t>(nbConnections_) > std::min
  117. (numPieces,
  118. static_cast<size_t>(requestGroup_->getNumConcurrentCommand()));
  119. bool selectBest = numPieces == 0 || reservedContext;
  120. if(numPieces > 0)
  121. ++nbConnections_;
  122. /* At least, 3 mirrors must be tested */
  123. if(getNbTestedServers(uris) < 3) {
  124. std::string notTested = getFirstNotTestedUri(uris);
  125. if(notTested != A2STR::NIL) {
  126. A2_LOG_DEBUG(fmt("AdaptiveURISelector: choosing the first non tested"
  127. " mirror: %s",
  128. notTested.c_str()));
  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. A2_LOG_DEBUG(fmt("AdaptiveURISelector: choosing non tested mirror %s"
  139. " for connection #%d",
  140. notTested.c_str(), nbConnections_));
  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. A2_LOG_DEBUG(fmt("AdaptiveURISelector: choosing mirror %s which has"
  147. " not been tested recently for connection #%d",
  148. toReTest.c_str(), nbConnections_));
  149. return toReTest;
  150. } else {
  151. return getBestMirror(uris);
  152. }
  153. }
  154. }
  155. else {
  156. return getBestMirror(uris);
  157. }
  158. }
  159. }
  160. std::string AdaptiveURISelector::getBestMirror
  161. (const std::deque<std::string>& uris) const
  162. {
  163. /* Here we return one of the bests mirrors */
  164. int max = getMaxDownloadSpeed(uris);
  165. int min = max-(int)(max*0.25);
  166. std::deque<std::string> bests = getUrisBySpeed(uris, min);
  167. if (bests.size() < 2) {
  168. std::string uri = getMaxDownloadSpeedUri(uris);
  169. A2_LOG_DEBUG(fmt("AdaptiveURISelector: choosing the best mirror :"
  170. " %.2fKB/s %s (other mirrors are at least 25%% slower)",
  171. (float) max/1024,
  172. uri.c_str()));
  173. return uri;
  174. } else {
  175. std::string uri = selectRandomUri(bests);
  176. A2_LOG_DEBUG(fmt("AdaptiveURISelector: choosing randomly one of the best"
  177. " mirrors (range [%.2fKB/s, %.2fKB/s]): %s",
  178. (float) min/1024,
  179. (float) max/1024,
  180. uri.c_str()));
  181. return uri;
  182. }
  183. }
  184. void AdaptiveURISelector::resetCounters()
  185. {
  186. nbConnections_ = 1;
  187. nbServerToEvaluate_ =
  188. requestGroup_->getOption()->getAsInt(PREF_SPLIT) - 1;
  189. }
  190. void AdaptiveURISelector::tuneDownloadCommand
  191. (const std::deque<std::string>& uris, DownloadCommand* command)
  192. {
  193. adjustLowestSpeedLimit(uris, command);
  194. }
  195. void AdaptiveURISelector::adjustLowestSpeedLimit
  196. (const std::deque<std::string>& uris, DownloadCommand* command) const
  197. {
  198. int lowest =
  199. requestGroup_->getOption()->getAsInt(PREF_LOWEST_SPEED_LIMIT);
  200. if (lowest > 0) {
  201. int low_lowest = 4 * 1024;
  202. int max = getMaxDownloadSpeed(uris);
  203. if (max > 0 && lowest > max / 4) {
  204. A2_LOG_NOTICE(fmt(_("Lowering lowest-speed-limit since known max speed is"
  205. " too near (new:%d was:%d max:%d)"),
  206. max / 4,
  207. lowest,
  208. max));
  209. command->setLowestDownloadSpeedLimit(max / 4);
  210. } else if (max == 0 && lowest > low_lowest) {
  211. A2_LOG_NOTICE(fmt(_("Lowering lowest-speed-limit since we have no clue"
  212. " about available speed (now:%d was:%d)"),
  213. low_lowest,
  214. lowest));
  215. command->setLowestDownloadSpeedLimit(low_lowest);
  216. }
  217. }
  218. }
  219. namespace {
  220. int getUriMaxSpeed(std::shared_ptr<ServerStat> ss)
  221. {
  222. return std::max(ss->getSingleConnectionAvgSpeed(),
  223. ss->getMultiConnectionAvgSpeed());
  224. }
  225. } // namespace
  226. 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(auto& u : uris) {
  240. std::shared_ptr<ServerStat> ss = getServerStats(u);
  241. if(!ss)
  242. continue;
  243. if((int)ss->getSingleConnectionAvgSpeed() > max) {
  244. max = ss->getSingleConnectionAvgSpeed();
  245. uri = u;
  246. }
  247. if((int)ss->getMultiConnectionAvgSpeed() > max) {
  248. max = ss->getMultiConnectionAvgSpeed();
  249. uri = u;
  250. }
  251. }
  252. return uri;
  253. }
  254. std::deque<std::string> AdaptiveURISelector::getUrisBySpeed
  255. (const std::deque<std::string>& uris, int min) const
  256. {
  257. std::deque<std::string> bests;
  258. for(auto& uri : uris) {
  259. std::shared_ptr<ServerStat> ss = getServerStats(uri);
  260. if(!ss)
  261. continue;
  262. if(ss->getSingleConnectionAvgSpeed() > min ||
  263. ss->getMultiConnectionAvgSpeed() > min) {
  264. bests.push_back(uri);
  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. auto 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 (const auto& i : uris) {
  281. std::shared_ptr<ServerStat> ss = getServerStats(i);
  282. if(!ss)
  283. return i;
  284. }
  285. return A2STR::NIL;
  286. }
  287. std::string AdaptiveURISelector::getFirstToTestUri
  288. (const std::deque<std::string>& uris) const
  289. {
  290. int counter;
  291. int power;
  292. for (const auto& u : uris) {
  293. std::shared_ptr<ServerStat> ss = getServerStats(u);
  294. if(!ss)
  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 u;
  304. }
  305. }
  306. return A2STR::NIL;
  307. }
  308. std::shared_ptr<ServerStat> AdaptiveURISelector::getServerStats
  309. (const std::string& uri) const
  310. {
  311. uri_split_result us;
  312. if(uri_split(&us, uri.c_str()) == 0) {
  313. std::string host = uri::getFieldString(us, USR_HOST, uri.c_str());
  314. std::string protocol = uri::getFieldString(us, USR_SCHEME, uri.c_str());
  315. return serverStatMan_->find(host, protocol);
  316. } else {
  317. return nullptr;
  318. }
  319. }
  320. int AdaptiveURISelector::getNbTestedServers
  321. (const std::deque<std::string>& uris) const
  322. {
  323. int counter = 0;
  324. for(const auto& u : uris) {
  325. std::shared_ptr<ServerStat> ss = getServerStats(u);
  326. if(!ss)
  327. ++counter;
  328. }
  329. return uris.size() - counter;
  330. }
  331. } // namespace aria2