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. 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_(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_,
  87. util::safeStrerror(errNum).c_str()));
  88. }
  89. }
  90. }
  91. bool EpollEventPoll::good() const
  92. {
  93. return epfd_ != -1;
  94. }
  95. void EpollEventPoll::poll(const struct timeval& tv)
  96. {
  97. // timeout is millisec
  98. int timeout = tv.tv_sec*1000+tv.tv_usec/1000;
  99. int res;
  100. while((res = epoll_wait(epfd_, epEvents_.get(),
  101. 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(auto& i : nameResolverEntries_) {
  119. auto& ent = i.second;
  120. ent.processTimeout();
  121. ent.removeSocketEvents(this);
  122. ent.addSocketEvents(this);
  123. }
  124. #endif // ENABLE_ASYNC_DNS
  125. // TODO timeout of name resolver is determined in Command(AbstractCommand,
  126. // DHTEntryPoint...Command)
  127. }
  128. namespace {
  129. int translateEvents(EventPoll::EventType events)
  130. {
  131. int newEvents = 0;
  132. if(EventPoll::EVENT_READ&events) {
  133. newEvents |= EPOLLIN;
  134. }
  135. if(EventPoll::EVENT_WRITE&events) {
  136. newEvents |= EPOLLOUT;
  137. }
  138. if(EventPoll::EVENT_ERROR&events) {
  139. newEvents |= EPOLLERR;
  140. }
  141. if(EventPoll::EVENT_HUP&events) {
  142. newEvents |= EPOLLHUP;
  143. }
  144. return newEvents;
  145. }
  146. } // namespace
  147. bool EpollEventPoll::addEvents(sock_t socket,
  148. const EpollEventPoll::KEvent& event)
  149. {
  150. auto i = socketEntries_.lower_bound(socket);
  151. int r = 0;
  152. int errNum = 0;
  153. if(i != std::end(socketEntries_) && (*i).first == socket) {
  154. auto& socketEntry = (*i).second;
  155. event.addSelf(&socketEntry);
  156. struct epoll_event epEvent = socketEntry.getEvents();
  157. r = epoll_ctl(epfd_, EPOLL_CTL_MOD, socketEntry.getSocket(), &epEvent);
  158. if(r == -1) {
  159. // try EPOLL_CTL_ADD: There is a chance that previously socket X is
  160. // added to epoll, but it is closed and is not yet removed from
  161. // SocketEntries. In this case, EPOLL_CTL_MOD is failed with ENOENT.
  162. r = epoll_ctl(epfd_, EPOLL_CTL_ADD, socketEntry.getSocket(),
  163. &epEvent);
  164. errNum = errno;
  165. }
  166. } else {
  167. i = socketEntries_.insert(i, std::make_pair(socket, KSocketEntry(socket)));
  168. auto& socketEntry = (*i).second;
  169. if(socketEntries_.size() > epEventsSize_) {
  170. epEventsSize_ *= 2;
  171. epEvents_ = make_unique<struct epoll_event[]>(epEventsSize_);
  172. }
  173. event.addSelf(&socketEntry);
  174. struct epoll_event epEvent = socketEntry.getEvents();
  175. r = epoll_ctl(epfd_, EPOLL_CTL_ADD, socketEntry.getSocket(), &epEvent);
  176. errNum = errno;
  177. }
  178. if(r == -1) {
  179. A2_LOG_DEBUG(fmt("Failed to add socket event %d:%s",
  180. socket,
  181. util::safeStrerror(errNum).c_str()));
  182. return false;
  183. } else {
  184. return true;
  185. }
  186. }
  187. bool EpollEventPoll::addEvents(sock_t socket, Command* command,
  188. EventPoll::EventType events)
  189. {
  190. int epEvents = translateEvents(events);
  191. return addEvents(socket, KCommandEvent(command, epEvents));
  192. }
  193. #ifdef ENABLE_ASYNC_DNS
  194. bool EpollEventPoll::addEvents(sock_t socket, Command* command, int events,
  195. const std::shared_ptr<AsyncNameResolver>& rs)
  196. {
  197. return addEvents(socket, KADNSEvent(rs, command, socket, events));
  198. }
  199. #endif // ENABLE_ASYNC_DNS
  200. bool EpollEventPoll::deleteEvents(sock_t socket,
  201. const EpollEventPoll::KEvent& event)
  202. {
  203. auto i = socketEntries_.find(socket);
  204. if(i == std::end(socketEntries_)) {
  205. A2_LOG_DEBUG(fmt("Socket %d is not found in SocketEntries.", socket));
  206. return false;
  207. }
  208. auto& socketEntry = (*i).second;
  209. event.removeSelf(&socketEntry);
  210. int r = 0;
  211. int errNum = 0;
  212. if(socketEntry.eventEmpty()) {
  213. // In kernel before 2.6.9, epoll_ctl with EPOLL_CTL_DEL requires non-null
  214. // pointer of epoll_event.
  215. struct epoll_event ev = {0,{0}};
  216. r = epoll_ctl(epfd_, EPOLL_CTL_DEL, socketEntry.getSocket(), &ev);
  217. errNum = errno;
  218. socketEntries_.erase(i);
  219. } else {
  220. // If socket is closed, then it seems it is automatically removed from
  221. // epoll, so following EPOLL_CTL_MOD may fail.
  222. struct epoll_event epEvent = socketEntry.getEvents();
  223. r = epoll_ctl(epfd_, EPOLL_CTL_MOD, socketEntry.getSocket(), &epEvent);
  224. errNum = errno;
  225. if(r == -1) {
  226. A2_LOG_DEBUG(fmt("Failed to delete socket event, but may be ignored:%s",
  227. util::safeStrerror(errNum).c_str()));
  228. }
  229. }
  230. if(r == -1) {
  231. A2_LOG_DEBUG(fmt("Failed to delete socket event:%s",
  232. util::safeStrerror(errNum).c_str()));
  233. return false;
  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