FileEntry.cc 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. /* <!-- copyright */
  2. /*
  3. * aria2 - The high speed download utility
  4. *
  5. * Copyright (C) 2006 Tatsuhiro Tsujikawa
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. *
  21. * In addition, as a special exception, the copyright holders give
  22. * permission to link the code of portions of this program with the
  23. * OpenSSL library under certain conditions as described in each
  24. * individual source file, and distribute linked combinations
  25. * including the two.
  26. * You must obey the GNU General Public License in all respects
  27. * for all of the code used other than OpenSSL. If you modify
  28. * file(s) with this exception, you may extend this exception to your
  29. * version of the file(s), but you are not obligated to do so. If you
  30. * do not wish to do so, delete this exception statement from your
  31. * version. If you delete this exception statement from all source
  32. * files in the program, then also delete it here.
  33. */
  34. /* copyright --> */
  35. #include "FileEntry.h"
  36. #include <cassert>
  37. #include <algorithm>
  38. #include "util.h"
  39. #include "URISelector.h"
  40. #include "LogFactory.h"
  41. namespace aria2 {
  42. FileEntry::FileEntry(const std::string& path,
  43. uint64_t length,
  44. off_t offset,
  45. const std::deque<std::string>& uris):
  46. path(path), _uris(uris), length(length), offset(offset),
  47. extracted(false), requested(true),
  48. _singleHostMultiConnection(true),
  49. _logger(LogFactory::getInstance()) {}
  50. FileEntry::FileEntry():
  51. length(0), offset(0), extracted(false), requested(false),
  52. _singleHostMultiConnection(true),
  53. _logger(LogFactory::getInstance()) {}
  54. FileEntry::~FileEntry() {}
  55. void FileEntry::setupDir()
  56. {
  57. util::mkdirs(File(path).getDirname());
  58. }
  59. FileEntry& FileEntry::operator=(const FileEntry& entry)
  60. {
  61. if(this != &entry) {
  62. path = entry.path;
  63. length = entry.length;
  64. offset = entry.offset;
  65. extracted = entry.extracted;
  66. requested = entry.requested;
  67. }
  68. return *this;
  69. }
  70. bool FileEntry::operator<(const FileEntry& fileEntry) const
  71. {
  72. return offset < fileEntry.offset;
  73. }
  74. bool FileEntry::exists() const
  75. {
  76. return File(getPath()).exists();
  77. }
  78. off_t FileEntry::gtoloff(off_t goff) const
  79. {
  80. assert(offset <= goff);
  81. return goff-offset;
  82. }
  83. void FileEntry::getUris(std::deque<std::string>& uris) const
  84. {
  85. uris.insert(uris.end(), _spentUris.begin(), _spentUris.end());
  86. uris.insert(uris.end(), _uris.begin(), _uris.end());
  87. }
  88. std::string FileEntry::selectUri(const SharedHandle<URISelector>& uriSelector)
  89. {
  90. return uriSelector->select(this);
  91. }
  92. template<typename InputIterator>
  93. static bool inFlightHost(InputIterator first, InputIterator last,
  94. const std::string& hostname)
  95. {
  96. // TODO redirection should be considered here. We need to parse
  97. // original URI to get hostname.
  98. for(; first != last; ++first) {
  99. if((*first)->getHost() == hostname) {
  100. return true;
  101. }
  102. }
  103. return false;
  104. }
  105. SharedHandle<Request>
  106. FileEntry::getRequest
  107. (const SharedHandle<URISelector>& selector,
  108. const std::string& referer,
  109. const std::string& method)
  110. {
  111. SharedHandle<Request> req;
  112. if(_requestPool.empty()) {
  113. std::deque<std::string> pending;
  114. while(1) {
  115. std::string uri = selector->select(this);
  116. if(uri.empty()) {
  117. return req;
  118. }
  119. req.reset(new Request());
  120. if(req->setUrl(uri)) {
  121. if(!_singleHostMultiConnection) {
  122. if(inFlightHost(_inFlightRequests.begin(), _inFlightRequests.end(),
  123. req->getHost())) {
  124. pending.push_back(uri);
  125. req.reset();
  126. continue;
  127. }
  128. }
  129. req->setReferer(referer);
  130. req->setMethod(method);
  131. _spentUris.push_back(uri);
  132. _inFlightRequests.push_back(req);
  133. break;
  134. } else {
  135. req.reset();
  136. }
  137. }
  138. _uris.insert(_uris.begin(), pending.begin(), pending.end());
  139. } else {
  140. req = _requestPool.front();
  141. _requestPool.pop_front();
  142. _inFlightRequests.push_back(req);
  143. }
  144. return req;
  145. }
  146. SharedHandle<Request>
  147. FileEntry::findFasterRequest(const SharedHandle<Request>& base)
  148. {
  149. if(_requestPool.empty()) {
  150. return SharedHandle<Request>();
  151. }
  152. const SharedHandle<PeerStat>& fastest = _requestPool.front()->getPeerStat();
  153. if(fastest.isNull()) {
  154. return SharedHandle<Request>();
  155. }
  156. const SharedHandle<PeerStat>& basestat = base->getPeerStat();
  157. // TODO hard coded value. See PREF_STARTUP_IDLE_TIME
  158. const int startupIdleTime = 10;
  159. if(basestat.isNull() ||
  160. (basestat->getDownloadStartTime().elapsed(startupIdleTime) &&
  161. fastest->getAvgDownloadSpeed()*0.8 > basestat->calculateDownloadSpeed())){
  162. // TODO we should consider that "fastest" is very slow.
  163. SharedHandle<Request> fastestRequest = _requestPool.front();
  164. _requestPool.pop_front();
  165. return fastestRequest;
  166. }
  167. return SharedHandle<Request>();
  168. }
  169. class RequestFaster {
  170. public:
  171. bool operator()(const SharedHandle<Request>& lhs,
  172. const SharedHandle<Request>& rhs) const
  173. {
  174. if(lhs->getPeerStat().isNull()) {
  175. return false;
  176. }
  177. if(rhs->getPeerStat().isNull()) {
  178. return true;
  179. }
  180. return
  181. lhs->getPeerStat()->getAvgDownloadSpeed() > rhs->getPeerStat()->getAvgDownloadSpeed();
  182. }
  183. };
  184. void FileEntry::storePool(const SharedHandle<Request>& request)
  185. {
  186. const SharedHandle<PeerStat>& peerStat = request->getPeerStat();
  187. if(!peerStat.isNull()) {
  188. // We need to calculate average download speed here in order to
  189. // store Request in the right position in the pool.
  190. peerStat->calculateAvgDownloadSpeed();
  191. }
  192. std::deque<SharedHandle<Request> >::iterator i =
  193. std::lower_bound(_requestPool.begin(), _requestPool.end(), request,
  194. RequestFaster());
  195. _requestPool.insert(i, request);
  196. }
  197. void FileEntry::poolRequest(const SharedHandle<Request>& request)
  198. {
  199. removeRequest(request);
  200. storePool(request);
  201. }
  202. bool FileEntry::removeRequest(const SharedHandle<Request>& request)
  203. {
  204. for(std::deque<SharedHandle<Request> >::iterator i =
  205. _inFlightRequests.begin(); i != _inFlightRequests.end(); ++i) {
  206. if((*i).get() == request.get()) {
  207. _inFlightRequests.erase(i);
  208. return true;
  209. }
  210. }
  211. return false;
  212. }
  213. void FileEntry::removeURIWhoseHostnameIs(const std::string& hostname)
  214. {
  215. std::deque<std::string> newURIs;
  216. Request req;
  217. for(std::deque<std::string>::const_iterator itr = _uris.begin(); itr != _uris.end(); ++itr) {
  218. if(((*itr).find(hostname) == std::string::npos) ||
  219. (req.setUrl(*itr) && (req.getHost() != hostname))) {
  220. newURIs.push_back(*itr);
  221. }
  222. }
  223. _logger->debug("Removed %d duplicate hostname URIs for path=%s",
  224. _uris.size()-newURIs.size(), getPath().c_str());
  225. _uris = newURIs;
  226. }
  227. void FileEntry::removeIdenticalURI(const std::string& uri)
  228. {
  229. _uris.erase(std::remove(_uris.begin(), _uris.end(), uri), _uris.end());
  230. }
  231. void FileEntry::addURIResult(std::string uri, downloadresultcode::RESULT result)
  232. {
  233. _uriResults.push_back(URIResult(uri, result));
  234. }
  235. class FindURIResultByResult {
  236. private:
  237. downloadresultcode::RESULT _r;
  238. public:
  239. FindURIResultByResult(downloadresultcode::RESULT r):_r(r) {}
  240. bool operator()(const URIResult& uriResult) const
  241. {
  242. return uriResult.getResult() == _r;
  243. }
  244. };
  245. void FileEntry::extractURIResult
  246. (std::deque<URIResult>& res, downloadresultcode::RESULT r)
  247. {
  248. std::deque<URIResult>::iterator i =
  249. std::stable_partition(_uriResults.begin(), _uriResults.end(),
  250. FindURIResultByResult(r));
  251. std::copy(_uriResults.begin(), i, std::back_inserter(res));
  252. _uriResults.erase(_uriResults.begin(), i);
  253. }
  254. void FileEntry::reuseUri(size_t num)
  255. {
  256. std::deque<std::string> uris = _spentUris;
  257. std::sort(uris.begin(), uris.end());
  258. uris.erase(std::unique(uris.begin(), uris.end()), uris.end());
  259. std::deque<std::string> errorUris(_uriResults.size());
  260. std::transform(_uriResults.begin(), _uriResults.end(),
  261. errorUris.begin(), std::mem_fun_ref(&URIResult::getURI));
  262. std::sort(errorUris.begin(), errorUris.end());
  263. errorUris.erase(std::unique(errorUris.begin(), errorUris.end()),
  264. errorUris.end());
  265. std::deque<std::string> reusableURIs;
  266. std::set_difference(uris.begin(), uris.end(),
  267. errorUris.begin(), errorUris.end(),
  268. std::back_inserter(reusableURIs));
  269. size_t ininum = reusableURIs.size();
  270. _logger->debug("Found %u reusable URIs",
  271. static_cast<unsigned int>(ininum));
  272. // Reuse at least num URIs here to avoid to
  273. // run this process repeatedly.
  274. if(ininum > 0 && ininum < num) {
  275. _logger->debug("fewer than num=%u",
  276. num);
  277. for(size_t i = 0; i < num/ininum; ++i) {
  278. _uris.insert(_uris.end(), reusableURIs.begin(), reusableURIs.end());
  279. }
  280. _uris.insert(_uris.end(), reusableURIs.begin(),
  281. reusableURIs.begin()+(num%ininum));
  282. _logger->debug("Duplication complete: now %u URIs for reuse",
  283. static_cast<unsigned int>(_uris.size()));
  284. }
  285. }
  286. void FileEntry::releaseRuntimeResource()
  287. {
  288. _requestPool.clear();
  289. _inFlightRequests.clear();
  290. _uriResults.clear();
  291. }
  292. } // namespace aria2