AdaptiveURISelector.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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. (std::shared_ptr<ServerStatMan> serverStatMan, RequestGroup* requestGroup)
  65. : serverStatMan_(std::move(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(std::begin(uris), std::end(uris), selected));
  86. }
  87. return selected;
  88. }
  89. namespace {
  90. constexpr auto MAX_TIMEOUT = 60_s;
  91. } // namespace
  92. void AdaptiveURISelector::mayRetryWithIncreasedTimeout(FileEntry* fileEntry)
  93. {
  94. if (requestGroup_->getTimeout()*2 >= MAX_TIMEOUT) return;
  95. requestGroup_->setTimeout(requestGroup_->getTimeout()*2);
  96. std::deque<std::string>& uris = fileEntry->getRemainingUris();
  97. // looking for retries
  98. std::deque<URIResult> timeouts;
  99. fileEntry->extractURIResult(timeouts, error_code::TIME_OUT);
  100. std::transform(std::begin(timeouts), std::end(timeouts),
  101. std::back_inserter(uris), std::mem_fn(&URIResult::getURI));
  102. if(A2_LOG_DEBUG_ENABLED) {
  103. for (const auto& uri : uris) {
  104. A2_LOG_DEBUG(
  105. fmt("AdaptiveURISelector: will retry server with increased"
  106. " timeout (%ld s): %s",
  107. static_cast<long int>(requestGroup_->getTimeout().count()),
  108. uri.c_str()));
  109. }
  110. }
  111. }
  112. std::string AdaptiveURISelector::selectOne(const std::deque<std::string>& uris)
  113. {
  114. if(uris.empty()) {
  115. return A2STR::NIL;
  116. } else {
  117. const size_t numPieces =
  118. requestGroup_->getDownloadContext()->getNumPieces();
  119. bool reservedContext = numPieces > 0 &&
  120. static_cast<size_t>(nbConnections_) > std::min
  121. (numPieces,
  122. static_cast<size_t>(requestGroup_->getNumConcurrentCommand()));
  123. bool selectBest = numPieces == 0 || reservedContext;
  124. if(numPieces > 0)
  125. ++nbConnections_;
  126. /* At least, 3 mirrors must be tested */
  127. if(getNbTestedServers(uris) < 3) {
  128. std::string notTested = getFirstNotTestedUri(uris);
  129. if(notTested != A2STR::NIL) {
  130. A2_LOG_DEBUG(fmt("AdaptiveURISelector: choosing the first non tested"
  131. " mirror: %s",
  132. notTested.c_str()));
  133. --nbServerToEvaluate_;
  134. return notTested;
  135. }
  136. }
  137. if(!selectBest && nbConnections_ > 1 && nbServerToEvaluate_ > 0) {
  138. nbServerToEvaluate_--;
  139. std::string notTested = getFirstNotTestedUri(uris);
  140. if(notTested != A2STR::NIL) {
  141. /* Here we return the first untested mirror */
  142. A2_LOG_DEBUG(fmt("AdaptiveURISelector: choosing non tested mirror %s"
  143. " for connection #%d",
  144. notTested.c_str(), nbConnections_));
  145. return notTested;
  146. } else {
  147. /* Here we return a mirror which need to be tested again */
  148. std::string toReTest = getFirstToTestUri(uris);
  149. if(toReTest != A2STR::NIL) {
  150. A2_LOG_DEBUG(fmt("AdaptiveURISelector: choosing mirror %s which has"
  151. " not been tested recently for connection #%d",
  152. toReTest.c_str(), nbConnections_));
  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. int max = getMaxDownloadSpeed(uris);
  169. 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. A2_LOG_DEBUG(fmt("AdaptiveURISelector: choosing the best mirror :"
  174. " %.2fKB/s %s (other mirrors are at least 25%% slower)",
  175. (float) max/1024,
  176. uri.c_str()));
  177. return uri;
  178. } else {
  179. std::string uri = selectRandomUri(bests);
  180. A2_LOG_DEBUG(fmt("AdaptiveURISelector: choosing randomly one of the best"
  181. " mirrors (range [%.2fKB/s, %.2fKB/s]): %s",
  182. (float) min/1024,
  183. (float) max/1024,
  184. uri.c_str()));
  185. return uri;
  186. }
  187. }
  188. void AdaptiveURISelector::resetCounters()
  189. {
  190. nbConnections_ = 1;
  191. nbServerToEvaluate_ =
  192. requestGroup_->getOption()->getAsInt(PREF_SPLIT) - 1;
  193. }
  194. void AdaptiveURISelector::tuneDownloadCommand
  195. (const std::deque<std::string>& uris, DownloadCommand* command)
  196. {
  197. adjustLowestSpeedLimit(uris, command);
  198. }
  199. void AdaptiveURISelector::adjustLowestSpeedLimit
  200. (const std::deque<std::string>& uris, DownloadCommand* command) const
  201. {
  202. int lowest =
  203. requestGroup_->getOption()->getAsInt(PREF_LOWEST_SPEED_LIMIT);
  204. if (lowest > 0) {
  205. int low_lowest = 4_k;
  206. int max = getMaxDownloadSpeed(uris);
  207. if (max > 0 && lowest > max / 4) {
  208. A2_LOG_NOTICE(fmt(_("Lowering lowest-speed-limit since known max speed is"
  209. " too near (new:%d was:%d max:%d)"),
  210. max / 4,
  211. lowest,
  212. max));
  213. command->setLowestDownloadSpeedLimit(max / 4);
  214. } else if (max == 0 && lowest > low_lowest) {
  215. A2_LOG_NOTICE(fmt(_("Lowering lowest-speed-limit since we have no clue"
  216. " about available speed (now:%d was:%d)"),
  217. low_lowest,
  218. lowest));
  219. command->setLowestDownloadSpeedLimit(low_lowest);
  220. }
  221. }
  222. }
  223. namespace {
  224. int getUriMaxSpeed(std::shared_ptr<ServerStat> ss)
  225. {
  226. return std::max(ss->getSingleConnectionAvgSpeed(),
  227. ss->getMultiConnectionAvgSpeed());
  228. }
  229. } // namespace
  230. int AdaptiveURISelector::getMaxDownloadSpeed
  231. (const std::deque<std::string>& uris) const
  232. {
  233. std::string uri = getMaxDownloadSpeedUri(uris);
  234. if(uri == A2STR::NIL)
  235. return 0;
  236. return getUriMaxSpeed(getServerStats(uri));
  237. }
  238. std::string AdaptiveURISelector::getMaxDownloadSpeedUri
  239. (const std::deque<std::string>& uris) const
  240. {
  241. int max = -1;
  242. std::string uri = A2STR::NIL;
  243. for(auto& u : uris) {
  244. std::shared_ptr<ServerStat> ss = getServerStats(u);
  245. if(!ss)
  246. continue;
  247. if((int)ss->getSingleConnectionAvgSpeed() > max) {
  248. max = ss->getSingleConnectionAvgSpeed();
  249. uri = u;
  250. }
  251. if((int)ss->getMultiConnectionAvgSpeed() > max) {
  252. max = ss->getMultiConnectionAvgSpeed();
  253. uri = u;
  254. }
  255. }
  256. return uri;
  257. }
  258. std::deque<std::string> AdaptiveURISelector::getUrisBySpeed
  259. (const std::deque<std::string>& uris, int min) const
  260. {
  261. std::deque<std::string> bests;
  262. for(auto& uri : uris) {
  263. std::shared_ptr<ServerStat> ss = getServerStats(uri);
  264. if(!ss)
  265. continue;
  266. if(ss->getSingleConnectionAvgSpeed() > min ||
  267. ss->getMultiConnectionAvgSpeed() > min) {
  268. bests.push_back(uri);
  269. }
  270. }
  271. return bests;
  272. }
  273. std::string AdaptiveURISelector::selectRandomUri
  274. (const std::deque<std::string>& uris) const
  275. {
  276. int pos = SimpleRandomizer::getInstance()->getRandomNumber(uris.size());
  277. auto i = std::begin(uris);
  278. i = i+pos;
  279. return *i;
  280. }
  281. std::string AdaptiveURISelector::getFirstNotTestedUri
  282. (const std::deque<std::string>& uris) const
  283. {
  284. for (const auto& i : uris) {
  285. std::shared_ptr<ServerStat> ss = getServerStats(i);
  286. if(!ss)
  287. return i;
  288. }
  289. return A2STR::NIL;
  290. }
  291. std::string AdaptiveURISelector::getFirstToTestUri
  292. (const std::deque<std::string>& uris) const
  293. {
  294. int counter;
  295. int power;
  296. for (const auto& u : uris) {
  297. std::shared_ptr<ServerStat> ss = getServerStats(u);
  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() > std::chrono::hours(power * 24)) {
  307. return u;
  308. }
  309. }
  310. return A2STR::NIL;
  311. }
  312. std::shared_ptr<ServerStat> AdaptiveURISelector::getServerStats
  313. (const std::string& uri) const
  314. {
  315. uri_split_result us;
  316. if(uri_split(&us, uri.c_str()) == 0) {
  317. std::string host = uri::getFieldString(us, USR_HOST, uri.c_str());
  318. std::string protocol = uri::getFieldString(us, USR_SCHEME, uri.c_str());
  319. return serverStatMan_->find(host, protocol);
  320. } else {
  321. return nullptr;
  322. }
  323. }
  324. int AdaptiveURISelector::getNbTestedServers
  325. (const std::deque<std::string>& uris) const
  326. {
  327. int counter = 0;
  328. for(const auto& u : uris) {
  329. std::shared_ptr<ServerStat> ss = getServerStats(u);
  330. if(!ss)
  331. ++counter;
  332. }
  333. return uris.size() - counter;
  334. }
  335. } // namespace aria2