FileEntry.cc 13 KB

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