FileEntry.cc 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  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. #include "ServerStatMan.h"
  48. #include "ServerStat.h"
  49. namespace aria2 {
  50. bool FileEntry::RequestFaster::operator()
  51. (const std::shared_ptr<Request>& lhs,
  52. const std::shared_ptr<Request>& rhs) const
  53. {
  54. if(!lhs->getPeerStat()) {
  55. return false;
  56. }
  57. if(!rhs->getPeerStat()) {
  58. return true;
  59. }
  60. int lspd = lhs->getPeerStat()->getAvgDownloadSpeed();
  61. int rspd = rhs->getPeerStat()->getAvgDownloadSpeed();
  62. return lspd > rspd || (lspd == rspd && lhs.get() < rhs.get());
  63. }
  64. FileEntry::FileEntry(const std::string& path, int64_t length, int64_t offset,
  65. const std::vector<std::string>& uris)
  66. : length_(length),
  67. offset_(offset),
  68. uris_(uris.begin(), uris.end()),
  69. path_(path),
  70. lastFasterReplace_(0),
  71. maxConnectionPerServer_(1),
  72. requested_(true),
  73. uniqueProtocol_(false)
  74. {}
  75. FileEntry::FileEntry()
  76. : length_(0),
  77. offset_(0),
  78. maxConnectionPerServer_(1),
  79. requested_(false),
  80. uniqueProtocol_(false)
  81. {}
  82. FileEntry::~FileEntry() {}
  83. FileEntry& FileEntry::operator=(const FileEntry& entry)
  84. {
  85. if(this != &entry) {
  86. path_ = entry.path_;
  87. length_ = entry.length_;
  88. offset_ = entry.offset_;
  89. requested_ = entry.requested_;
  90. }
  91. return *this;
  92. }
  93. bool FileEntry::operator<(const FileEntry& fileEntry) const
  94. {
  95. return offset_ < fileEntry.offset_;
  96. }
  97. bool FileEntry::exists() const
  98. {
  99. return File(getPath()).exists();
  100. }
  101. int64_t FileEntry::gtoloff(int64_t goff) const
  102. {
  103. assert(offset_ <= goff);
  104. return goff-offset_;
  105. }
  106. void FileEntry::getUris(std::vector<std::string>& uris) const
  107. {
  108. uris.insert(uris.end(), spentUris_.begin(), spentUris_.end());
  109. uris.insert(uris.end(), uris_.begin(), uris_.end());
  110. }
  111. namespace {
  112. template<typename InputIterator, typename OutputIterator>
  113. OutputIterator enumerateInFlightHosts
  114. (InputIterator first, InputIterator last, OutputIterator out)
  115. {
  116. for(; first != last; ++first) {
  117. uri_split_result us;
  118. if(uri_split(&us, (*first)->getUri().c_str()) == 0) {
  119. *out++ = uri::getFieldString(us, USR_HOST, (*first)->getUri().c_str());
  120. }
  121. }
  122. return out;
  123. }
  124. } // namespace
  125. std::shared_ptr<Request>
  126. FileEntry::getRequest
  127. (URISelector* selector,
  128. bool uriReuse,
  129. const std::vector<std::pair<size_t, std::string> >& usedHosts,
  130. const std::string& referer,
  131. const std::string& method)
  132. {
  133. std::shared_ptr<Request> req;
  134. if(requestPool_.empty()) {
  135. std::vector<std::string> inFlightHosts;
  136. enumerateInFlightHosts(inFlightRequests_.begin(), inFlightRequests_.end(),
  137. std::back_inserter(inFlightHosts));
  138. for(int g = 0; g < 2; ++g) {
  139. std::vector<std::string> pending;
  140. std::vector<std::string> ignoreHost;
  141. while(1) {
  142. std::string uri = selector->select(this, usedHosts);
  143. if(uri.empty()) {
  144. break;
  145. }
  146. req.reset(new Request());
  147. if(req->setUri(uri)) {
  148. if(std::count(inFlightHosts.begin(),
  149. inFlightHosts.end(),req->getHost())
  150. >= maxConnectionPerServer_) {
  151. pending.push_back(uri);
  152. ignoreHost.push_back(req->getHost());
  153. req.reset();
  154. continue;
  155. }
  156. if(referer == "*") {
  157. // Assuming uri has already been percent-encoded.
  158. req->setReferer(uri);
  159. } else {
  160. req->setReferer(util::percentEncodeMini(referer));
  161. }
  162. req->setMethod(method);
  163. spentUris_.push_back(uri);
  164. inFlightRequests_.insert(req);
  165. break;
  166. } else {
  167. req.reset();
  168. }
  169. }
  170. uris_.insert(uris_.begin(), pending.begin(), pending.end());
  171. if(g == 0 && uriReuse && !req && uris_.size() == pending.size()) {
  172. // Reuse URIs other than ones in pending
  173. reuseUri(ignoreHost);
  174. } else {
  175. break;
  176. }
  177. }
  178. } else {
  179. // Skip Request object if it is still
  180. // sleeping(Request::getWakeTime() < global::wallclock()). If all
  181. // pooled objects are sleeping, return first one. Caller should
  182. // inspect returned object's getWakeTime().
  183. auto i = requestPool_.begin();
  184. auto eoi = requestPool_.end();
  185. for(; i != eoi; ++i) {
  186. if((*i)->getWakeTime() <= global::wallclock()) {
  187. break;
  188. }
  189. }
  190. if(i == eoi) {
  191. i = requestPool_.begin();
  192. }
  193. req = *i;
  194. requestPool_.erase(i);
  195. inFlightRequests_.insert(req);
  196. A2_LOG_DEBUG(fmt("Picked up from pool: %s", req->getUri().c_str()));
  197. }
  198. return req;
  199. }
  200. std::shared_ptr<Request>
  201. FileEntry::findFasterRequest(const std::shared_ptr<Request>& base)
  202. {
  203. const int startupIdleTime = 10;
  204. if(requestPool_.empty() ||
  205. lastFasterReplace_.difference(global::wallclock()) < startupIdleTime) {
  206. return nullptr;
  207. }
  208. const std::shared_ptr<PeerStat>& fastest =
  209. (*requestPool_.begin())->getPeerStat();
  210. if(!fastest) {
  211. return nullptr;
  212. }
  213. const std::shared_ptr<PeerStat>& basestat = base->getPeerStat();
  214. // TODO hard coded value. See PREF_STARTUP_IDLE_TIME
  215. if(!basestat ||
  216. (basestat->getDownloadStartTime().
  217. difference(global::wallclock()) >= startupIdleTime &&
  218. fastest->getAvgDownloadSpeed()*0.8 > basestat->calculateDownloadSpeed())){
  219. // TODO we should consider that "fastest" is very slow.
  220. std::shared_ptr<Request> fastestRequest = *requestPool_.begin();
  221. requestPool_.erase(requestPool_.begin());
  222. inFlightRequests_.insert(fastestRequest);
  223. lastFasterReplace_ = global::wallclock();
  224. return fastestRequest;
  225. }
  226. return nullptr;
  227. }
  228. std::shared_ptr<Request>
  229. FileEntry::findFasterRequest
  230. (const std::shared_ptr<Request>& base,
  231. const std::vector<std::pair<size_t, std::string> >& usedHosts,
  232. const std::shared_ptr<ServerStatMan>& serverStatMan)
  233. {
  234. const int startupIdleTime = 10;
  235. const int SPEED_THRESHOLD = 20*1024;
  236. if(lastFasterReplace_.difference(global::wallclock()) < startupIdleTime) {
  237. return nullptr;
  238. }
  239. std::vector<std::string> inFlightHosts;
  240. enumerateInFlightHosts(inFlightRequests_.begin(), inFlightRequests_.end(),
  241. std::back_inserter(inFlightHosts));
  242. const std::shared_ptr<PeerStat>& basestat = base->getPeerStat();
  243. A2_LOG_DEBUG("Search faster server using ServerStat.");
  244. // Use first 10 good URIs to introduce some randomness.
  245. const size_t NUM_URI = 10;
  246. std::vector<std::pair<std::shared_ptr<ServerStat>, std::string> > fastCands;
  247. std::vector<std::string> normCands;
  248. for(std::deque<std::string>::const_iterator i = uris_.begin(),
  249. eoi = uris_.end(); i != eoi && fastCands.size() < NUM_URI; ++i) {
  250. uri_split_result us;
  251. if(uri_split(&us, (*i).c_str()) == -1) {
  252. continue;
  253. }
  254. std::string host = uri::getFieldString(us, USR_HOST, (*i).c_str());
  255. std::string protocol = uri::getFieldString(us, USR_SCHEME, (*i).c_str());
  256. if(std::count(inFlightHosts.begin(), inFlightHosts.end(), host)
  257. >= maxConnectionPerServer_) {
  258. A2_LOG_DEBUG(fmt("%s has already used %d times, not considered.",
  259. (*i).c_str(),
  260. maxConnectionPerServer_));
  261. continue;
  262. }
  263. if(findSecond(usedHosts.begin(), usedHosts.end(), host) !=
  264. usedHosts.end()) {
  265. A2_LOG_DEBUG(fmt("%s is in usedHosts, not considered", (*i).c_str()));
  266. continue;
  267. }
  268. std::shared_ptr<ServerStat> ss = serverStatMan->find(host, protocol);
  269. if(ss && ss->isOK()) {
  270. if((basestat &&
  271. ss->getDownloadSpeed() > basestat->calculateDownloadSpeed()*1.5) ||
  272. (!basestat && ss->getDownloadSpeed() > SPEED_THRESHOLD)) {
  273. fastCands.push_back(std::make_pair(ss, *i));
  274. }
  275. }
  276. }
  277. if(!fastCands.empty()) {
  278. std::sort(fastCands.begin(), fastCands.end(), ServerStatFaster());
  279. std::shared_ptr<Request> fastestRequest(new Request());
  280. const std::string& uri = fastCands.front().second;
  281. A2_LOG_DEBUG(fmt("Selected %s from fastCands", uri.c_str()));
  282. fastestRequest->setUri(uri);
  283. fastestRequest->setReferer(base->getReferer());
  284. uris_.erase(std::find(uris_.begin(), uris_.end(), uri));
  285. spentUris_.push_back(uri);
  286. inFlightRequests_.insert(fastestRequest);
  287. lastFasterReplace_ = global::wallclock();
  288. return fastestRequest;
  289. }
  290. A2_LOG_DEBUG("No faster server found.");
  291. return nullptr;
  292. }
  293. void FileEntry::storePool(const std::shared_ptr<Request>& request)
  294. {
  295. const std::shared_ptr<PeerStat>& peerStat = request->getPeerStat();
  296. if(peerStat) {
  297. // We need to calculate average download speed here in order to
  298. // store Request in the right position in the pool.
  299. peerStat->calculateAvgDownloadSpeed();
  300. }
  301. requestPool_.insert(request);
  302. }
  303. void FileEntry::poolRequest(const std::shared_ptr<Request>& request)
  304. {
  305. removeRequest(request);
  306. if(!request->removalRequested()) {
  307. storePool(request);
  308. }
  309. }
  310. bool FileEntry::removeRequest(const std::shared_ptr<Request>& request)
  311. {
  312. return inFlightRequests_.erase(request) == 1;
  313. }
  314. void FileEntry::removeURIWhoseHostnameIs(const std::string& hostname)
  315. {
  316. std::deque<std::string> newURIs;
  317. for(std::deque<std::string>::const_iterator itr = uris_.begin(),
  318. eoi = uris_.end(); itr != eoi; ++itr) {
  319. uri_split_result us;
  320. if(uri_split(&us, (*itr).c_str()) == -1) {
  321. continue;
  322. }
  323. if(us.fields[USR_HOST].len != hostname.size() ||
  324. memcmp((*itr).c_str()+us.fields[USR_HOST].off, hostname.c_str(),
  325. hostname.size()) != 0) {
  326. newURIs.push_back(*itr);
  327. }
  328. }
  329. A2_LOG_DEBUG(fmt("Removed %lu duplicate hostname URIs for path=%s",
  330. static_cast<unsigned long>(uris_.size()-newURIs.size()),
  331. getPath().c_str()));
  332. uris_.swap(newURIs);
  333. }
  334. void FileEntry::removeIdenticalURI(const std::string& uri)
  335. {
  336. uris_.erase(std::remove(uris_.begin(), uris_.end(), uri), uris_.end());
  337. }
  338. void FileEntry::addURIResult(std::string uri, error_code::Value result)
  339. {
  340. uriResults_.push_back(URIResult(uri, result));
  341. }
  342. namespace {
  343. class FindURIResultByResult {
  344. private:
  345. error_code::Value r_;
  346. public:
  347. FindURIResultByResult(error_code::Value r):r_(r) {}
  348. bool operator()(const URIResult& uriResult) const
  349. {
  350. return uriResult.getResult() == r_;
  351. }
  352. };
  353. } // namespace
  354. void FileEntry::extractURIResult
  355. (std::deque<URIResult>& res, error_code::Value r)
  356. {
  357. auto i = std::stable_partition(uriResults_.begin(), uriResults_.end(),
  358. FindURIResultByResult(r));
  359. std::copy(uriResults_.begin(), i, std::back_inserter(res));
  360. uriResults_.erase(uriResults_.begin(), i);
  361. }
  362. void FileEntry::reuseUri(const std::vector<std::string>& ignore)
  363. {
  364. if(A2_LOG_DEBUG_ENABLED) {
  365. for (const auto& i: ignore) {
  366. A2_LOG_DEBUG(fmt("ignore host=%s", i.c_str()));
  367. }
  368. }
  369. std::deque<std::string> uris = spentUris_;
  370. std::sort(uris.begin(), uris.end());
  371. uris.erase(std::unique(uris.begin(), uris.end()), uris.end());
  372. std::vector<std::string> errorUris(uriResults_.size());
  373. std::transform(uriResults_.begin(), uriResults_.end(),
  374. errorUris.begin(), std::mem_fn(&URIResult::getURI));
  375. std::sort(errorUris.begin(), errorUris.end());
  376. errorUris.erase(std::unique(errorUris.begin(), errorUris.end()),
  377. errorUris.end());
  378. if(A2_LOG_DEBUG_ENABLED) {
  379. for(std::vector<std::string>::const_iterator i = errorUris.begin(),
  380. eoi = errorUris.end(); i != eoi; ++i) {
  381. A2_LOG_DEBUG(fmt("error URI=%s", (*i).c_str()));
  382. }
  383. }
  384. std::vector<std::string> reusableURIs;
  385. std::set_difference(uris.begin(), uris.end(),
  386. errorUris.begin(), errorUris.end(),
  387. std::back_inserter(reusableURIs));
  388. auto insertionPoint = reusableURIs.begin();
  389. for(auto i = reusableURIs.begin(),
  390. eoi = reusableURIs.end(); i != eoi; ++i) {
  391. uri_split_result us;
  392. if(uri_split(&us, (*i).c_str()) == 0 &&
  393. std::find(ignore.begin(), ignore.end(),
  394. uri::getFieldString(us, USR_HOST, (*i).c_str()))
  395. == ignore.end()) {
  396. if(i != insertionPoint) {
  397. *insertionPoint = *i;
  398. }
  399. ++insertionPoint;
  400. }
  401. }
  402. reusableURIs.erase(insertionPoint, reusableURIs.end());
  403. size_t ininum = reusableURIs.size();
  404. if(A2_LOG_DEBUG_ENABLED) {
  405. A2_LOG_DEBUG(fmt("Found %u reusable URIs",
  406. static_cast<unsigned int>(ininum)));
  407. for(std::vector<std::string>::const_iterator i = reusableURIs.begin(),
  408. eoi = reusableURIs.end(); i != eoi; ++i) {
  409. A2_LOG_DEBUG(fmt("URI=%s", (*i).c_str()));
  410. }
  411. }
  412. uris_.insert(uris_.end(), reusableURIs.begin(), reusableURIs.end());
  413. }
  414. void FileEntry::releaseRuntimeResource()
  415. {
  416. requestPool_.clear();
  417. inFlightRequests_.clear();
  418. }
  419. namespace {
  420. template<typename InputIterator>
  421. void putBackUri
  422. (std::deque<std::string>& uris,
  423. InputIterator first,
  424. InputIterator last)
  425. {
  426. for(; first != last; ++first) {
  427. uris.push_front((*first)->getUri());
  428. }
  429. }
  430. } // namespace
  431. void FileEntry::putBackRequest()
  432. {
  433. putBackUri(uris_, requestPool_.begin(), requestPool_.end());
  434. putBackUri(uris_, inFlightRequests_.begin(), inFlightRequests_.end());
  435. }
  436. namespace {
  437. template<typename InputIterator, typename T>
  438. InputIterator findRequestByUri
  439. (InputIterator first, InputIterator last, const T& uri)
  440. {
  441. for(; first != last; ++first) {
  442. if(!(*first)->removalRequested() && (*first)->getUri() == uri) {
  443. return first;
  444. }
  445. }
  446. return last;
  447. }
  448. } // namespace
  449. bool FileEntry::removeUri(const std::string& uri)
  450. {
  451. auto itr = std::find(spentUris_.begin(), spentUris_.end(), uri);
  452. if(itr == spentUris_.end()) {
  453. itr = std::find(uris_.begin(), uris_.end(), uri);
  454. if(itr == uris_.end()) {
  455. return false;
  456. }
  457. uris_.erase(itr);
  458. return true;
  459. }
  460. spentUris_.erase(itr);
  461. std::shared_ptr<Request> req;
  462. auto riter =
  463. findRequestByUri(inFlightRequests_.begin(), inFlightRequests_.end(), uri);
  464. if(riter == inFlightRequests_.end()) {
  465. auto riter = findRequestByUri(requestPool_.begin(),
  466. requestPool_.end(), uri);
  467. if(riter == requestPool_.end()) {
  468. return true;
  469. }
  470. req = *riter;
  471. requestPool_.erase(riter);
  472. } else {
  473. req = *riter;
  474. }
  475. req->requestRemoval();
  476. return true;
  477. }
  478. std::string FileEntry::getBasename() const
  479. {
  480. return File(path_).getBasename();
  481. }
  482. std::string FileEntry::getDirname() const
  483. {
  484. return File(path_).getDirname();
  485. }
  486. size_t FileEntry::setUris(const std::vector<std::string>& uris)
  487. {
  488. uris_.clear();
  489. return addUris(uris.begin(), uris.end());
  490. }
  491. bool FileEntry::addUri(const std::string& uri)
  492. {
  493. std::string peUri = util::percentEncodeMini(uri);
  494. if(uri_split(nullptr, peUri.c_str()) == 0) {
  495. uris_.push_back(peUri);
  496. return true;
  497. } else {
  498. return false;
  499. }
  500. }
  501. bool FileEntry::insertUri(const std::string& uri, size_t pos)
  502. {
  503. std::string peUri = util::percentEncodeMini(uri);
  504. if(uri_split(nullptr, peUri.c_str()) != 0) {
  505. return false;
  506. }
  507. pos = std::min(pos, uris_.size());
  508. uris_.insert(uris_.begin()+pos, peUri);
  509. return true;
  510. }
  511. void FileEntry::setPath(const std::string& path)
  512. {
  513. path_ = path;
  514. }
  515. void FileEntry::setContentType(const std::string& contentType)
  516. {
  517. contentType_ = contentType;
  518. }
  519. size_t FileEntry::countInFlightRequest() const
  520. {
  521. return inFlightRequests_.size();
  522. }
  523. size_t FileEntry::countPooledRequest() const
  524. {
  525. return requestPool_.size();
  526. }
  527. void FileEntry::setOriginalName(const std::string& originalName)
  528. {
  529. originalName_ = originalName;
  530. }
  531. bool FileEntry::emptyRequestUri() const
  532. {
  533. return uris_.empty() && inFlightRequests_.empty() && requestPool_.empty();
  534. }
  535. void writeFilePath
  536. (std::ostream& o,
  537. const std::shared_ptr<FileEntry>& entry,
  538. bool memory)
  539. {
  540. if(entry->getPath().empty()) {
  541. std::vector<std::string> uris;
  542. entry->getUris(uris);
  543. if(uris.empty()) {
  544. o << "n/a";
  545. } else {
  546. o << uris.front();
  547. }
  548. return;
  549. }
  550. if(memory) {
  551. o << "[MEMORY]" << File(entry->getPath()).getBasename();
  552. } else {
  553. o << entry->getPath();
  554. }
  555. }
  556. } // namespace aria2