DownloadEngine.cc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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 "DownloadEngine.h"
  36. #include <signal.h>
  37. #include <cstring>
  38. #include <cerrno>
  39. #include <algorithm>
  40. #include <numeric>
  41. #include "StatCalc.h"
  42. #include "RequestGroup.h"
  43. #include "RequestGroupMan.h"
  44. #include "DownloadResult.h"
  45. #include "StatCalc.h"
  46. #include "LogFactory.h"
  47. #include "Logger.h"
  48. #include "TimeA2.h"
  49. #include "a2time.h"
  50. #include "Socket.h"
  51. #include "Util.h"
  52. #include "a2functional.h"
  53. #include "DlAbortEx.h"
  54. #include "ServerStatMan.h"
  55. #include "CookieStorage.h"
  56. #include "A2STR.h"
  57. #include "DNSCache.h"
  58. #include "AuthConfigFactory.h"
  59. #include "AuthConfig.h"
  60. #include "Request.h"
  61. #include "EventPoll.h"
  62. #include "Command.h"
  63. #include "FileAllocationEntry.h"
  64. #include "CheckIntegrityEntry.h"
  65. #include "BtRegistry.h"
  66. #include "BtContext.h"
  67. #include "PeerStorage.h"
  68. #include "PieceStorage.h"
  69. #include "BtAnnounce.h"
  70. #include "BtRuntime.h"
  71. #include "BtProgressInfoFile.h"
  72. namespace aria2 {
  73. // 0 ... running
  74. // 1 ... stop signal detected
  75. // 2 ... stop signal processed by DownloadEngine
  76. // 3 ... 2nd stop signal(force shutdown) detected
  77. // 4 ... 2nd stop signal processed by DownloadEngine
  78. volatile sig_atomic_t globalHaltRequested = 0;
  79. DownloadEngine::DownloadEngine(const SharedHandle<EventPoll>& eventPoll):
  80. _eventPoll(eventPoll),
  81. logger(LogFactory::getInstance()),
  82. _haltRequested(false),
  83. _noWait(false),
  84. _refreshInterval(DEFAULT_REFRESH_INTERVAL),
  85. _cookieStorage(new CookieStorage()),
  86. _btRegistry(new BtRegistry()),
  87. _dnsCache(new SimpleDNSCache())
  88. {}
  89. DownloadEngine::~DownloadEngine() {
  90. cleanQueue();
  91. }
  92. void DownloadEngine::cleanQueue() {
  93. std::for_each(commands.begin(), commands.end(), Deleter());
  94. commands.clear();
  95. }
  96. static void executeCommand(std::deque<Command*>& commands,
  97. Command::STATUS statusFilter)
  98. {
  99. size_t max = commands.size();
  100. for(size_t i = 0; i < max; i++) {
  101. Command* com = commands.front();
  102. commands.pop_front();
  103. if(com->statusMatch(statusFilter)) {
  104. com->transitStatus();
  105. if(com->execute()) {
  106. delete com;
  107. com = 0;
  108. }
  109. } else {
  110. commands.push_back(com);
  111. }
  112. if(com) {
  113. com->clearIOEvents();
  114. }
  115. }
  116. }
  117. void DownloadEngine::run()
  118. {
  119. Time cp;
  120. cp.setTimeInSec(0);
  121. while(!commands.empty() || !_routineCommands.empty()) {
  122. if(cp.elapsed(_refreshInterval)) {
  123. _refreshInterval = DEFAULT_REFRESH_INTERVAL;
  124. cp.reset();
  125. executeCommand(commands, Command::STATUS_ALL);
  126. } else {
  127. executeCommand(commands, Command::STATUS_ACTIVE);
  128. }
  129. executeCommand(_routineCommands, Command::STATUS_ALL);
  130. afterEachIteration();
  131. if(!commands.empty()) {
  132. waitData();
  133. }
  134. _noWait = false;
  135. calculateStatistics();
  136. }
  137. onEndOfRun();
  138. }
  139. void DownloadEngine::waitData()
  140. {
  141. struct timeval tv;
  142. if(_noWait) {
  143. tv.tv_sec = tv.tv_usec = 0;
  144. } else {
  145. tv.tv_sec = 1;
  146. tv.tv_usec = 0;
  147. }
  148. _eventPoll->poll(tv);
  149. }
  150. bool DownloadEngine::addSocketForReadCheck(const SocketHandle& socket,
  151. Command* command)
  152. {
  153. return _eventPoll->addEvents(socket->getSockfd(), command,
  154. EventPoll::EVENT_READ);
  155. }
  156. bool DownloadEngine::deleteSocketForReadCheck(const SocketHandle& socket,
  157. Command* command)
  158. {
  159. return _eventPoll->deleteEvents(socket->getSockfd(), command,
  160. EventPoll::EVENT_READ);
  161. }
  162. bool DownloadEngine::addSocketForWriteCheck(const SocketHandle& socket,
  163. Command* command)
  164. {
  165. return _eventPoll->addEvents(socket->getSockfd(), command,
  166. EventPoll::EVENT_WRITE);
  167. }
  168. bool DownloadEngine::deleteSocketForWriteCheck(const SocketHandle& socket,
  169. Command* command)
  170. {
  171. return _eventPoll->deleteEvents(socket->getSockfd(), command,
  172. EventPoll::EVENT_WRITE);
  173. }
  174. void DownloadEngine::calculateStatistics()
  175. {
  176. if(!_statCalc.isNull()) {
  177. _statCalc->calculateStat(this);
  178. }
  179. }
  180. void DownloadEngine::onEndOfRun()
  181. {
  182. _requestGroupMan->updateServerStat();
  183. _requestGroupMan->closeFile();
  184. _requestGroupMan->save();
  185. }
  186. void DownloadEngine::afterEachIteration()
  187. {
  188. _requestGroupMan->calculateStat();
  189. if(globalHaltRequested == 1) {
  190. logger->notice(_("Shutdown sequence commencing... Press Ctrl-C again for emergency shutdown."));
  191. requestHalt();
  192. globalHaltRequested = 2;
  193. setNoWait(true);
  194. setRefreshInterval(0);
  195. } else if(globalHaltRequested == 3) {
  196. logger->notice(_("Emergency shutdown sequence commencing..."));
  197. _requestGroupMan->forceHalt();
  198. globalHaltRequested = 4;
  199. setNoWait(true);
  200. setRefreshInterval(0);
  201. }
  202. }
  203. void DownloadEngine::requestHalt()
  204. {
  205. _haltRequested = true;
  206. _requestGroupMan->halt();
  207. }
  208. void DownloadEngine::fillCommand()
  209. {
  210. std::deque<Command*> commands;
  211. _requestGroupMan->getInitialCommands(commands, this);
  212. addCommand(commands);
  213. }
  214. void DownloadEngine::setStatCalc(const StatCalcHandle& statCalc)
  215. {
  216. _statCalc = statCalc;
  217. }
  218. void DownloadEngine::addCommand(const Commands& commands)
  219. {
  220. this->commands.insert(this->commands.end(), commands.begin(), commands.end());
  221. }
  222. #ifdef ENABLE_ASYNC_DNS
  223. bool DownloadEngine::addNameResolverCheck
  224. (const SharedHandle<AsyncNameResolver>& resolver, Command* command)
  225. {
  226. return _eventPoll->addNameResolver(resolver, command);
  227. }
  228. bool DownloadEngine::deleteNameResolverCheck
  229. (const SharedHandle<AsyncNameResolver>& resolver, Command* command)
  230. {
  231. return _eventPoll->deleteNameResolver(resolver, command);
  232. }
  233. #endif // ENABLE_ASYNC_DNS
  234. void DownloadEngine::setNoWait(bool b)
  235. {
  236. _noWait = b;
  237. }
  238. void DownloadEngine::addRoutineCommand(Command* command)
  239. {
  240. _routineCommands.push_back(command);
  241. }
  242. void DownloadEngine::poolSocket(const std::string& ipaddr,
  243. uint16_t port,
  244. const SocketPoolEntry& entry)
  245. {
  246. std::string addr = ipaddr+":"+Util::uitos(port);
  247. logger->info("Pool socket for %s", addr.c_str());
  248. std::multimap<std::string, SocketPoolEntry>::value_type p(addr, entry);
  249. _socketPool.insert(p);
  250. if(_lastSocketPoolScan.elapsed(60)) {
  251. std::multimap<std::string, SocketPoolEntry> newPool;
  252. logger->debug("Scaning SocketPool and erasing timed out entry.");
  253. _lastSocketPoolScan.reset();
  254. for(std::multimap<std::string, SocketPoolEntry>::iterator i =
  255. _socketPool.begin(); i != _socketPool.end(); ++i) {
  256. if(!(*i).second.isTimeout()) {
  257. newPool.insert(*i);
  258. }
  259. }
  260. logger->debug
  261. ("%lu entries removed.",
  262. static_cast<unsigned long>(_socketPool.size()-newPool.size()));
  263. _socketPool = newPool;
  264. }
  265. }
  266. void DownloadEngine::poolSocket
  267. (const std::string& ipaddr,
  268. uint16_t port,
  269. const SharedHandle<SocketCore>& sock,
  270. const std::map<std::string, std::string>& options,
  271. time_t timeout)
  272. {
  273. SocketPoolEntry e(sock, options, timeout);
  274. poolSocket(ipaddr, port, e);
  275. }
  276. void DownloadEngine::poolSocket
  277. (const std::string& ipaddr,
  278. uint16_t port,
  279. const SharedHandle<SocketCore>& sock,
  280. time_t timeout)
  281. {
  282. SocketPoolEntry e(sock, std::map<std::string, std::string>(), timeout);
  283. poolSocket(ipaddr, port, e);
  284. }
  285. void DownloadEngine::poolSocket(const SharedHandle<Request>& request,
  286. bool proxyDefined,
  287. const SharedHandle<SocketCore>& socket,
  288. time_t timeout)
  289. {
  290. if(proxyDefined) {
  291. // If proxy is defined, then pool socket with its hostname.
  292. poolSocket(request->getHost(), request->getPort(), socket);
  293. } else {
  294. std::pair<std::string, uint16_t> peerInfo;
  295. socket->getPeerInfo(peerInfo);
  296. poolSocket(peerInfo.first, peerInfo.second, socket);
  297. }
  298. }
  299. void DownloadEngine::poolSocket
  300. (const SharedHandle<Request>& request,
  301. bool proxyDefined,
  302. const SharedHandle<SocketCore>& socket,
  303. const std::map<std::string, std::string>& options,
  304. time_t timeout)
  305. {
  306. if(proxyDefined) {
  307. // If proxy is defined, then pool socket with its hostname.
  308. poolSocket(request->getHost(), request->getPort(), socket, options);
  309. } else {
  310. std::pair<std::string, uint16_t> peerInfo;
  311. socket->getPeerInfo(peerInfo);
  312. poolSocket(peerInfo.first, peerInfo.second, socket, options);
  313. }
  314. }
  315. std::multimap<std::string, DownloadEngine::SocketPoolEntry>::iterator
  316. DownloadEngine::findSocketPoolEntry(const std::string& ipaddr, uint16_t port)
  317. {
  318. std::string addr = ipaddr+":"+Util::uitos(port);
  319. std::pair<std::multimap<std::string, SocketPoolEntry>::iterator,
  320. std::multimap<std::string, SocketPoolEntry>::iterator> range =
  321. _socketPool.equal_range(addr);
  322. for(std::multimap<std::string, SocketPoolEntry>::iterator i = range.first;
  323. i != range.second; ++i) {
  324. const SocketPoolEntry& e = (*i).second;
  325. if(!e.isTimeout()) {
  326. logger->info("Found socket for %s", addr.c_str());
  327. return i;
  328. }
  329. }
  330. return _socketPool.end();
  331. }
  332. SharedHandle<SocketCore>
  333. DownloadEngine::popPooledSocket(const std::string& ipaddr, uint16_t port)
  334. {
  335. SharedHandle<SocketCore> s;
  336. std::multimap<std::string, SocketPoolEntry>::iterator i =
  337. findSocketPoolEntry(ipaddr, port);
  338. if(i != _socketPool.end()) {
  339. s = (*i).second.getSocket();
  340. _socketPool.erase(i);
  341. }
  342. return s;
  343. }
  344. SharedHandle<SocketCore>
  345. DownloadEngine::popPooledSocket(std::map<std::string, std::string>& options,
  346. const std::string& ipaddr, uint16_t port)
  347. {
  348. SharedHandle<SocketCore> s;
  349. std::multimap<std::string, SocketPoolEntry>::iterator i =
  350. findSocketPoolEntry(ipaddr, port);
  351. if(i != _socketPool.end()) {
  352. s = (*i).second.getSocket();
  353. options = (*i).second.getOptions();
  354. _socketPool.erase(i);
  355. }
  356. return s;
  357. }
  358. SharedHandle<SocketCore>
  359. DownloadEngine::popPooledSocket
  360. (const std::deque<std::string>& ipaddrs, uint16_t port)
  361. {
  362. SharedHandle<SocketCore> s;
  363. for(std::deque<std::string>::const_iterator i = ipaddrs.begin();
  364. i != ipaddrs.end(); ++i) {
  365. s = popPooledSocket(*i, port);
  366. if(!s.isNull()) {
  367. break;
  368. }
  369. }
  370. return s;
  371. }
  372. SharedHandle<SocketCore>
  373. DownloadEngine::popPooledSocket
  374. (std::map<std::string, std::string>& options,
  375. const std::deque<std::string>& ipaddrs, uint16_t port)
  376. {
  377. SharedHandle<SocketCore> s;
  378. for(std::deque<std::string>::const_iterator i = ipaddrs.begin();
  379. i != ipaddrs.end(); ++i) {
  380. s = popPooledSocket(options, *i, port);
  381. if(!s.isNull()) {
  382. break;
  383. }
  384. }
  385. return s;
  386. }
  387. DownloadEngine::SocketPoolEntry::SocketPoolEntry
  388. (const SharedHandle<SocketCore>& socket,
  389. const std::map<std::string, std::string>& options,
  390. time_t timeout):
  391. _socket(socket),
  392. _options(options),
  393. _timeout(timeout) {}
  394. DownloadEngine::SocketPoolEntry::~SocketPoolEntry() {}
  395. bool DownloadEngine::SocketPoolEntry::isTimeout() const
  396. {
  397. return _registeredTime.elapsed(_timeout);
  398. }
  399. cuid_t DownloadEngine::newCUID()
  400. {
  401. return _cuidCounter.newID();
  402. }
  403. const std::string& DownloadEngine::findCachedIPAddress
  404. (const std::string& hostname) const
  405. {
  406. return _dnsCache->find(hostname);
  407. }
  408. void DownloadEngine::cacheIPAddress
  409. (const std::string& hostname, const std::string& ipaddr)
  410. {
  411. _dnsCache->put(hostname, ipaddr);
  412. }
  413. void DownloadEngine::setAuthConfigFactory
  414. (const SharedHandle<AuthConfigFactory>& factory)
  415. {
  416. _authConfigFactory = factory;
  417. }
  418. void DownloadEngine::setRefreshInterval(time_t interval)
  419. {
  420. _refreshInterval = interval;
  421. }
  422. } // namespace aria2