EpollEventPoll.cc 9.7 KB

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