DownloadEngine.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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. #ifdef ENABLE_ASYNC_DNS
  37. #include "AsyncNameResolver.h"
  38. #endif // ENABLE_ASYNC_DNS
  39. #include "StatCalc.h"
  40. #include "RequestGroup.h"
  41. #include "RequestGroupMan.h"
  42. #include "FileAllocationMan.h"
  43. #include "CheckIntegrityMan.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 <signal.h>
  54. #include <cstring>
  55. #include <algorithm>
  56. namespace aria2 {
  57. // 0 ... running
  58. // 1 ... stop signal detected
  59. // 2 ... stop signal processed by DownloadEngine
  60. // 3 ... 2nd stop signal(force shutdown) detected
  61. // 4 ... 2nd stop signal processed by DownloadEngine
  62. volatile sig_atomic_t globalHaltRequested = 0;
  63. SocketEntry::SocketEntry(const SocketHandle& socket,
  64. Command* command,
  65. TYPE type):
  66. socket(socket), command(command), type(type) {}
  67. bool SocketEntry::operator==(const SocketEntry& entry)
  68. {
  69. return socket == entry.socket &&
  70. command == entry.command &&
  71. type == entry.type;
  72. }
  73. #ifdef ENABLE_ASYNC_DNS
  74. AsyncNameResolverEntry::AsyncNameResolverEntry
  75. (const SharedHandle<AsyncNameResolver>& nameResolver,
  76. Command* command):
  77. nameResolver(nameResolver), command(command) {}
  78. bool AsyncNameResolverEntry::operator==(const AsyncNameResolverEntry& entry)
  79. {
  80. return nameResolver == entry.nameResolver &&
  81. command == entry.command;
  82. }
  83. #endif // ENABLE_ASYNC_DNS
  84. DownloadEngine::DownloadEngine():logger(LogFactory::getInstance()),
  85. _haltRequested(false),
  86. _noWait(false)
  87. {
  88. updateFdSet();
  89. }
  90. DownloadEngine::~DownloadEngine() {
  91. cleanQueue();
  92. }
  93. void DownloadEngine::cleanQueue() {
  94. std::for_each(commands.begin(), commands.end(), Deleter());
  95. commands.clear();
  96. }
  97. static void executeCommand(std::deque<Command*>& commands,
  98. Command::STATUS statusFilter)
  99. {
  100. size_t max = commands.size();
  101. for(size_t i = 0; i < max; i++) {
  102. Command* com = commands.front();
  103. commands.pop_front();
  104. if(com->statusMatch(statusFilter)) {
  105. com->transitStatus();
  106. if(com->execute()) {
  107. delete com;
  108. }
  109. } else {
  110. commands.push_back(com);
  111. }
  112. }
  113. }
  114. void DownloadEngine::run() {
  115. Time cp;
  116. cp.setTimeInSec(0);
  117. while(!commands.empty() || !_routineCommands.empty()) {
  118. if(cp.elapsed(1)) {
  119. cp.reset();
  120. executeCommand(commands, Command::STATUS_ALL);
  121. } else {
  122. executeCommand(commands, Command::STATUS_ACTIVE);
  123. }
  124. executeCommand(_routineCommands, Command::STATUS_ALL);
  125. afterEachIteration();
  126. if(!commands.empty()) {
  127. waitData();
  128. }
  129. _noWait = false;
  130. calculateStatistics();
  131. }
  132. onEndOfRun();
  133. }
  134. void DownloadEngine::shortSleep() const {
  135. struct timeval tv;
  136. tv.tv_sec = 0;
  137. tv.tv_usec = 1000;
  138. fd_set rfds;
  139. FD_ZERO(&rfds);
  140. select(0, &rfds, NULL, NULL, &tv);
  141. }
  142. void DownloadEngine::waitData() {
  143. fd_set rfds;
  144. fd_set wfds;
  145. struct timeval tv;
  146. memcpy(&rfds, &rfdset, sizeof(fd_set));
  147. memcpy(&wfds, &wfdset, sizeof(fd_set));
  148. #ifdef ENABLE_ASYNC_DNS
  149. for(AsyncNameResolverEntries::iterator itr = nameResolverEntries.begin();
  150. itr != nameResolverEntries.end(); ++itr) {
  151. AsyncNameResolverEntry& entry = *itr;
  152. int fd = entry.nameResolver->getFds(&rfds, &wfds);
  153. // TODO force error if fd == 0
  154. if(fdmax < fd) {
  155. fdmax = fd;
  156. }
  157. }
  158. #endif // ENABLE_ASYNC_DNS
  159. tv.tv_sec = _noWait ? 0 : 1;
  160. tv.tv_usec = 0;
  161. int retval = select(fdmax+1, &rfds, &wfds, NULL, &tv);
  162. if(retval > 0) {
  163. for(SocketEntries::iterator itr = socketEntries.begin();
  164. itr != socketEntries.end(); ++itr) {
  165. SocketEntry& entry = *itr;
  166. if(FD_ISSET(entry.socket->getSockfd(), &rfds) ||
  167. FD_ISSET(entry.socket->getSockfd(), &wfds)) {
  168. entry.command->setStatusActive();
  169. }
  170. }
  171. }
  172. #ifdef ENABLE_ASYNC_DNS
  173. for(AsyncNameResolverEntries::iterator itr = nameResolverEntries.begin();
  174. itr != nameResolverEntries.end(); ++itr) {
  175. AsyncNameResolverEntry& entry = *itr;
  176. entry.nameResolver->process(&rfds, &wfds);
  177. switch(entry.nameResolver->getStatus()) {
  178. case AsyncNameResolver::STATUS_SUCCESS:
  179. case AsyncNameResolver::STATUS_ERROR:
  180. entry.command->setStatusActive();
  181. break;
  182. default:
  183. break;
  184. }
  185. }
  186. #endif // ENABLE_ASYNC_DNS
  187. }
  188. void DownloadEngine::updateFdSet() {
  189. fdmax = 0;
  190. FD_ZERO(&rfdset);
  191. FD_ZERO(&wfdset);
  192. for(SocketEntries::iterator itr = socketEntries.begin();
  193. itr != socketEntries.end(); ++itr) {
  194. SocketEntry& entry = *itr;
  195. int fd = entry.socket->getSockfd();
  196. switch(entry.type) {
  197. case SocketEntry::TYPE_RD:
  198. FD_SET(fd, &rfdset);
  199. break;
  200. case SocketEntry::TYPE_WR:
  201. FD_SET(fd, &wfdset);
  202. break;
  203. }
  204. if(fdmax < fd) {
  205. fdmax = fd;
  206. }
  207. }
  208. }
  209. bool DownloadEngine::addSocket(const SocketEntry& entry) {
  210. SocketEntries::iterator itr =
  211. std::find(socketEntries.begin(), socketEntries.end(), entry);
  212. if(itr == socketEntries.end()) {
  213. socketEntries.push_back(entry);
  214. updateFdSet();
  215. return true;
  216. } else {
  217. return false;
  218. }
  219. }
  220. bool DownloadEngine::deleteSocket(const SocketEntry& entry) {
  221. SocketEntries::iterator itr =
  222. std::find(socketEntries.begin(), socketEntries.end(), entry);
  223. if(itr == socketEntries.end()) {
  224. return false;
  225. } else {
  226. socketEntries.erase(itr);
  227. updateFdSet();
  228. return true;
  229. }
  230. }
  231. bool DownloadEngine::addSocketForReadCheck(const SocketHandle& socket,
  232. Command* command) {
  233. SocketEntry entry(socket, command, SocketEntry::TYPE_RD);
  234. return addSocket(entry);
  235. }
  236. bool DownloadEngine::deleteSocketForReadCheck(const SocketHandle& socket,
  237. Command* command) {
  238. SocketEntry entry(socket, command, SocketEntry::TYPE_RD);
  239. return deleteSocket(entry);
  240. }
  241. bool DownloadEngine::addSocketForWriteCheck(const SocketHandle& socket,
  242. Command* command) {
  243. SocketEntry entry(socket, command, SocketEntry::TYPE_WR);
  244. return addSocket(entry);
  245. }
  246. bool DownloadEngine::deleteSocketForWriteCheck(const SocketHandle& socket,
  247. Command* command) {
  248. SocketEntry entry(socket, command, SocketEntry::TYPE_WR);
  249. return deleteSocket(entry);
  250. }
  251. void DownloadEngine::calculateStatistics()
  252. {
  253. if(!_statCalc.isNull()) {
  254. _statCalc->calculateStat(_requestGroupMan, _fileAllocationMan, _checkIntegrityMan);
  255. }
  256. }
  257. void DownloadEngine::onEndOfRun()
  258. {
  259. _requestGroupMan->closeFile();
  260. _requestGroupMan->save();
  261. }
  262. void DownloadEngine::afterEachIteration()
  263. {
  264. if(globalHaltRequested == 1) {
  265. logger->notice(_("Shutdown sequence commencing... Press Ctrl-C again for emergency shutdown."));
  266. requestHalt();
  267. globalHaltRequested = 2;
  268. } else if(globalHaltRequested == 3) {
  269. logger->notice(_("Emergency shutdown sequence commencing..."));
  270. _requestGroupMan->forceHalt();
  271. globalHaltRequested = 4;
  272. }
  273. }
  274. void DownloadEngine::requestHalt()
  275. {
  276. _haltRequested = true;
  277. _requestGroupMan->halt();
  278. }
  279. void DownloadEngine::fillCommand()
  280. {
  281. std::deque<Command*> commands;
  282. _requestGroupMan->getInitialCommands(commands, this);
  283. addCommand(commands);
  284. }
  285. void DownloadEngine::setStatCalc(const StatCalcHandle& statCalc)
  286. {
  287. _statCalc = statCalc;
  288. }
  289. void DownloadEngine::addCommand(const Commands& commands)
  290. {
  291. this->commands.insert(this->commands.end(), commands.begin(), commands.end());
  292. }
  293. #ifdef ENABLE_ASYNC_DNS
  294. bool DownloadEngine::addNameResolverCheck
  295. (const SharedHandle<AsyncNameResolver>& resolver,
  296. Command* command)
  297. {
  298. AsyncNameResolverEntry entry(resolver, command);
  299. AsyncNameResolverEntries::iterator itr =
  300. std::find(nameResolverEntries.begin(), nameResolverEntries.end(), entry);
  301. if(itr == nameResolverEntries.end()) {
  302. nameResolverEntries.push_back(entry);
  303. return true;
  304. } else {
  305. return false;
  306. }
  307. }
  308. bool DownloadEngine::deleteNameResolverCheck
  309. (const SharedHandle<AsyncNameResolver>& resolver,
  310. Command* command)
  311. {
  312. AsyncNameResolverEntry entry(resolver, command);
  313. AsyncNameResolverEntries::iterator itr =
  314. std::find(nameResolverEntries.begin(), nameResolverEntries.end(), entry);
  315. if(itr == nameResolverEntries.end()) {
  316. return false;
  317. } else {
  318. nameResolverEntries.erase(itr);
  319. return true;
  320. }
  321. }
  322. #endif // ENABLE_ASYNC_DNS
  323. void DownloadEngine::setNoWait(bool b)
  324. {
  325. _noWait = b;
  326. }
  327. void DownloadEngine::addRoutineCommand(Command* command)
  328. {
  329. _routineCommands.push_back(command);
  330. }
  331. void DownloadEngine::poolSocket(const std::string& ipaddr, uint16_t port,
  332. const SharedHandle<SocketCore>& sock,
  333. time_t timeout)
  334. {
  335. std::string addr = ipaddr+":"+Util::uitos(port);
  336. logger->info("Pool socket for %s", addr.c_str());
  337. SocketPoolEntry e(sock, timeout);
  338. std::multimap<std::string, SocketPoolEntry>::value_type p(addr, e);
  339. _socketPool.insert(p);
  340. }
  341. SharedHandle<SocketCore>
  342. DownloadEngine::popPooledSocket(const std::string& ipaddr, uint16_t port)
  343. {
  344. SharedHandle<SocketCore> s;
  345. std::string addr = ipaddr+":"+Util::uitos(port);
  346. std::multimap<std::string, SocketPoolEntry>::iterator first = _socketPool.find(addr);
  347. for(std::multimap<std::string, SocketPoolEntry>::iterator i = first;
  348. i != _socketPool.end() && (*i).first == addr; ++i) {
  349. const SocketPoolEntry& e = (*i).second;
  350. if(!e.isTimeout()) {
  351. logger->info("Reuse socket for %s", addr.c_str());
  352. s = e.getSocket();
  353. _socketPool.erase(first, ++i);
  354. break;
  355. }
  356. }
  357. return s;
  358. }
  359. SharedHandle<SocketCore>
  360. DownloadEngine::popPooledSocket
  361. (const std::deque<std::string>& ipaddrs, uint16_t port)
  362. {
  363. for(std::deque<std::string>::const_iterator i = ipaddrs.begin();
  364. i != ipaddrs.end(); ++i) {
  365. SharedHandle<SocketCore> s = popPooledSocket(*i, port);
  366. if(!s.isNull()) {
  367. return s;
  368. }
  369. }
  370. return SharedHandle<SocketCore>();
  371. }
  372. DownloadEngine::SocketPoolEntry::SocketPoolEntry
  373. (const SharedHandle<SocketCore>& socket,
  374. time_t timeout):
  375. _socket(socket),
  376. _timeout(timeout) {}
  377. DownloadEngine::SocketPoolEntry::~SocketPoolEntry() {}
  378. bool DownloadEngine::SocketPoolEntry::isTimeout() const
  379. {
  380. return _registeredTime.elapsed(_timeout);
  381. }
  382. SharedHandle<SocketCore> DownloadEngine::SocketPoolEntry::getSocket() const
  383. {
  384. return _socket;
  385. }
  386. } // namespace aria2