EpollEventPoll.cc 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. /* <!-- copyright */
  2. /*
  3. * aria2 - The high speed download utility
  4. *
  5. * Copyright (C) 2009 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 "EpollEventPoll.h"
  36. #include <cstring>
  37. #include <algorithm>
  38. #include <numeric>
  39. #include "Command.h"
  40. #include "LogFactory.h"
  41. #include "Logger.h"
  42. namespace aria2 {
  43. EpollEventPoll::KSocketEntry::KSocketEntry(sock_t s):
  44. SocketEntry<KCommandEvent, KADNSEvent>(s) {}
  45. int accumulateEvent(int events, const EpollEventPoll::KEvent& event)
  46. {
  47. return events|event.getEvents();
  48. }
  49. struct epoll_event EpollEventPoll::KSocketEntry::getEvents()
  50. {
  51. struct epoll_event epEvent;
  52. memset(&epEvent, 0, sizeof(struct epoll_event));
  53. epEvent.data.ptr = this;
  54. #ifdef ENABLE_ASYNC_DNS
  55. epEvent.events =
  56. std::accumulate(adnsEvents_.begin(),
  57. adnsEvents_.end(),
  58. std::accumulate(commandEvents_.begin(),
  59. commandEvents_.end(), 0, accumulateEvent),
  60. accumulateEvent);
  61. #else // !ENABLE_ASYNC_DNS
  62. epEvent.events =
  63. std::accumulate(commandEvents_.begin(), commandEvents_.end(), 0,
  64. accumulateEvent);
  65. #endif // !ENABLE_ASYNC_DNS
  66. return epEvent;
  67. }
  68. EpollEventPoll::EpollEventPoll():
  69. epEventsSize_(EPOLL_EVENTS_MAX),
  70. epEvents_(new struct epoll_event[epEventsSize_]),
  71. logger_(LogFactory::getInstance())
  72. {
  73. epfd_ = epoll_create(EPOLL_EVENTS_MAX);
  74. }
  75. EpollEventPoll::~EpollEventPoll()
  76. {
  77. if(epfd_ != -1) {
  78. int r;
  79. while((r = close(epfd_)) == -1 && errno == EINTR);
  80. if(r == -1) {
  81. logger_->error("Error occurred while closing epoll file descriptor"
  82. " %d: %s",
  83. epfd_, strerror(errno));
  84. }
  85. }
  86. delete [] epEvents_;
  87. }
  88. bool EpollEventPoll::good() const
  89. {
  90. return epfd_ != -1;
  91. }
  92. void EpollEventPoll::poll(const struct timeval& tv)
  93. {
  94. // timeout is millisec
  95. int timeout = tv.tv_sec*1000+tv.tv_usec/1000;
  96. int res;
  97. while((res = epoll_wait(epfd_, epEvents_, EPOLL_EVENTS_MAX, timeout)) == -1 &&
  98. errno == EINTR);
  99. if(res > 0) {
  100. for(int i = 0; i < res; ++i) {
  101. KSocketEntry* p = reinterpret_cast<KSocketEntry*>(epEvents_[i].data.ptr);
  102. p->processEvents(epEvents_[i].events);
  103. }
  104. }
  105. #ifdef ENABLE_ASYNC_DNS
  106. // It turns out that we have to call ares_process_fd before ares's
  107. // own timeout and ares may create new sockets or closes socket in
  108. // their API. So we call ares_process_fd for all ares_channel and
  109. // re-register their sockets.
  110. for(std::deque<SharedHandle<KAsyncNameResolverEntry> >::iterator i =
  111. nameResolverEntries_.begin(), eoi = nameResolverEntries_.end();
  112. i != eoi; ++i) {
  113. (*i)->processTimeout();
  114. (*i)->removeSocketEvents(this);
  115. (*i)->addSocketEvents(this);
  116. }
  117. #endif // ENABLE_ASYNC_DNS
  118. // TODO timeout of name resolver is determined in Command(AbstractCommand,
  119. // DHTEntryPoint...Command)
  120. }
  121. static int translateEvents(EventPoll::EventType events)
  122. {
  123. int newEvents = 0;
  124. if(EventPoll::EVENT_READ&events) {
  125. newEvents |= EPOLLIN;
  126. }
  127. if(EventPoll::EVENT_WRITE&events) {
  128. newEvents |= EPOLLOUT;
  129. }
  130. if(EventPoll::EVENT_ERROR&events) {
  131. newEvents |= EPOLLERR;
  132. }
  133. if(EventPoll::EVENT_HUP&events) {
  134. newEvents |= EPOLLHUP;
  135. }
  136. return newEvents;
  137. }
  138. bool EpollEventPoll::addEvents(sock_t socket,
  139. const EpollEventPoll::KEvent& event)
  140. {
  141. SharedHandle<KSocketEntry> socketEntry(new KSocketEntry(socket));
  142. std::deque<SharedHandle<KSocketEntry> >::iterator i =
  143. std::lower_bound(socketEntries_.begin(), socketEntries_.end(), socketEntry);
  144. int r = 0;
  145. if(i != socketEntries_.end() && (*i) == socketEntry) {
  146. event.addSelf(*i);
  147. struct epoll_event epEvent = (*i)->getEvents();
  148. r = epoll_ctl(epfd_, EPOLL_CTL_MOD, (*i)->getSocket(), &epEvent);
  149. if(r == -1) {
  150. // try EPOLL_CTL_ADD: There is a chance that previously socket X is
  151. // added to epoll, but it is closed and is not yet removed from
  152. // SocketEntries. In this case, EPOLL_CTL_MOD is failed with ENOENT.
  153. r = epoll_ctl(epfd_, EPOLL_CTL_ADD, (*i)->getSocket(),
  154. &epEvent);
  155. }
  156. } else {
  157. socketEntries_.insert(i, socketEntry);
  158. if(socketEntries_.size() > epEventsSize_) {
  159. epEventsSize_ *= 2;
  160. delete [] epEvents_;
  161. epEvents_ = new struct epoll_event[epEventsSize_];
  162. }
  163. event.addSelf(socketEntry);
  164. struct epoll_event epEvent = socketEntry->getEvents();
  165. r = epoll_ctl(epfd_, EPOLL_CTL_ADD, socketEntry->getSocket(), &epEvent);
  166. }
  167. if(r == -1) {
  168. if(logger_->debug()) {
  169. logger_->debug("Failed to add socket event %d:%s",
  170. socket, strerror(errno));
  171. }
  172. return false;
  173. } else {
  174. return true;
  175. }
  176. }
  177. bool EpollEventPoll::addEvents(sock_t socket, Command* command,
  178. EventPoll::EventType events)
  179. {
  180. int epEvents = translateEvents(events);
  181. return addEvents(socket, KCommandEvent(command, epEvents));
  182. }
  183. #ifdef ENABLE_ASYNC_DNS
  184. bool EpollEventPoll::addEvents(sock_t socket, Command* command, int events,
  185. const SharedHandle<AsyncNameResolver>& rs)
  186. {
  187. return addEvents(socket, KADNSEvent(rs, command, socket, events));
  188. }
  189. #endif // ENABLE_ASYNC_DNS
  190. bool EpollEventPoll::deleteEvents(sock_t socket,
  191. const EpollEventPoll::KEvent& event)
  192. {
  193. SharedHandle<KSocketEntry> socketEntry(new KSocketEntry(socket));
  194. std::deque<SharedHandle<KSocketEntry> >::iterator i =
  195. std::lower_bound(socketEntries_.begin(), socketEntries_.end(), socketEntry);
  196. if(i != socketEntries_.end() && (*i) == socketEntry) {
  197. event.removeSelf(*i);
  198. int r = 0;
  199. if((*i)->eventEmpty()) {
  200. // In kernel before 2.6.9, epoll_ctl with EPOLL_CTL_DEL requires non-null
  201. // pointer of epoll_event.
  202. struct epoll_event ev = {0,{0}};
  203. r = epoll_ctl(epfd_, EPOLL_CTL_DEL, (*i)->getSocket(), &ev);
  204. socketEntries_.erase(i);
  205. } else {
  206. // If socket is closed, then it seems it is automatically removed from
  207. // epoll, so following EPOLL_CTL_MOD may fail.
  208. struct epoll_event epEvent = (*i)->getEvents();
  209. r = epoll_ctl(epfd_, EPOLL_CTL_MOD, (*i)->getSocket(), &epEvent);
  210. if(r == -1) {
  211. if(logger_->debug()) {
  212. logger_->debug("Failed to delete socket event, but may be ignored:%s",
  213. strerror(errno));
  214. }
  215. }
  216. }
  217. if(r == -1) {
  218. if(logger_->debug()) {
  219. logger_->debug("Failed to delete socket event:%s", strerror(errno));
  220. }
  221. return false;
  222. } else {
  223. return true;
  224. }
  225. } else {
  226. if(logger_->debug()) {
  227. logger_->debug("Socket %d is not found in SocketEntries.", socket);
  228. }
  229. return false;
  230. }
  231. }
  232. #ifdef ENABLE_ASYNC_DNS
  233. bool EpollEventPoll::deleteEvents(sock_t socket, Command* command,
  234. const SharedHandle<AsyncNameResolver>& rs)
  235. {
  236. return deleteEvents(socket, KADNSEvent(rs, command, socket, 0));
  237. }
  238. #endif // ENABLE_ASYNC_DNS
  239. bool EpollEventPoll::deleteEvents(sock_t socket, Command* command,
  240. EventPoll::EventType events)
  241. {
  242. int epEvents = translateEvents(events);
  243. return deleteEvents(socket, KCommandEvent(command, epEvents));
  244. }
  245. #ifdef ENABLE_ASYNC_DNS
  246. bool EpollEventPoll::addNameResolver
  247. (const SharedHandle<AsyncNameResolver>& resolver, Command* command)
  248. {
  249. SharedHandle<KAsyncNameResolverEntry> entry
  250. (new KAsyncNameResolverEntry(resolver, command));
  251. std::deque<SharedHandle<KAsyncNameResolverEntry> >::iterator itr =
  252. std::find(nameResolverEntries_.begin(), nameResolverEntries_.end(), entry);
  253. if(itr == nameResolverEntries_.end()) {
  254. nameResolverEntries_.push_back(entry);
  255. entry->addSocketEvents(this);
  256. return true;
  257. } else {
  258. return false;
  259. }
  260. }
  261. bool EpollEventPoll::deleteNameResolver
  262. (const SharedHandle<AsyncNameResolver>& resolver, Command* command)
  263. {
  264. SharedHandle<KAsyncNameResolverEntry> entry
  265. (new KAsyncNameResolverEntry(resolver, command));
  266. std::deque<SharedHandle<KAsyncNameResolverEntry> >::iterator itr =
  267. std::find(nameResolverEntries_.begin(), nameResolverEntries_.end(), entry);
  268. if(itr == nameResolverEntries_.end()) {
  269. return false;
  270. } else {
  271. (*itr)->removeSocketEvents(this);
  272. nameResolverEntries_.erase(itr);
  273. return true;
  274. }
  275. }
  276. #endif // ENABLE_ASYNC_DNS
  277. } // namespace aria2