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)), 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(
  75. fmt("AdaptiveURISelector: called %d", 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(std::begin(uris), std::end(uris), selected));
  85. }
  86. return selected;
  87. }
  88. namespace {
  89. constexpr auto MAX_TIMEOUT = 60_s;
  90. } // namespace
  91. void AdaptiveURISelector::mayRetryWithIncreasedTimeout(FileEntry* fileEntry)
  92. {
  93. if (requestGroup_->getTimeout() * 2 >= MAX_TIMEOUT)
  94. 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. }
  117. else {
  118. const size_t numPieces =
  119. requestGroup_->getDownloadContext()->getNumPieces();
  120. bool reservedContext =
  121. numPieces > 0 &&
  122. static_cast<size_t>(nbConnections_) >
  123. std::min(numPieces, static_cast<size_t>(
  124. requestGroup_->getNumConcurrentCommand()));
  125. bool selectBest = numPieces == 0 || reservedContext;
  126. if (numPieces > 0)
  127. ++nbConnections_;
  128. /* At least, 3 mirrors must be tested */
  129. if (getNbTestedServers(uris) < 3) {
  130. std::string notTested = getFirstNotTestedUri(uris);
  131. if (notTested != A2STR::NIL) {
  132. A2_LOG_DEBUG(fmt("AdaptiveURISelector: choosing the first non tested"
  133. " mirror: %s",
  134. notTested.c_str()));
  135. --nbServerToEvaluate_;
  136. return notTested;
  137. }
  138. }
  139. if (!selectBest && nbConnections_ > 1 && nbServerToEvaluate_ > 0) {
  140. nbServerToEvaluate_--;
  141. std::string notTested = getFirstNotTestedUri(uris);
  142. if (notTested != A2STR::NIL) {
  143. /* Here we return the first untested mirror */
  144. A2_LOG_DEBUG(fmt("AdaptiveURISelector: choosing non tested mirror %s"
  145. " for connection #%d",
  146. notTested.c_str(), nbConnections_));
  147. return notTested;
  148. }
  149. else {
  150. /* Here we return a mirror which need to be tested again */
  151. std::string toReTest = getFirstToTestUri(uris);
  152. if (toReTest != A2STR::NIL) {
  153. A2_LOG_DEBUG(fmt("AdaptiveURISelector: choosing mirror %s which has"
  154. " not been tested recently for connection #%d",
  155. toReTest.c_str(), nbConnections_));
  156. return toReTest;
  157. }
  158. else {
  159. return getBestMirror(uris);
  160. }
  161. }
  162. }
  163. else {
  164. return getBestMirror(uris);
  165. }
  166. }
  167. }
  168. std::string
  169. AdaptiveURISelector::getBestMirror(const std::deque<std::string>& uris) const
  170. {
  171. /* Here we return one of the bests mirrors */
  172. int max = getMaxDownloadSpeed(uris);
  173. int min = max - (int)(max * 0.25);
  174. std::deque<std::string> bests = getUrisBySpeed(uris, min);
  175. if (bests.size() < 2) {
  176. std::string uri = getMaxDownloadSpeedUri(uris);
  177. A2_LOG_DEBUG(fmt("AdaptiveURISelector: choosing the best mirror :"
  178. " %.2fKB/s %s (other mirrors are at least 25%% slower)",
  179. (float)max / 1024, uri.c_str()));
  180. return uri;
  181. }
  182. else {
  183. std::string uri = selectRandomUri(bests);
  184. A2_LOG_DEBUG(fmt("AdaptiveURISelector: choosing randomly one of the best"
  185. " mirrors (range [%.2fKB/s, %.2fKB/s]): %s",
  186. (float)min / 1024, (float)max / 1024, uri.c_str()));
  187. return uri;
  188. }
  189. }
  190. void AdaptiveURISelector::resetCounters()
  191. {
  192. nbConnections_ = 1;
  193. nbServerToEvaluate_ = requestGroup_->getOption()->getAsInt(PREF_SPLIT) - 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. int lowest = 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, lowest, max));
  211. command->setLowestDownloadSpeedLimit(max / 4);
  212. }
  213. else if (max == 0 && lowest > low_lowest) {
  214. A2_LOG_NOTICE(fmt(_("Lowering lowest-speed-limit since we have no clue"
  215. " about available speed (now:%d was:%d)"),
  216. low_lowest, lowest));
  217. command->setLowestDownloadSpeedLimit(low_lowest);
  218. }
  219. }
  220. }
  221. namespace {
  222. int getUriMaxSpeed(std::shared_ptr<ServerStat> ss)
  223. {
  224. return std::max(ss->getSingleConnectionAvgSpeed(),
  225. ss->getMultiConnectionAvgSpeed());
  226. }
  227. } // namespace
  228. int AdaptiveURISelector::getMaxDownloadSpeed(
  229. const std::deque<std::string>& uris) const
  230. {
  231. std::string uri = getMaxDownloadSpeedUri(uris);
  232. if (uri == A2STR::NIL)
  233. return 0;
  234. return getUriMaxSpeed(getServerStats(uri));
  235. }
  236. std::string AdaptiveURISelector::getMaxDownloadSpeedUri(
  237. const std::deque<std::string>& uris) const
  238. {
  239. int max = -1;
  240. std::string uri = A2STR::NIL;
  241. for (auto& u : uris) {
  242. std::shared_ptr<ServerStat> ss = getServerStats(u);
  243. if (!ss)
  244. continue;
  245. if ((int)ss->getSingleConnectionAvgSpeed() > max) {
  246. max = ss->getSingleConnectionAvgSpeed();
  247. uri = u;
  248. }
  249. if ((int)ss->getMultiConnectionAvgSpeed() > max) {
  250. max = ss->getMultiConnectionAvgSpeed();
  251. uri = u;
  252. }
  253. }
  254. return uri;
  255. }
  256. std::deque<std::string>
  257. AdaptiveURISelector::getUrisBySpeed(const std::deque<std::string>& uris,
  258. int min) const
  259. {
  260. std::deque<std::string> bests;
  261. for (auto& uri : uris) {
  262. std::shared_ptr<ServerStat> ss = getServerStats(uri);
  263. if (!ss)
  264. continue;
  265. if (ss->getSingleConnectionAvgSpeed() > min ||
  266. ss->getMultiConnectionAvgSpeed() > min) {
  267. bests.push_back(uri);
  268. }
  269. }
  270. return bests;
  271. }
  272. std::string
  273. AdaptiveURISelector::selectRandomUri(const std::deque<std::string>& uris) const
  274. {
  275. int pos = SimpleRandomizer::getInstance()->getRandomNumber(uris.size());
  276. auto i = std::begin(uris);
  277. i = i + pos;
  278. return *i;
  279. }
  280. std::string AdaptiveURISelector::getFirstNotTestedUri(
  281. const std::deque<std::string>& uris) const
  282. {
  283. for (const auto& i : uris) {
  284. std::shared_ptr<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. int counter;
  294. int power;
  295. for (const auto& u : uris) {
  296. std::shared_ptr<ServerStat> ss = getServerStats(u);
  297. if (!ss)
  298. continue;
  299. counter = ss->getCounter();
  300. if (counter > 8)
  301. continue;
  302. power = (int)pow(2.0, (float)counter);
  303. /* We test the mirror another time if it has not been
  304. * tested since 2^counter days */
  305. if (ss->getLastUpdated().difference() > std::chrono::hours(power * 24)) {
  306. return u;
  307. }
  308. }
  309. return A2STR::NIL;
  310. }
  311. std::shared_ptr<ServerStat>
  312. AdaptiveURISelector::getServerStats(const std::string& uri) const
  313. {
  314. uri_split_result us;
  315. if (uri_split(&us, uri.c_str()) == 0) {
  316. std::string host = uri::getFieldString(us, USR_HOST, uri.c_str());
  317. std::string protocol = uri::getFieldString(us, USR_SCHEME, uri.c_str());
  318. return serverStatMan_->find(host, protocol);
  319. }
  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