EpollEventPoll.cc 9.5 KB

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