FileEntry.cc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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. namespace {
  191. class RequestFaster {
  192. public:
  193. bool operator()(const SharedHandle<Request>& lhs,
  194. const SharedHandle<Request>& rhs) const
  195. {
  196. if(lhs->getPeerStat().isNull()) {
  197. return false;
  198. }
  199. if(rhs->getPeerStat().isNull()) {
  200. return true;
  201. }
  202. return
  203. lhs->getPeerStat()->getAvgDownloadSpeed() > rhs->getPeerStat()->getAvgDownloadSpeed();
  204. }
  205. };
  206. }
  207. void FileEntry::storePool(const SharedHandle<Request>& request)
  208. {
  209. const SharedHandle<PeerStat>& peerStat = request->getPeerStat();
  210. if(!peerStat.isNull()) {
  211. // We need to calculate average download speed here in order to
  212. // store Request in the right position in the pool.
  213. peerStat->calculateAvgDownloadSpeed();
  214. }
  215. std::deque<SharedHandle<Request> >::iterator i =
  216. std::lower_bound(requestPool_.begin(), requestPool_.end(), request,
  217. RequestFaster());
  218. requestPool_.insert(i, request);
  219. }
  220. void FileEntry::poolRequest(const SharedHandle<Request>& request)
  221. {
  222. removeRequest(request);
  223. if(!request->removalRequested()) {
  224. storePool(request);
  225. }
  226. }
  227. bool FileEntry::removeRequest(const SharedHandle<Request>& request)
  228. {
  229. for(std::deque<SharedHandle<Request> >::iterator i =
  230. inFlightRequests_.begin(), eoi = inFlightRequests_.end();
  231. i != eoi; ++i) {
  232. if((*i).get() == request.get()) {
  233. inFlightRequests_.erase(i);
  234. return true;
  235. }
  236. }
  237. return false;
  238. }
  239. void FileEntry::removeURIWhoseHostnameIs(const std::string& hostname)
  240. {
  241. std::deque<std::string> newURIs;
  242. Request req;
  243. for(std::deque<std::string>::const_iterator itr = uris_.begin(),
  244. eoi = uris_.end(); itr != eoi; ++itr) {
  245. if(((*itr).find(hostname) == std::string::npos) ||
  246. (req.setUri(*itr) && (req.getHost() != hostname))) {
  247. newURIs.push_back(*itr);
  248. }
  249. }
  250. if(logger_->debug()) {
  251. logger_->debug("Removed %d duplicate hostname URIs for path=%s",
  252. uris_.size()-newURIs.size(), getPath().c_str());
  253. }
  254. uris_ = newURIs;
  255. }
  256. void FileEntry::removeIdenticalURI(const std::string& uri)
  257. {
  258. uris_.erase(std::remove(uris_.begin(), uris_.end(), uri), uris_.end());
  259. }
  260. void FileEntry::addURIResult(std::string uri, downloadresultcode::RESULT result)
  261. {
  262. uriResults_.push_back(URIResult(uri, result));
  263. }
  264. namespace {
  265. class FindURIResultByResult {
  266. private:
  267. downloadresultcode::RESULT r_;
  268. public:
  269. FindURIResultByResult(downloadresultcode::RESULT r):r_(r) {}
  270. bool operator()(const URIResult& uriResult) const
  271. {
  272. return uriResult.getResult() == r_;
  273. }
  274. };
  275. }
  276. void FileEntry::extractURIResult
  277. (std::deque<URIResult>& res, downloadresultcode::RESULT r)
  278. {
  279. std::deque<URIResult>::iterator i =
  280. std::stable_partition(uriResults_.begin(), uriResults_.end(),
  281. FindURIResultByResult(r));
  282. std::copy(uriResults_.begin(), i, std::back_inserter(res));
  283. uriResults_.erase(uriResults_.begin(), i);
  284. }
  285. void FileEntry::reuseUri(const std::vector<std::string>& ignore)
  286. {
  287. if(logger_->debug()) {
  288. for(std::vector<std::string>::const_iterator i = ignore.begin(),
  289. eoi = ignore.end(); i != eoi; ++i) {
  290. logger_->debug("ignore host=%s", (*i).c_str());
  291. }
  292. }
  293. std::deque<std::string> uris = spentUris_;
  294. std::sort(uris.begin(), uris.end());
  295. uris.erase(std::unique(uris.begin(), uris.end()), uris.end());
  296. std::vector<std::string> errorUris(uriResults_.size());
  297. std::transform(uriResults_.begin(), uriResults_.end(),
  298. errorUris.begin(), std::mem_fun_ref(&URIResult::getURI));
  299. std::sort(errorUris.begin(), errorUris.end());
  300. errorUris.erase(std::unique(errorUris.begin(), errorUris.end()),
  301. errorUris.end());
  302. if(logger_->debug()) {
  303. for(std::vector<std::string>::const_iterator i = errorUris.begin(),
  304. eoi = errorUris.end(); i != eoi; ++i) {
  305. logger_->debug("error URI=%s", (*i).c_str());
  306. }
  307. }
  308. std::vector<std::string> reusableURIs;
  309. std::set_difference(uris.begin(), uris.end(),
  310. errorUris.begin(), errorUris.end(),
  311. std::back_inserter(reusableURIs));
  312. std::vector<std::string>::iterator insertionPoint = reusableURIs.begin();
  313. Request req;
  314. for(std::vector<std::string>::iterator i = reusableURIs.begin(),
  315. eoi = reusableURIs.end(); i != eoi; ++i) {
  316. req.setUri(*i);
  317. if(std::find(ignore.begin(), ignore.end(), req.getHost()) == ignore.end()) {
  318. if(i != insertionPoint) {
  319. *insertionPoint = *i;
  320. }
  321. ++insertionPoint;
  322. }
  323. }
  324. reusableURIs.erase(insertionPoint, reusableURIs.end());
  325. size_t ininum = reusableURIs.size();
  326. if(logger_->debug()) {
  327. logger_->debug("Found %u reusable URIs", static_cast<unsigned int>(ininum));
  328. for(std::vector<std::string>::const_iterator i = reusableURIs.begin(),
  329. eoi = reusableURIs.end(); i != eoi; ++i) {
  330. logger_->debug("URI=%s", (*i).c_str());
  331. }
  332. }
  333. uris_.insert(uris_.end(), reusableURIs.begin(), reusableURIs.end());
  334. }
  335. void FileEntry::releaseRuntimeResource()
  336. {
  337. requestPool_.clear();
  338. inFlightRequests_.clear();
  339. }
  340. template<typename InputIterator, typename T>
  341. static InputIterator findRequestByUri
  342. (InputIterator first, InputIterator last, const T& uri)
  343. {
  344. for(; first != last; ++first) {
  345. if(!(*first)->removalRequested() && (*first)->getUri() == uri) {
  346. return first;
  347. }
  348. }
  349. return last;
  350. }
  351. bool FileEntry::removeUri(const std::string& uri)
  352. {
  353. std::deque<std::string>::iterator itr =
  354. std::find(spentUris_.begin(), spentUris_.end(), uri);
  355. if(itr == spentUris_.end()) {
  356. itr = std::find(uris_.begin(), uris_.end(), uri);
  357. if(itr == uris_.end()) {
  358. return false;
  359. } else {
  360. uris_.erase(itr);
  361. return true;
  362. }
  363. } else {
  364. spentUris_.erase(itr);
  365. SharedHandle<Request> req;
  366. std::deque<SharedHandle<Request> >::iterator riter =
  367. findRequestByUri(inFlightRequests_.begin(), inFlightRequests_.end(), uri);
  368. if(riter == inFlightRequests_.end()) {
  369. riter = findRequestByUri(requestPool_.begin(), requestPool_.end(), uri);
  370. if(riter == requestPool_.end()) {
  371. return true;
  372. } else {
  373. req = *riter;
  374. requestPool_.erase(riter);
  375. }
  376. } else {
  377. req = *riter;
  378. }
  379. req->requestRemoval();
  380. return true;
  381. }
  382. }
  383. std::string FileEntry::getBasename() const
  384. {
  385. return File(path_).getBasename();
  386. }
  387. std::string FileEntry::getDirname() const
  388. {
  389. return File(path_).getDirname();
  390. }
  391. size_t FileEntry::setUris(const std::vector<std::string>& uris)
  392. {
  393. uris_.clear();
  394. return addUris(uris.begin(), uris.end());
  395. }
  396. bool FileEntry::addUri(const std::string& uri)
  397. {
  398. if(Request().setUri(uri)) {
  399. uris_.push_back(uri);
  400. return true;
  401. } else {
  402. return false;
  403. }
  404. }
  405. bool FileEntry::insertUri(const std::string& uri, size_t pos)
  406. {
  407. if(Request().setUri(uri)) {
  408. pos = std::min(pos, uris_.size());
  409. uris_.insert(uris_.begin()+pos, uri);
  410. return true;
  411. } else {
  412. return false;
  413. }
  414. }
  415. } // namespace aria2