tc_epoller.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656
  1. #include "util/tc_epoller.h"
  2. #include "util/tc_timeprovider.h"
  3. #include "util/tc_logger.h"
  4. #include <algorithm>
  5. #if TARGET_PLATFORM_WINDOWS
  6. #include "sys/epoll.h"
  7. #else
  8. #include <unistd.h>
  9. #endif
  10. namespace tars
  11. {
  12. TC_Epoller::NotifyInfo::~NotifyInfo()
  13. {
  14. if(_epollInfo && _epoller)
  15. {
  16. // LOG_CONSOLE_DEBUG << this << ", fd:" << notifyFd() << endl;
  17. _epoller->releaseEpollInfo(_epollInfo);
  18. _notify.close();
  19. _epollInfo = NULL;
  20. _epoller = NULL;
  21. }
  22. }
  23. void TC_Epoller::NotifyInfo::init(TC_Epoller *epoller)
  24. {
  25. _epoller = epoller;
  26. //用udp句柄, 方便唤醒, tcp句柄还得构建连接后才能唤醒
  27. _notify.createSocket(SOCK_DGRAM, AF_INET);
  28. _epollInfo = _epoller->createEpollInfo(notifyFd());
  29. // LOG_CONSOLE_DEBUG << this << ", fd:" << notifyFd() << endl;
  30. }
  31. /////////////////////////////////////////////////////////////////////
  32. TC_Epoller::EpollInfo::~EpollInfo()
  33. {
  34. // LOG_CONSOLE_DEBUG << this << endl;
  35. clearCallback();
  36. if(_deconstructor)
  37. {
  38. _deconstructor(_cookie);
  39. _cookie = NULL;
  40. }
  41. }
  42. void TC_Epoller::EpollInfo::clearCallback()
  43. {
  44. _callbacks[0] = EVENT_CALLBACK();
  45. _callbacks[1] = EVENT_CALLBACK();
  46. _callbacks[2] = EVENT_CALLBACK();
  47. }
  48. void TC_Epoller::EpollInfo::registerCallback(const map<uint32_t, EVENT_CALLBACK> & callbacks, uint32_t events)
  49. {
  50. for(auto it : callbacks)
  51. {
  52. switch(it.first)
  53. {
  54. case EPOLLIN:
  55. _callbacks[0] = it.second;
  56. break;
  57. case EPOLLOUT:
  58. _callbacks[1] = it.second;
  59. break;
  60. case EPOLLERR:
  61. _callbacks[2] = it.second;
  62. break;
  63. }
  64. }
  65. if(events != 0)
  66. {
  67. add(events);
  68. }
  69. }
  70. bool TC_Epoller::EpollInfo::fireEvent(uint32_t event)
  71. {
  72. try
  73. {
  74. auto data = shared_from_this();
  75. if((event & EPOLLERR) && _callbacks[2])
  76. {
  77. _callbacks[2](data);
  78. return false;
  79. }
  80. if((event & EPOLLIN) && _callbacks[0])
  81. {
  82. if (!_callbacks[0](data))
  83. return false;
  84. }
  85. if((event & EPOLLOUT) && _callbacks[1])
  86. {
  87. if (!_callbacks[1](data))
  88. return false;
  89. }
  90. }
  91. catch(exception &ex)
  92. {
  93. cerr << "TC_Epoller::EpollInfo::fireEvent event:" << event << ", error: " << ex.what() << endl;
  94. return false;
  95. }
  96. catch(...)
  97. {
  98. cerr << "TC_Epoller::EpollInfo::fireEvent event:" << event << ", error." << endl;
  99. return false;
  100. }
  101. return true;
  102. }
  103. void TC_Epoller::EpollInfo::release()
  104. {
  105. if(this->valid())
  106. {
  107. assert(_epoller);
  108. //epoll不再关注该事件
  109. del(0);
  110. _fd = INVALID_SOCKET;
  111. }
  112. }
  113. void TC_Epoller::EpollInfo::add(uint32_t events)
  114. {
  115. if(valid())
  116. {
  117. _epoller->add(_fd, data(), events);
  118. }
  119. }
  120. void TC_Epoller::EpollInfo::mod(uint32_t events)
  121. {
  122. if(valid())
  123. {
  124. _epoller->mod(_fd, data(), events);
  125. }
  126. }
  127. void TC_Epoller::EpollInfo::del(uint32_t events)
  128. {
  129. if(valid())
  130. {
  131. _epoller->del(_fd, 0, events);
  132. }
  133. }
  134. //////////////////////////////////////////////////////////////////////
  135. TC_Epoller::TC_Epoller()
  136. {
  137. #if TARGET_PLATFORM_WINDOWS
  138. _iEpollfd = NULL;
  139. #else
  140. _iEpollfd = -1;
  141. #endif
  142. _pevs = nullptr;
  143. _max_connections = 1024;
  144. }
  145. TC_Epoller::~TC_Epoller()
  146. {
  147. if(_notify != nullptr)
  148. {
  149. delete _notify;
  150. _notify = nullptr;
  151. }
  152. if(_pevs != nullptr)
  153. {
  154. delete[] _pevs;
  155. _pevs = nullptr;
  156. }
  157. clear();
  158. _idleCallbacks.clear();
  159. #if TARGET_PLATFORM_WINDOWS
  160. if (_iEpollfd != NULL)
  161. {
  162. epoll_close(_iEpollfd);
  163. _iEpollfd = NULL;
  164. }
  165. #else
  166. if (_iEpollfd >= 0)
  167. {
  168. ::close(_iEpollfd);
  169. _iEpollfd = -1;
  170. }
  171. #endif
  172. }
  173. #if TARGET_PLATFORM_IOS
  174. int TC_Epoller::ctrl(SOCKET_TYPE fd, uint64_t data, uint32_t events, int op)
  175. {
  176. if(fd < 0) return -1;
  177. int n = 0;
  178. struct kevent64_s ev[2];
  179. if(_enableET)
  180. {
  181. op = op | EV_CLEAR;
  182. }
  183. if (events & EPOLLIN)
  184. {
  185. EV_SET64(&ev[n++], fd, EVFILT_READ, op, 0, 0, data, 0, 0);
  186. }
  187. if (events & EPOLLOUT)
  188. {
  189. EV_SET64(&ev[n++], fd, EVFILT_WRITE, op, 0, 0, data, 0, 0);
  190. }
  191. int ret = kevent64(_iEpollfd, ev, n, nullptr, 0, 0, nullptr);
  192. if(ret == -1)
  193. {
  194. //一般都是析构的时候出现,有需要close就行
  195. // cerr << "[TC_Epoller::ctrl] error, fd:" << fd << ", errno:" << errno << "|"<< strerror(errno) << endl;
  196. close();
  197. }
  198. return ret;
  199. }
  200. #else
  201. int TC_Epoller::ctrl(SOCKET_TYPE fd, uint64_t data, uint32_t events, int op)
  202. {
  203. struct epoll_event ev;
  204. ev.data.u64 = data;
  205. #if TARGET_PLATFORM_WINDOWS
  206. ev.events = events;
  207. #else
  208. if(_enableET)
  209. {
  210. ev.events = events | EPOLLET;
  211. }
  212. else
  213. {
  214. ev.events = events;
  215. }
  216. #endif
  217. return epoll_ctl(_iEpollfd, op, fd, &ev);
  218. }
  219. #endif
  220. void TC_Epoller::create(int size, bool createNotify)
  221. {
  222. #if TARGET_PLATFORM_IOS
  223. _iEpollfd = kqueue();
  224. #else
  225. _iEpollfd = epoll_create(size);
  226. #endif
  227. if (nullptr != _pevs)
  228. {
  229. delete[] _pevs;
  230. }
  231. _max_connections = 128;
  232. _pevs = new epoll_event[_max_connections];
  233. if(createNotify)
  234. {
  235. if (_notify != NULL)
  236. {
  237. delete _notify;
  238. _notify = NULL;
  239. }
  240. _notify = new NotifyInfo();
  241. _notify->init(this);
  242. _notify->getEpollInfo()->add(EPOLLIN);
  243. }
  244. }
  245. void TC_Epoller::close()
  246. {
  247. if(_notify != nullptr)
  248. {
  249. delete _notify;
  250. _notify = nullptr;
  251. }
  252. #if TARGET_PLATFORM_LINUX || TARGET_PLATFORM_IOS
  253. ::close(_iEpollfd);
  254. _iEpollfd = -1;
  255. #else
  256. epoll_close(_iEpollfd);
  257. _iEpollfd = NULL;
  258. #endif
  259. }
  260. shared_ptr<TC_Epoller::EpollInfo> TC_Epoller::createEpollInfo(SOCKET_TYPE fd)
  261. {
  262. return std::make_shared<TC_Epoller::EpollInfo>(this, fd);
  263. }
  264. void TC_Epoller::releaseEpollInfo(const shared_ptr<TC_Epoller::EpollInfo> &epollInfo)
  265. {
  266. if(epollInfo)
  267. {
  268. // epollInfo->clearCallback(); //may cause epoll crash
  269. epollInfo->release();
  270. }
  271. }
  272. void TC_Epoller::add(SOCKET_TYPE fd, uint64_t data, uint32_t events)
  273. {
  274. #if TARGET_PLATFORM_IOS
  275. ctrl(fd, data, events, EV_ADD|EV_ENABLE);
  276. #else
  277. ctrl(fd, data, events, EPOLL_CTL_ADD);
  278. #endif
  279. }
  280. void TC_Epoller::mod(SOCKET_TYPE fd, uint64_t data, uint32_t events)
  281. {
  282. #if TARGET_PLATFORM_IOS
  283. ctrl(fd, data, events, EV_ADD|EV_ENABLE);
  284. #else
  285. ctrl(fd, data, events, EPOLL_CTL_MOD);
  286. #endif
  287. }
  288. void TC_Epoller::del(SOCKET_TYPE fd, uint64_t data, uint32_t events)
  289. {
  290. #if TARGET_PLATFORM_IOS
  291. ctrl(fd, data, events, EV_DELETE);
  292. #else
  293. ctrl(fd, data, events, EPOLL_CTL_DEL);
  294. #endif
  295. }
  296. epoll_event& TC_Epoller::get(int i)
  297. {
  298. assert(_pevs != 0);
  299. return _pevs[i];
  300. }
  301. int TC_Epoller::wait(int millsecond)
  302. {
  303. //#if !TARGET_PLATFORM_WINDOWS
  304. //retry:
  305. //#endif
  306. int ret;
  307. #if TARGET_PLATFORM_IOS
  308. struct timespec timeout;
  309. timeout.tv_sec = millsecond / 1000;
  310. timeout.tv_nsec = (millsecond % 1000) * 1000 * 1000;
  311. ret = kevent64(_iEpollfd, nullptr, 0, _pevs, _max_connections, 0, &timeout);
  312. #else
  313. ret = epoll_wait(_iEpollfd, _pevs, _max_connections, millsecond);
  314. #endif
  315. #if TARGET_PLATFORM_WINDOWS
  316. return ret;
  317. #else
  318. if(ret < 0 && errno == EINTR)
  319. {
  320. return 0;
  321. // goto retry;
  322. }
  323. return ret;
  324. #endif
  325. }
  326. bool TC_Epoller::readEvent(const epoll_event &ev)
  327. {
  328. #if TARGET_PLATFORM_IOS
  329. if (ev.filter == EVFILT_READ)
  330. #else
  331. if (ev.events & EPOLLIN)
  332. #endif
  333. {
  334. return true;
  335. }
  336. return false;
  337. }
  338. bool TC_Epoller::writeEvent(const epoll_event &ev)
  339. {
  340. #if TARGET_PLATFORM_IOS
  341. if (ev.filter == EVFILT_WRITE)
  342. #else
  343. if (ev.events & EPOLLOUT)
  344. #endif
  345. {
  346. return true;
  347. }
  348. return false;
  349. }
  350. bool TC_Epoller::errorEvent(const epoll_event &ev)
  351. {
  352. #if TARGET_PLATFORM_IOS
  353. if (ev.filter == EVFILT_EXCEPT)
  354. {
  355. return true;
  356. }
  357. #else
  358. if (ev.events & EPOLLERR || ev.events & EPOLLHUP)
  359. {
  360. return true;
  361. }
  362. #endif
  363. return false;
  364. }
  365. uint32_t TC_Epoller::getU32(const epoll_event &ev, bool high)
  366. {
  367. uint32_t u32 = 0;
  368. if(high)
  369. {
  370. #if TARGET_PLATFORM_IOS
  371. u32 = ev.udata >> 32;
  372. #else
  373. u32 = ev.data.u64 >> 32;
  374. #endif
  375. }
  376. else
  377. {
  378. #if TARGET_PLATFORM_IOS
  379. u32 = (uint32_t)ev.udata;
  380. #else
  381. u32 = ev.data.u32;
  382. #endif
  383. }
  384. return u32;
  385. }
  386. uint64_t TC_Epoller::getU64(const epoll_event &ev)
  387. {
  388. uint64_t data;
  389. #if TARGET_PLATFORM_IOS
  390. data = ev.udata;
  391. #else
  392. data = ev.data.u64;
  393. #endif
  394. return data;
  395. }
  396. void TC_Epoller::terminate()
  397. {
  398. //清空定时任务
  399. clear();
  400. _terminate = true;
  401. notify();
  402. }
  403. void TC_Epoller::reset()
  404. {
  405. clear();
  406. _terminate = false;
  407. }
  408. void TC_Epoller::syncCallback(const std::function<void()>& func, int64_t millseconds)
  409. {
  410. TC_Epoller::NotifyInfo syncNotify;
  411. shared_ptr<std::mutex> syncMutex = std::make_shared<std::mutex>();
  412. shared_ptr<std::condition_variable> syncCond = std::make_shared<std::condition_variable>();
  413. syncNotify.init(this);
  414. map<uint32_t, TC_Epoller::EpollInfo::EVENT_CALLBACK> callbacks;
  415. callbacks[EPOLLOUT] = [&](const shared_ptr<TC_Epoller::EpollInfo> &data)
  416. {
  417. try
  418. {
  419. func();
  420. }
  421. catch (...)
  422. {
  423. }
  424. std::unique_lock<std::mutex> lock(*syncMutex.get());
  425. syncCond->notify_one();
  426. return false;
  427. };
  428. std::unique_lock<std::mutex> lock(*syncMutex.get());
  429. syncNotify.getEpollInfo()->registerCallback(callbacks, EPOLLOUT);
  430. if (millseconds >= 0)
  431. {
  432. syncCond->wait_for(lock, std::chrono::milliseconds(millseconds));
  433. }
  434. else
  435. {
  436. syncCond->wait(lock);
  437. }
  438. }
  439. void TC_Epoller::asyncCallback(const std::function<void()>& func)
  440. {
  441. TC_Epoller::NotifyInfo *syncNotify = new TC_Epoller::NotifyInfo();
  442. syncNotify->init(this);
  443. syncNotify->getEpollInfo()->cookie(syncNotify, [](void *p)
  444. {
  445. TC_Epoller::NotifyInfo *ni = (TC_Epoller::NotifyInfo *)p;
  446. delete ni;
  447. });
  448. map<uint32_t, TC_Epoller::EpollInfo::EVENT_CALLBACK> callbacks;
  449. callbacks[EPOLLOUT] = [=](const shared_ptr<TC_Epoller::EpollInfo> &data)
  450. {
  451. try { func(); } catch(...) {}
  452. //释放到自己的owner, 这样才回保证EpollInfo被自动释放
  453. syncNotify->getEpollInfo().reset();
  454. return false;
  455. };
  456. syncNotify->getEpollInfo()->registerCallback(callbacks, EPOLLOUT);
  457. }
  458. void TC_Epoller::notify()
  459. {
  460. if(_notify)
  461. {
  462. _notify->getEpollInfo()->mod(EPOLLOUT);
  463. }
  464. }
  465. void TC_Epoller::onAddTimer()
  466. {
  467. notify();
  468. }
  469. void TC_Epoller::onFireEvent(std::function<void()> func)
  470. {
  471. try {func();} catch(...){}
  472. }
  473. void TC_Epoller::done(uint64_t ms)
  474. {
  475. // LOG_CONSOLE_DEBUG << "fireEvents: " << ms << endl;
  476. //触发定时事件
  477. int64_t nextTimer = fireEvents(ms);
  478. // LOG_CONSOLE_DEBUG << "wait: " << ms << ", " << ms - TNOWMS << endl;
  479. int num = wait(nextTimer);
  480. list<shared_ptr<EpollInfo>> delEpollInfo;
  481. //先处理epoll的网络事件
  482. for (int i = 0; i < num; ++i)
  483. {
  484. if(_terminate)
  485. return;
  486. const epoll_event& ev = get(i);
  487. EpollInfo *info = (EpollInfo*)TC_Epoller::getU64(ev);
  488. if(info == NULL || !info->valid())
  489. {
  490. continue;
  491. }
  492. if(info->_epoller != this)
  493. {
  494. //not current epoller, not process(should not be here!!!!)
  495. continue;
  496. }
  497. // assert(info->_epoller == this);
  498. //返回成智能指针, 保证EpollInfo fireEvent的过程中, 不会被释放掉
  499. auto data = info->shared_from_this();
  500. if(data->_callback)
  501. {
  502. try {data->_callback(data); } catch(exception &ex) {}
  503. }
  504. uint32_t events = 0;
  505. if (TC_Epoller::errorEvent(ev))
  506. {
  507. events = EPOLLERR;
  508. }
  509. else
  510. {
  511. if (TC_Epoller::writeEvent(ev)) {
  512. events |= EPOLLOUT;
  513. }
  514. if (TC_Epoller::readEvent(ev))
  515. {
  516. events |= EPOLLIN;
  517. }
  518. }
  519. if(!data->fireEvent(events))
  520. {
  521. delEpollInfo.push_back(data);
  522. data->release();
  523. }
  524. }
  525. std::for_each(_idleCallbacks.begin(), _idleCallbacks.end(), [](const std::function<void()> &f){
  526. try {f();} catch(...){}
  527. });
  528. }
  529. void TC_Epoller::loop(uint64_t ms)
  530. {
  531. while(!_terminate)
  532. {
  533. this->done(ms);
  534. }
  535. }
  536. }