FileEntry.cc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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. #include "wallclock.h"
  42. #include "a2algo.h"
  43. namespace aria2 {
  44. FileEntry::FileEntry(const std::string& path,
  45. uint64_t length,
  46. off_t offset,
  47. const std::vector<std::string>& uris):
  48. path_(path), uris_(uris.begin(), uris.end()), length_(length),
  49. offset_(offset),
  50. requested_(true),
  51. uniqueProtocol_(false),
  52. maxConnectionPerServer_(1),
  53. lastFasterReplace_(0),
  54. logger_(LogFactory::getInstance()) {}
  55. FileEntry::FileEntry():
  56. length_(0), offset_(0), requested_(false),
  57. uniqueProtocol_(false),
  58. maxConnectionPerServer_(1),
  59. logger_(LogFactory::getInstance()) {}
  60. FileEntry::~FileEntry() {}
  61. void FileEntry::setupDir()
  62. {
  63. util::mkdirs(File(path_).getDirname());
  64. }
  65. FileEntry& FileEntry::operator=(const FileEntry& entry)
  66. {
  67. if(this != &entry) {
  68. path_ = entry.path_;
  69. length_ = entry.length_;
  70. offset_ = entry.offset_;
  71. requested_ = entry.requested_;
  72. }
  73. return *this;
  74. }
  75. bool FileEntry::operator<(const FileEntry& fileEntry) const
  76. {
  77. return offset_ < fileEntry.offset_;
  78. }
  79. bool FileEntry::exists() const
  80. {
  81. return File(getPath()).exists();
  82. }
  83. off_t FileEntry::gtoloff(off_t goff) const
  84. {
  85. assert(offset_ <= goff);
  86. return goff-offset_;
  87. }
  88. void FileEntry::getUris(std::vector<std::string>& uris) const
  89. {
  90. uris.insert(uris.end(), spentUris_.begin(), spentUris_.end());
  91. uris.insert(uris.end(), uris_.begin(), uris_.end());
  92. }
  93. template<typename InputIterator, typename OutputIterator>
  94. static OutputIterator
  95. enumerateInFlightHosts
  96. (InputIterator first, InputIterator last, OutputIterator out)
  97. {
  98. Request r;
  99. for(; first != last; ++first) {
  100. r.setUri((*first)->getUri());
  101. *out++ = r.getHost();
  102. }
  103. return out;
  104. }
  105. SharedHandle<Request>
  106. FileEntry::getRequest
  107. (const SharedHandle<URISelector>& selector,
  108. bool uriReuse,
  109. const std::vector<std::pair<size_t, std::string> >& usedHosts,
  110. const std::string& referer,
  111. const std::string& method)
  112. {
  113. SharedHandle<Request> req;
  114. if(requestPool_.empty()) {
  115. std::vector<std::string> inFlightHosts;
  116. enumerateInFlightHosts(inFlightRequests_.begin(), inFlightRequests_.end(),
  117. std::back_inserter(inFlightHosts));
  118. for(int g = 0; g < 2; ++g) {
  119. std::vector<std::string> pending;
  120. std::vector<std::string> ignoreHost;
  121. while(1) {
  122. std::string uri = selector->select(this, usedHosts);
  123. if(uri.empty()) {
  124. break;
  125. }
  126. req.reset(new Request());
  127. if(req->setUri(uri)) {
  128. if(std::count(inFlightHosts.begin(),
  129. inFlightHosts.end(),req->getHost())
  130. >= static_cast<int>(maxConnectionPerServer_)) {
  131. pending.push_back(uri);
  132. ignoreHost.push_back(req->getHost());
  133. req.reset();
  134. continue;
  135. }
  136. req->setReferer(referer);
  137. req->setMethod(method);
  138. spentUris_.push_back(uri);
  139. inFlightRequests_.push_back(req);
  140. break;
  141. } else {
  142. req.reset();
  143. }
  144. }
  145. uris_.insert(uris_.begin(), pending.begin(), pending.end());
  146. if(g == 0 && uriReuse && req.isNull() && uris_.size() == pending.size()) {
  147. // Reuse URIs other than ones in pending
  148. reuseUri(ignoreHost);
  149. } else {
  150. break;
  151. }
  152. }
  153. } else {
  154. req = requestPool_.front();
  155. requestPool_.pop_front();
  156. inFlightRequests_.push_back(req);
  157. if(logger_->debug()) {
  158. logger_->debug("Picked up from pool: %s", req->getUri().c_str());
  159. }
  160. }
  161. return req;
  162. }
  163. SharedHandle<Request>
  164. FileEntry::findFasterRequest(const SharedHandle<Request>& base)
  165. {
  166. const int startupIdleTime = 10;
  167. if(requestPool_.empty() ||
  168. lastFasterReplace_.difference(global::wallclock) < startupIdleTime) {
  169. return SharedHandle<Request>();
  170. }
  171. const SharedHandle<PeerStat>& fastest = requestPool_.front()->getPeerStat();
  172. if(fastest.isNull()) {
  173. return SharedHandle<Request>();
  174. }
  175. const SharedHandle<PeerStat>& basestat = base->getPeerStat();
  176. // TODO hard coded value. See PREF_STARTUP_IDLE_TIME
  177. if(basestat.isNull() ||
  178. (basestat->getDownloadStartTime().
  179. difference(global::wallclock) >= startupIdleTime &&
  180. fastest->getAvgDownloadSpeed()*0.8 > basestat->calculateDownloadSpeed())){
  181. // TODO we should consider that "fastest" is very slow.
  182. SharedHandle<Request> fastestRequest = requestPool_.front();
  183. requestPool_.pop_front();
  184. inFlightRequests_.push_back(fastestRequest);
  185. lastFasterReplace_.reset();
  186. return fastestRequest;
  187. }
  188. return SharedHandle<Request>();
  189. }
  190. class RequestFaster {
  191. public:
  192. bool operator()(const SharedHandle<Request>& lhs,
  193. const SharedHandle<Request>& rhs) const
  194. {
  195. if(lhs->getPeerStat().isNull()) {
  196. return false;
  197. }
  198. if(rhs->getPeerStat().isNull()) {
  199. return true;
  200. }
  201. return
  202. lhs->getPeerStat()->getAvgDownloadSpeed() > rhs->getPeerStat()->getAvgDownloadSpeed();
  203. }
  204. };
  205. void FileEntry::storePool(const SharedHandle<Request>& request)
  206. {
  207. const SharedHandle<PeerStat>& peerStat = request->getPeerStat();
  208. if(!peerStat.isNull()) {
  209. // We need to calculate average download speed here in order to
  210. // store Request in the right position in the pool.
  211. peerStat->calculateAvgDownloadSpeed();
  212. }
  213. std::deque<SharedHandle<Request> >::iterator i =
  214. std::lower_bound(requestPool_.begin(), requestPool_.end(), request,
  215. RequestFaster());
  216. requestPool_.insert(i, request);
  217. }
  218. void FileEntry::poolRequest(const SharedHandle<Request>& request)
  219. {
  220. removeRequest(request);
  221. if(!request->removalRequested()) {
  222. storePool(request);
  223. }
  224. }
  225. bool FileEntry::removeRequest(const SharedHandle<Request>& request)
  226. {
  227. for(std::deque<SharedHandle<Request> >::iterator i =
  228. inFlightRequests_.begin(), eoi = inFlightRequests_.end();
  229. i != eoi; ++i) {
  230. if((*i).get() == request.get()) {
  231. inFlightRequests_.erase(i);
  232. return true;
  233. }
  234. }
  235. return false;
  236. }
  237. void FileEntry::removeURIWhoseHostnameIs(const std::string& hostname)
  238. {
  239. std::deque<std::string> newURIs;
  240. Request req;
  241. for(std::deque<std::string>::const_iterator itr = uris_.begin(),
  242. eoi = uris_.end(); itr != eoi; ++itr) {
  243. if(((*itr).find(hostname) == std::string::npos) ||
  244. (req.setUri(*itr) && (req.getHost() != hostname))) {
  245. newURIs.push_back(*itr);
  246. }
  247. }
  248. if(logger_->debug()) {
  249. logger_->debug("Removed %d duplicate hostname URIs for path=%s",
  250. uris_.size()-newURIs.size(), getPath().c_str());
  251. }
  252. uris_ = newURIs;
  253. }
  254. void FileEntry::removeIdenticalURI(const std::string& uri)
  255. {
  256. uris_.erase(std::remove(uris_.begin(), uris_.end(), uri), uris_.end());
  257. }
  258. void FileEntry::addURIResult(std::string uri, downloadresultcode::RESULT result)
  259. {
  260. uriResults_.push_back(URIResult(uri, result));
  261. }
  262. class FindURIResultByResult {
  263. private:
  264. downloadresultcode::RESULT r_;
  265. public:
  266. FindURIResultByResult(downloadresultcode::RESULT r):r_(r) {}
  267. bool operator()(const URIResult& uriResult) const
  268. {
  269. return uriResult.getResult() == r_;
  270. }
  271. };
  272. void FileEntry::extractURIResult
  273. (std::deque<URIResult>& res, downloadresultcode::RESULT r)
  274. {
  275. std::deque<URIResult>::iterator i =
  276. std::stable_partition(uriResults_.begin(), uriResults_.end(),
  277. FindURIResultByResult(r));
  278. std::copy(uriResults_.begin(), i, std::back_inserter(res));
  279. uriResults_.erase(uriResults_.begin(), i);
  280. }
  281. void FileEntry::reuseUri(const std::vector<std::string>& ignore)
  282. {
  283. if(logger_->debug()) {
  284. for(std::vector<std::string>::const_iterator i = ignore.begin(),
  285. eoi = ignore.end(); i != eoi; ++i) {
  286. logger_->debug("ignore host=%s", (*i).c_str());
  287. }
  288. }
  289. std::deque<std::string> uris = spentUris_;
  290. std::sort(uris.begin(), uris.end());
  291. uris.erase(std::unique(uris.begin(), uris.end()), uris.end());
  292. std::vector<std::string> errorUris(uriResults_.size());
  293. std::transform(uriResults_.begin(), uriResults_.end(),
  294. errorUris.begin(), std::mem_fun_ref(&URIResult::getURI));
  295. std::sort(errorUris.begin(), errorUris.end());
  296. errorUris.erase(std::unique(errorUris.begin(), errorUris.end()),
  297. errorUris.end());
  298. if(logger_->debug()) {
  299. for(std::vector<std::string>::const_iterator i = errorUris.begin(),
  300. eoi = errorUris.end(); i != eoi; ++i) {
  301. logger_->debug("error URI=%s", (*i).c_str());
  302. }
  303. }
  304. std::vector<std::string> reusableURIs;
  305. std::set_difference(uris.begin(), uris.end(),
  306. errorUris.begin(), errorUris.end(),
  307. std::back_inserter(reusableURIs));
  308. std::vector<std::string>::iterator insertionPoint = reusableURIs.begin();
  309. Request req;
  310. for(std::vector<std::string>::iterator i = reusableURIs.begin(),
  311. eoi = reusableURIs.end(); i != eoi; ++i) {
  312. req.setUri(*i);
  313. if(std::find(ignore.begin(), ignore.end(), req.getHost()) == ignore.end()) {
  314. if(i != insertionPoint) {
  315. *insertionPoint = *i;
  316. }
  317. ++insertionPoint;
  318. }
  319. }
  320. reusableURIs.erase(insertionPoint, reusableURIs.end());
  321. size_t ininum = reusableURIs.size();
  322. if(logger_->debug()) {
  323. logger_->debug("Found %u reusable URIs", static_cast<unsigned int>(ininum));
  324. for(std::vector<std::string>::const_iterator i = reusableURIs.begin(),
  325. eoi = reusableURIs.end(); i != eoi; ++i) {
  326. logger_->debug("URI=%s", (*i).c_str());
  327. }
  328. }
  329. uris_.insert(uris_.end(), reusableURIs.begin(), reusableURIs.end());
  330. }
  331. void FileEntry::releaseRuntimeResource()
  332. {
  333. requestPool_.clear();
  334. inFlightRequests_.clear();
  335. }
  336. template<typename InputIterator, typename T>
  337. static InputIterator findRequestByUri
  338. (InputIterator first, InputIterator last, const T& uri)
  339. {
  340. for(; first != last; ++first) {
  341. if(!(*first)->removalRequested() && (*first)->getUri() == uri) {
  342. return first;
  343. }
  344. }
  345. return last;
  346. }
  347. bool FileEntry::removeUri(const std::string& uri)
  348. {
  349. std::deque<std::string>::iterator itr =
  350. std::find(spentUris_.begin(), spentUris_.end(), uri);
  351. if(itr == spentUris_.end()) {
  352. itr = std::find(uris_.begin(), uris_.end(), uri);
  353. if(itr == uris_.end()) {
  354. return false;
  355. } else {
  356. uris_.erase(itr);
  357. return true;
  358. }
  359. } else {
  360. spentUris_.erase(itr);
  361. SharedHandle<Request> req;
  362. std::deque<SharedHandle<Request> >::iterator riter =
  363. findRequestByUri(inFlightRequests_.begin(), inFlightRequests_.end(), uri);
  364. if(riter == inFlightRequests_.end()) {
  365. riter = findRequestByUri(requestPool_.begin(), requestPool_.end(), uri);
  366. if(riter == requestPool_.end()) {
  367. return true;
  368. } else {
  369. req = *riter;
  370. requestPool_.erase(riter);
  371. }
  372. } else {
  373. req = *riter;
  374. }
  375. req->requestRemoval();
  376. return true;
  377. }
  378. }
  379. std::string FileEntry::getBasename() const
  380. {
  381. return File(path_).getBasename();
  382. }
  383. std::string FileEntry::getDirname() const
  384. {
  385. return File(path_).getDirname();
  386. }
  387. size_t FileEntry::setUris(const std::vector<std::string>& uris)
  388. {
  389. uris_.clear();
  390. return addUris(uris.begin(), uris.end());
  391. }
  392. bool FileEntry::addUri(const std::string& uri)
  393. {
  394. if(Request().setUri(uri)) {
  395. uris_.push_back(uri);
  396. return true;
  397. } else {
  398. return false;
  399. }
  400. }
  401. bool FileEntry::insertUri(const std::string& uri, size_t pos)
  402. {
  403. if(Request().setUri(uri)) {
  404. pos = std::min(pos, uris_.size());
  405. uris_.insert(uris_.begin()+pos, uri);
  406. return true;
  407. } else {
  408. return false;
  409. }
  410. }
  411. } // namespace aria2