hloop.c 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109
  1. #include "hloop.h"
  2. #include "hevent.h"
  3. #include "iowatcher.h"
  4. #include "hdef.h"
  5. #include "hbase.h"
  6. #include "hlog.h"
  7. #include "hmath.h"
  8. #include "htime.h"
  9. #include "hsocket.h"
  10. #include "hthread.h"
  11. #if defined(OS_UNIX) && HAVE_EVENTFD
  12. #include "sys/eventfd.h"
  13. #endif
  14. #define HLOOP_PAUSE_TIME 10 // ms
  15. #define HLOOP_MAX_BLOCK_TIME 100 // ms
  16. #define HLOOP_STAT_TIMEOUT 60000 // ms
  17. #define IO_ARRAY_INIT_SIZE 1024
  18. #define CUSTOM_EVENT_QUEUE_INIT_SIZE 16
  19. #define EVENTFDS_READ_INDEX 0
  20. #define EVENTFDS_WRITE_INDEX 1
  21. static void __hidle_del(hidle_t* idle);
  22. static void __htimer_del(htimer_t* timer);
  23. static int timers_compare(const struct heap_node* lhs, const struct heap_node* rhs) {
  24. return TIMER_ENTRY(lhs)->next_timeout < TIMER_ENTRY(rhs)->next_timeout;
  25. }
  26. static int hloop_process_idles(hloop_t* loop) {
  27. int nidles = 0;
  28. struct list_node* node = loop->idles.next;
  29. hidle_t* idle = NULL;
  30. while (node != &loop->idles) {
  31. idle = IDLE_ENTRY(node);
  32. node = node->next;
  33. if (idle->repeat != INFINITE) {
  34. --idle->repeat;
  35. }
  36. if (idle->repeat == 0) {
  37. // NOTE: Just mark it as destroy and remove from list.
  38. // Real deletion occurs after hloop_process_pendings.
  39. __hidle_del(idle);
  40. }
  41. EVENT_PENDING(idle);
  42. ++nidles;
  43. }
  44. return nidles;
  45. }
  46. static int __hloop_process_timers(struct heap* timers, uint64_t timeout) {
  47. int ntimers = 0;
  48. htimer_t* timer = NULL;
  49. while (timers->root) {
  50. // NOTE: root of minheap has min timeout.
  51. timer = TIMER_ENTRY(timers->root);
  52. if (timer->next_timeout > timeout) {
  53. break;
  54. }
  55. if (timer->repeat != INFINITE) {
  56. --timer->repeat;
  57. }
  58. if (timer->repeat == 0) {
  59. // NOTE: Just mark it as destroy and remove from heap.
  60. // Real deletion occurs after hloop_process_pendings.
  61. __htimer_del(timer);
  62. }
  63. else {
  64. // NOTE: calc next timeout, then re-insert heap.
  65. heap_dequeue(timers);
  66. if (timer->event_type == HEVENT_TYPE_TIMEOUT) {
  67. while (timer->next_timeout <= timeout) {
  68. timer->next_timeout += (uint64_t)((htimeout_t*)timer)->timeout * 1000;
  69. }
  70. }
  71. else if (timer->event_type == HEVENT_TYPE_PERIOD) {
  72. hperiod_t* period = (hperiod_t*)timer;
  73. timer->next_timeout = (uint64_t)cron_next_timeout(period->minute, period->hour, period->day,
  74. period->week, period->month) * 1000000;
  75. }
  76. heap_insert(timers, &timer->node);
  77. }
  78. EVENT_PENDING(timer);
  79. ++ntimers;
  80. }
  81. return ntimers;
  82. }
  83. static int hloop_process_timers(hloop_t* loop) {
  84. uint64_t now = hloop_now_us(loop);
  85. int ntimers = __hloop_process_timers(&loop->timers, loop->cur_hrtime);
  86. ntimers += __hloop_process_timers(&loop->realtimers, now);
  87. return ntimers;
  88. }
  89. static int hloop_process_ios(hloop_t* loop, int timeout) {
  90. // That is to call IO multiplexing function such as select, poll, epoll, etc.
  91. int nevents = iowatcher_poll_events(loop, timeout);
  92. if (nevents < 0) {
  93. hlogd("poll_events error=%d", -nevents);
  94. }
  95. return nevents < 0 ? 0 : nevents;
  96. }
  97. static int hloop_process_pendings(hloop_t* loop) {
  98. if (loop->npendings == 0) return 0;
  99. hevent_t* cur = NULL;
  100. hevent_t* next = NULL;
  101. int ncbs = 0;
  102. // NOTE: invoke event callback from high to low sorted by priority.
  103. for (int i = HEVENT_PRIORITY_SIZE-1; i >= 0; --i) {
  104. cur = loop->pendings[i];
  105. while (cur) {
  106. next = cur->pending_next;
  107. if (cur->pending) {
  108. if (cur->active && cur->cb) {
  109. cur->cb(cur);
  110. ++ncbs;
  111. }
  112. cur->pending = 0;
  113. // NOTE: Now we can safely delete event marked as destroy.
  114. if (cur->destroy) {
  115. EVENT_DEL(cur);
  116. }
  117. }
  118. cur = next;
  119. }
  120. loop->pendings[i] = NULL;
  121. }
  122. loop->npendings = 0;
  123. return ncbs;
  124. }
  125. // hloop_process_ios -> hloop_process_timers -> hloop_process_idles -> hloop_process_pendings
  126. int hloop_process_events(hloop_t* loop, int timeout_ms) {
  127. // ios -> timers -> idles
  128. int nios, ntimers, nidles;
  129. nios = ntimers = nidles = 0;
  130. // calc blocktime
  131. int32_t blocktime_ms = timeout_ms;
  132. if (loop->ntimers) {
  133. hloop_update_time(loop);
  134. int64_t blocktime_us = blocktime_ms * 1000;
  135. if (loop->timers.root) {
  136. int64_t min_timeout = TIMER_ENTRY(loop->timers.root)->next_timeout - loop->cur_hrtime;
  137. blocktime_us = MIN(blocktime_us, min_timeout);
  138. }
  139. if (loop->realtimers.root) {
  140. int64_t min_timeout = TIMER_ENTRY(loop->realtimers.root)->next_timeout - hloop_now_us(loop);
  141. blocktime_us = MIN(blocktime_us, min_timeout);
  142. }
  143. if (blocktime_us < 0) goto process_timers;
  144. blocktime_ms = blocktime_us / 1000 + 1;
  145. blocktime_ms = MIN(blocktime_ms, timeout_ms);
  146. }
  147. if (loop->nios) {
  148. nios = hloop_process_ios(loop, blocktime_ms);
  149. } else {
  150. hv_msleep(blocktime_ms);
  151. }
  152. hloop_update_time(loop);
  153. // wakeup by hloop_stop
  154. if (loop->status == HLOOP_STATUS_STOP) {
  155. return 0;
  156. }
  157. process_timers:
  158. if (loop->ntimers) {
  159. ntimers = hloop_process_timers(loop);
  160. }
  161. int npendings = loop->npendings;
  162. if (npendings == 0) {
  163. if (loop->nidles) {
  164. nidles= hloop_process_idles(loop);
  165. }
  166. }
  167. int ncbs = hloop_process_pendings(loop);
  168. // printd("blocktime=%d nios=%d/%u ntimers=%d/%u nidles=%d/%u nactives=%d npendings=%d ncbs=%d\n",
  169. // blocktime, nios, loop->nios, ntimers, loop->ntimers, nidles, loop->nidles,
  170. // loop->nactives, npendings, ncbs);
  171. return ncbs;
  172. (void)nios;
  173. }
  174. #ifdef DEBUG
  175. static void hloop_stat_timer_cb(htimer_t* timer) {
  176. hloop_t* loop = timer->loop;
  177. // hlog_set_level(LOG_LEVEL_DEBUG);
  178. hlogd("[loop] pid=%ld tid=%ld uptime=%lluus cnt=%llu nactives=%u nios=%u ntimers=%u nidles=%u",
  179. loop->pid, loop->tid,
  180. (unsigned long long)loop->cur_hrtime - loop->start_hrtime,
  181. (unsigned long long)loop->loop_cnt,
  182. loop->nactives, loop->nios, loop->ntimers, loop->nidles);
  183. }
  184. #endif
  185. static void eventfd_read_cb(hio_t* io, void* buf, int readbytes) {
  186. hloop_t* loop = io->loop;
  187. hevent_t* pev = NULL;
  188. hevent_t ev;
  189. uint64_t count = readbytes;
  190. #if defined(OS_UNIX) && HAVE_EVENTFD
  191. assert(readbytes == sizeof(count));
  192. count = *(uint64_t*)buf;
  193. #endif
  194. for (uint64_t i = 0; i < count; ++i) {
  195. hmutex_lock(&loop->custom_events_mutex);
  196. if (event_queue_empty(&loop->custom_events)) {
  197. goto unlock;
  198. }
  199. pev = event_queue_front(&loop->custom_events);
  200. if (pev == NULL) {
  201. goto unlock;
  202. }
  203. ev = *pev;
  204. event_queue_pop_front(&loop->custom_events);
  205. // NOTE: unlock before cb, avoid deadlock if hloop_post_event called in cb.
  206. hmutex_unlock(&loop->custom_events_mutex);
  207. if (ev.cb) {
  208. ev.cb(&ev);
  209. }
  210. }
  211. return;
  212. unlock:
  213. hmutex_unlock(&loop->custom_events_mutex);
  214. }
  215. static int hloop_create_eventfds(hloop_t* loop) {
  216. #if defined(OS_UNIX) && HAVE_EVENTFD
  217. int efd = eventfd(0, 0);
  218. if (efd < 0) {
  219. hloge("eventfd create failed!");
  220. return -1;
  221. }
  222. loop->eventfds[0] = loop->eventfds[1] = efd;
  223. #elif defined(OS_UNIX) && HAVE_PIPE
  224. if (pipe(loop->eventfds) != 0) {
  225. hloge("pipe create failed!");
  226. return -1;
  227. }
  228. #else
  229. if (Socketpair(AF_INET, SOCK_STREAM, 0, loop->eventfds) != 0) {
  230. hloge("socketpair create failed!");
  231. return -1;
  232. }
  233. #endif
  234. hio_t* io = hread(loop, loop->eventfds[EVENTFDS_READ_INDEX], NULL, 0, eventfd_read_cb);
  235. io->priority = HEVENT_HIGH_PRIORITY;
  236. ++loop->intern_nevents;
  237. return 0;
  238. }
  239. static void hloop_destroy_eventfds(hloop_t* loop) {
  240. #if defined(OS_UNIX) && HAVE_EVENTFD
  241. // NOTE: eventfd has only one fd
  242. SAFE_CLOSE(loop->eventfds[0]);
  243. #elif defined(OS_UNIX) && HAVE_PIPE
  244. SAFE_CLOSE(loop->eventfds[0]);
  245. SAFE_CLOSE(loop->eventfds[1]);
  246. #else
  247. // NOTE: Avoid duplication closesocket in hio_cleanup
  248. // SAFE_CLOSESOCKET(loop->eventfds[EVENTFDS_READ_INDEX]);
  249. SAFE_CLOSESOCKET(loop->eventfds[EVENTFDS_WRITE_INDEX]);
  250. #endif
  251. loop->eventfds[0] = loop->eventfds[1] = -1;
  252. }
  253. void hloop_post_event(hloop_t* loop, hevent_t* ev) {
  254. if (ev->loop == NULL) {
  255. ev->loop = loop;
  256. }
  257. if (ev->event_type == 0) {
  258. ev->event_type = HEVENT_TYPE_CUSTOM;
  259. }
  260. if (ev->event_id == 0) {
  261. ev->event_id = hloop_next_event_id();
  262. }
  263. int nwrite = 0;
  264. uint64_t count = 1;
  265. hmutex_lock(&loop->custom_events_mutex);
  266. if (loop->eventfds[EVENTFDS_WRITE_INDEX] == -1) {
  267. if (hloop_create_eventfds(loop) != 0) {
  268. goto unlock;
  269. }
  270. }
  271. #if defined(OS_UNIX) && HAVE_EVENTFD
  272. nwrite = write(loop->eventfds[EVENTFDS_WRITE_INDEX], &count, sizeof(count));
  273. #elif defined(OS_UNIX) && HAVE_PIPE
  274. nwrite = write(loop->eventfds[EVENTFDS_WRITE_INDEX], "e", 1);
  275. #else
  276. nwrite = send(loop->eventfds[EVENTFDS_WRITE_INDEX], "e", 1, 0);
  277. #endif
  278. if (nwrite <= 0) {
  279. hloge("hloop_post_event failed!");
  280. goto unlock;
  281. }
  282. if (loop->custom_events.maxsize == 0) {
  283. event_queue_init(&loop->custom_events, CUSTOM_EVENT_QUEUE_INIT_SIZE);
  284. }
  285. event_queue_push_back(&loop->custom_events, ev);
  286. unlock:
  287. hmutex_unlock(&loop->custom_events_mutex);
  288. }
  289. static void hloop_init(hloop_t* loop) {
  290. #ifdef OS_WIN
  291. WSAInit();
  292. #endif
  293. #ifdef SIGPIPE
  294. // NOTE: if not ignore SIGPIPE, write twice when peer close will lead to exit process by SIGPIPE.
  295. signal(SIGPIPE, SIG_IGN);
  296. #endif
  297. loop->status = HLOOP_STATUS_STOP;
  298. loop->pid = hv_getpid();
  299. loop->tid = hv_gettid();
  300. // idles
  301. list_init(&loop->idles);
  302. // timers
  303. heap_init(&loop->timers, timers_compare);
  304. heap_init(&loop->realtimers, timers_compare);
  305. // ios
  306. // NOTE: io_array_init when hio_get -> io_array_resize
  307. // io_array_init(&loop->ios, IO_ARRAY_INIT_SIZE);
  308. // readbuf
  309. // NOTE: alloc readbuf when hio_use_loop_readbuf
  310. // loop->readbuf.len = HLOOP_READ_BUFSIZE;
  311. // HV_ALLOC(loop->readbuf.base, loop->readbuf.len);
  312. // NOTE: iowatcher_init when hio_add -> iowatcher_add_event
  313. // iowatcher_init(loop);
  314. // custom_events
  315. hmutex_init(&loop->custom_events_mutex);
  316. // NOTE: hloop_create_eventfds when hloop_post_event or hloop_run
  317. loop->eventfds[0] = loop->eventfds[1] = -1;
  318. // NOTE: init start_time here, because htimer_add use it.
  319. loop->start_ms = gettimeofday_ms();
  320. loop->start_hrtime = loop->cur_hrtime = gethrtime_us();
  321. }
  322. static void hloop_cleanup(hloop_t* loop) {
  323. // pendings
  324. printd("cleanup pendings...\n");
  325. for (int i = 0; i < HEVENT_PRIORITY_SIZE; ++i) {
  326. loop->pendings[i] = NULL;
  327. }
  328. // ios
  329. printd("cleanup ios...\n");
  330. for (int i = 0; i < loop->ios.maxsize; ++i) {
  331. hio_t* io = loop->ios.ptr[i];
  332. if (io) {
  333. hio_free(io);
  334. }
  335. }
  336. io_array_cleanup(&loop->ios);
  337. // idles
  338. printd("cleanup idles...\n");
  339. struct list_node* node = loop->idles.next;
  340. hidle_t* idle;
  341. while (node != &loop->idles) {
  342. idle = IDLE_ENTRY(node);
  343. node = node->next;
  344. HV_FREE(idle);
  345. }
  346. list_init(&loop->idles);
  347. // timers
  348. printd("cleanup timers...\n");
  349. htimer_t* timer;
  350. while (loop->timers.root) {
  351. timer = TIMER_ENTRY(loop->timers.root);
  352. heap_dequeue(&loop->timers);
  353. HV_FREE(timer);
  354. }
  355. heap_init(&loop->timers, NULL);
  356. while (loop->realtimers.root) {
  357. timer = TIMER_ENTRY(loop->realtimers.root);
  358. heap_dequeue(&loop->realtimers);
  359. HV_FREE(timer);
  360. }
  361. heap_init(&loop->realtimers, NULL);
  362. // signals
  363. printd("cleanup signals...\n");
  364. for (int i = 0; i < loop->signals.maxsize; ++i) {
  365. hsignal_t* sig = loop->signals.ptr[i];
  366. HV_FREE(sig);
  367. }
  368. signal_array_cleanup(&loop->signals);
  369. // readbuf
  370. if (loop->readbuf.base && loop->readbuf.len) {
  371. HV_FREE(loop->readbuf.base);
  372. loop->readbuf.base = NULL;
  373. loop->readbuf.len = 0;
  374. }
  375. // iowatcher
  376. iowatcher_cleanup(loop);
  377. // custom_events
  378. hmutex_lock(&loop->custom_events_mutex);
  379. hloop_destroy_eventfds(loop);
  380. event_queue_cleanup(&loop->custom_events);
  381. hmutex_unlock(&loop->custom_events_mutex);
  382. hmutex_destroy(&loop->custom_events_mutex);
  383. }
  384. hloop_t* hloop_new(int flags) {
  385. hloop_t* loop;
  386. HV_ALLOC_SIZEOF(loop);
  387. hloop_init(loop);
  388. loop->flags |= flags;
  389. hlogd("hloop_new tid=%ld", loop->tid);
  390. return loop;
  391. }
  392. void hloop_free(hloop_t** pp) {
  393. if (pp == NULL || *pp == NULL) return;
  394. hloop_t* loop = *pp;
  395. if (loop->status == HLOOP_STATUS_DESTROY) return;
  396. loop->status = HLOOP_STATUS_DESTROY;
  397. hlogd("hloop_free tid=%ld", hv_gettid());
  398. hloop_cleanup(loop);
  399. HV_FREE(loop);
  400. *pp = NULL;
  401. }
  402. // while (loop->status) { hloop_process_events(loop); }
  403. int hloop_run(hloop_t* loop) {
  404. if (loop == NULL) return -1;
  405. if (loop->status == HLOOP_STATUS_RUNNING) return -2;
  406. loop->status = HLOOP_STATUS_RUNNING;
  407. loop->pid = hv_getpid();
  408. loop->tid = hv_gettid();
  409. hlogd("hloop_run tid=%ld", loop->tid);
  410. if (loop->intern_nevents == 0) {
  411. hmutex_lock(&loop->custom_events_mutex);
  412. if (loop->eventfds[EVENTFDS_WRITE_INDEX] == -1) {
  413. hloop_create_eventfds(loop);
  414. }
  415. hmutex_unlock(&loop->custom_events_mutex);
  416. #ifdef DEBUG
  417. htimer_add(loop, hloop_stat_timer_cb, HLOOP_STAT_TIMEOUT, INFINITE);
  418. ++loop->intern_nevents;
  419. #endif
  420. }
  421. while (loop->status != HLOOP_STATUS_STOP) {
  422. if (loop->status == HLOOP_STATUS_PAUSE) {
  423. hv_msleep(HLOOP_PAUSE_TIME);
  424. hloop_update_time(loop);
  425. continue;
  426. }
  427. ++loop->loop_cnt;
  428. if ((loop->flags & HLOOP_FLAG_QUIT_WHEN_NO_ACTIVE_EVENTS) &&
  429. loop->nactives <= loop->intern_nevents) {
  430. break;
  431. }
  432. hloop_process_events(loop, HLOOP_MAX_BLOCK_TIME);
  433. if (loop->flags & HLOOP_FLAG_RUN_ONCE) {
  434. break;
  435. }
  436. }
  437. loop->status = HLOOP_STATUS_STOP;
  438. loop->end_hrtime = gethrtime_us();
  439. if (loop->flags & HLOOP_FLAG_AUTO_FREE) {
  440. hloop_free(&loop);
  441. }
  442. return 0;
  443. }
  444. int hloop_wakeup(hloop_t* loop) {
  445. hevent_t ev;
  446. memset(&ev, 0, sizeof(ev));
  447. hloop_post_event(loop, &ev);
  448. return 0;
  449. }
  450. int hloop_stop(hloop_t* loop) {
  451. if (loop == NULL) return -1;
  452. if (loop->status == HLOOP_STATUS_STOP) return -2;
  453. hlogd("hloop_stop tid=%ld", hv_gettid());
  454. if (hv_gettid() != loop->tid) {
  455. hloop_wakeup(loop);
  456. }
  457. loop->status = HLOOP_STATUS_STOP;
  458. return 0;
  459. }
  460. int hloop_pause(hloop_t* loop) {
  461. if (loop->status == HLOOP_STATUS_RUNNING) {
  462. loop->status = HLOOP_STATUS_PAUSE;
  463. }
  464. return 0;
  465. }
  466. int hloop_resume(hloop_t* loop) {
  467. if (loop->status == HLOOP_STATUS_PAUSE) {
  468. loop->status = HLOOP_STATUS_RUNNING;
  469. }
  470. return 0;
  471. }
  472. hloop_status_e hloop_status(hloop_t* loop) {
  473. return loop->status;
  474. }
  475. void hloop_update_time(hloop_t* loop) {
  476. loop->cur_hrtime = gethrtime_us();
  477. if (hloop_now(loop) != time(NULL)) {
  478. // systemtime changed, we adjust start_ms
  479. loop->start_ms = gettimeofday_ms() - (loop->cur_hrtime - loop->start_hrtime) / 1000;
  480. }
  481. }
  482. uint64_t hloop_now(hloop_t* loop) {
  483. return loop->start_ms / 1000 + (loop->cur_hrtime - loop->start_hrtime) / 1000000;
  484. }
  485. uint64_t hloop_now_ms(hloop_t* loop) {
  486. return loop->start_ms + (loop->cur_hrtime - loop->start_hrtime) / 1000;
  487. }
  488. uint64_t hloop_now_us(hloop_t* loop) {
  489. return loop->start_ms * 1000 + (loop->cur_hrtime - loop->start_hrtime);
  490. }
  491. uint64_t hloop_now_hrtime(hloop_t* loop) {
  492. return loop->cur_hrtime;
  493. }
  494. uint64_t hio_last_read_time(hio_t* io) {
  495. hloop_t* loop = io->loop;
  496. return loop->start_ms + (io->last_read_hrtime - loop->start_hrtime) / 1000;
  497. }
  498. uint64_t hio_last_write_time(hio_t* io) {
  499. hloop_t* loop = io->loop;
  500. return loop->start_ms + (io->last_write_hrtime - loop->start_hrtime) / 1000;
  501. }
  502. long hloop_pid(hloop_t* loop) {
  503. return loop->pid;
  504. }
  505. long hloop_tid(hloop_t* loop) {
  506. return loop->tid;
  507. }
  508. uint64_t hloop_count(hloop_t* loop) {
  509. return loop->loop_cnt;
  510. }
  511. uint32_t hloop_nios(hloop_t* loop) {
  512. return loop->nios;
  513. }
  514. uint32_t hloop_ntimers(hloop_t* loop) {
  515. return loop->ntimers;
  516. }
  517. uint32_t hloop_nidles(hloop_t* loop) {
  518. return loop->nidles;
  519. }
  520. uint32_t hloop_nactives(hloop_t* loop) {
  521. return loop->nactives;
  522. }
  523. void hloop_set_userdata(hloop_t* loop, void* userdata) {
  524. loop->userdata = userdata;
  525. }
  526. void* hloop_userdata(hloop_t* loop) {
  527. return loop->userdata;
  528. }
  529. static hloop_t* s_signal_loop = NULL;
  530. static void signal_handler(int signo) {
  531. if (!s_signal_loop) return;
  532. if (signo >= s_signal_loop->signals.maxsize) return;
  533. hsignal_t* sig = s_signal_loop->signals.ptr[signo];
  534. if (!sig) return;
  535. hloop_post_event(s_signal_loop, sig);
  536. }
  537. hsignal_t* hsignal_add(hloop_t* loop, hsignal_cb cb, int signo) {
  538. int max_signo = 64;
  539. #ifdef _NSIG
  540. max_signo = _NSIG;
  541. #endif
  542. if (signo <= 0 || signo >= max_signo) {
  543. hloge("signo %d over %d!", signo, max_signo);
  544. return NULL;
  545. }
  546. if (loop->signals.maxsize == 0) {
  547. signal_array_init(&loop->signals, max_signo);
  548. }
  549. hsignal_t* sig = loop->signals.ptr[signo];
  550. if (sig == NULL) {
  551. HV_ALLOC_SIZEOF(sig);
  552. sig->loop = loop;
  553. sig->event_type = HEVENT_TYPE_SIGNAL;
  554. // NOTE: use event_id as signo
  555. sig->event_id = signo;
  556. sig->cb = cb;
  557. sig->priority = HEVENT_HIGHEST_PRIORITY;
  558. loop->signals.ptr[signo] = sig;
  559. loop->nsignals++;
  560. }
  561. EVENT_ACTIVE(sig);
  562. s_signal_loop = loop;
  563. signal(signo, signal_handler);
  564. return sig;
  565. }
  566. void hsignal_del(hsignal_t* sig) {
  567. if (!sig->active) return;
  568. hloop_t* loop = sig->loop;
  569. int signo = (int)sig->event_id;
  570. if (signo >= loop->signals.maxsize) return;
  571. loop->signals.ptr[signo] = NULL;
  572. loop->nsignals--;
  573. EVENT_DEL(sig);
  574. }
  575. hidle_t* hidle_add(hloop_t* loop, hidle_cb cb, uint32_t repeat) {
  576. hidle_t* idle;
  577. HV_ALLOC_SIZEOF(idle);
  578. idle->event_type = HEVENT_TYPE_IDLE;
  579. idle->priority = HEVENT_LOWEST_PRIORITY;
  580. idle->repeat = repeat;
  581. list_add(&idle->node, &loop->idles);
  582. EVENT_ADD(loop, idle, cb);
  583. loop->nidles++;
  584. return idle;
  585. }
  586. static void __hidle_del(hidle_t* idle) {
  587. if (idle->destroy) return;
  588. idle->destroy = 1;
  589. list_del(&idle->node);
  590. idle->loop->nidles--;
  591. }
  592. void hidle_del(hidle_t* idle) {
  593. if (!idle->active) return;
  594. __hidle_del(idle);
  595. EVENT_DEL(idle);
  596. }
  597. htimer_t* htimer_add(hloop_t* loop, htimer_cb cb, uint32_t timeout_ms, uint32_t repeat) {
  598. if (timeout_ms == 0) return NULL;
  599. htimeout_t* timer;
  600. HV_ALLOC_SIZEOF(timer);
  601. timer->event_type = HEVENT_TYPE_TIMEOUT;
  602. timer->priority = HEVENT_HIGHEST_PRIORITY;
  603. timer->repeat = repeat;
  604. timer->timeout = timeout_ms;
  605. hloop_update_time(loop);
  606. timer->next_timeout = loop->cur_hrtime + (uint64_t)timeout_ms * 1000;
  607. // NOTE: Limit granularity to 100ms
  608. if (timeout_ms >= 1000 && timeout_ms % 100 == 0) {
  609. timer->next_timeout = timer->next_timeout / 100000 * 100000;
  610. }
  611. heap_insert(&loop->timers, &timer->node);
  612. EVENT_ADD(loop, timer, cb);
  613. loop->ntimers++;
  614. return (htimer_t*)timer;
  615. }
  616. void htimer_reset(htimer_t* timer, uint32_t timeout_ms) {
  617. if (timer->event_type != HEVENT_TYPE_TIMEOUT) {
  618. return;
  619. }
  620. hloop_t* loop = timer->loop;
  621. htimeout_t* timeout = (htimeout_t*)timer;
  622. if (timer->destroy) {
  623. loop->ntimers++;
  624. } else {
  625. heap_remove(&loop->timers, &timer->node);
  626. }
  627. if (timer->repeat == 0) {
  628. timer->repeat = 1;
  629. }
  630. if (timeout_ms > 0) {
  631. timeout->timeout = timeout_ms;
  632. }
  633. timer->next_timeout = loop->cur_hrtime + (uint64_t)timeout->timeout * 1000;
  634. // NOTE: Limit granularity to 100ms
  635. if (timeout->timeout >= 1000 && timeout->timeout % 100 == 0) {
  636. timer->next_timeout = timer->next_timeout / 100000 * 100000;
  637. }
  638. heap_insert(&loop->timers, &timer->node);
  639. EVENT_RESET(timer);
  640. }
  641. htimer_t* htimer_add_period(hloop_t* loop, htimer_cb cb,
  642. int8_t minute, int8_t hour, int8_t day,
  643. int8_t week, int8_t month, uint32_t repeat) {
  644. if (minute > 59 || hour > 23 || day > 31 || week > 6 || month > 12) {
  645. return NULL;
  646. }
  647. hperiod_t* timer;
  648. HV_ALLOC_SIZEOF(timer);
  649. timer->event_type = HEVENT_TYPE_PERIOD;
  650. timer->priority = HEVENT_HIGH_PRIORITY;
  651. timer->repeat = repeat;
  652. timer->minute = minute;
  653. timer->hour = hour;
  654. timer->day = day;
  655. timer->month = month;
  656. timer->week = week;
  657. timer->next_timeout = (uint64_t)cron_next_timeout(minute, hour, day, week, month) * 1000000;
  658. heap_insert(&loop->realtimers, &timer->node);
  659. EVENT_ADD(loop, timer, cb);
  660. loop->ntimers++;
  661. return (htimer_t*)timer;
  662. }
  663. static void __htimer_del(htimer_t* timer) {
  664. if (timer->destroy) return;
  665. if (timer->event_type == HEVENT_TYPE_TIMEOUT) {
  666. heap_remove(&timer->loop->timers, &timer->node);
  667. } else if (timer->event_type == HEVENT_TYPE_PERIOD) {
  668. heap_remove(&timer->loop->realtimers, &timer->node);
  669. }
  670. timer->loop->ntimers--;
  671. timer->destroy = 1;
  672. }
  673. void htimer_del(htimer_t* timer) {
  674. if (!timer->active) return;
  675. __htimer_del(timer);
  676. EVENT_DEL(timer);
  677. }
  678. const char* hio_engine() {
  679. #ifdef EVENT_SELECT
  680. return "select";
  681. #elif defined(EVENT_POLL)
  682. return "poll";
  683. #elif defined(EVENT_EPOLL)
  684. return "epoll";
  685. #elif defined(EVENT_KQUEUE)
  686. return "kqueue";
  687. #elif defined(EVENT_IOCP)
  688. return "iocp";
  689. #elif defined(EVENT_PORT)
  690. return "evport";
  691. #else
  692. return "noevent";
  693. #endif
  694. }
  695. static inline hio_t* __hio_get(hloop_t* loop, int fd) {
  696. if (fd >= loop->ios.maxsize) {
  697. int newsize = ceil2e(fd);
  698. newsize = MAX(newsize, IO_ARRAY_INIT_SIZE);
  699. io_array_resize(&loop->ios, newsize > fd ? newsize : 2*fd);
  700. }
  701. return loop->ios.ptr[fd];
  702. }
  703. hio_t* hio_get(hloop_t* loop, int fd) {
  704. hio_t* io = __hio_get(loop, fd);
  705. if (io == NULL) {
  706. HV_ALLOC_SIZEOF(io);
  707. hio_init(io);
  708. io->event_type = HEVENT_TYPE_IO;
  709. io->loop = loop;
  710. io->fd = fd;
  711. loop->ios.ptr[fd] = io;
  712. }
  713. if (!io->ready) {
  714. hio_ready(io);
  715. }
  716. return io;
  717. }
  718. void hio_detach(hio_t* io) {
  719. hloop_t* loop = io->loop;
  720. int fd = io->fd;
  721. assert(loop != NULL && fd < loop->ios.maxsize);
  722. loop->ios.ptr[fd] = NULL;
  723. }
  724. void hio_attach(hloop_t* loop, hio_t* io) {
  725. int fd = io->fd;
  726. // NOTE: hio was not freed for reused when closed, but attached hio can't be reused,
  727. // so we need to free it if fd exists to avoid memory leak.
  728. hio_t* preio = __hio_get(loop, fd);
  729. if (preio != NULL && preio != io) {
  730. hio_free(preio);
  731. }
  732. io->loop = loop;
  733. // NOTE: use new_loop readbuf
  734. hio_use_loop_readbuf(io);
  735. loop->ios.ptr[fd] = io;
  736. }
  737. bool hio_exists(hloop_t* loop, int fd) {
  738. if (fd >= loop->ios.maxsize) {
  739. return false;
  740. }
  741. return loop->ios.ptr[fd] != NULL;
  742. }
  743. int hio_add(hio_t* io, hio_cb cb, int events) {
  744. printd("hio_add fd=%d io->events=%d events=%d\n", io->fd, io->events, events);
  745. #ifdef OS_WIN
  746. // Windows iowatcher not work on stdio
  747. if (io->fd < 3) return -1;
  748. #endif
  749. hloop_t* loop = io->loop;
  750. if (!io->active) {
  751. EVENT_ADD(loop, io, cb);
  752. loop->nios++;
  753. }
  754. if (!io->ready) {
  755. hio_ready(io);
  756. }
  757. if (cb) {
  758. io->cb = (hevent_cb)cb;
  759. }
  760. if (!(io->events & events)) {
  761. iowatcher_add_event(loop, io->fd, events);
  762. io->events |= events;
  763. }
  764. return 0;
  765. }
  766. int hio_del(hio_t* io, int events) {
  767. printd("hio_del fd=%d io->events=%d events=%d\n", io->fd, io->events, events);
  768. #ifdef OS_WIN
  769. // Windows iowatcher not work on stdio
  770. if (io->fd < 3) return -1;
  771. #endif
  772. if (!io->active) return -1;
  773. if (io->events & events) {
  774. iowatcher_del_event(io->loop, io->fd, events);
  775. io->events &= ~events;
  776. }
  777. if (io->events == 0) {
  778. io->loop->nios--;
  779. // NOTE: not EVENT_DEL, avoid free
  780. EVENT_INACTIVE(io);
  781. }
  782. return 0;
  783. }
  784. static void hio_close_event_cb(hevent_t* ev) {
  785. hio_t* io = (hio_t*)ev->userdata;
  786. uint32_t id = (uintptr_t)ev->privdata;
  787. if (io->id != id) return;
  788. hio_close(io);
  789. }
  790. int hio_close_async(hio_t* io) {
  791. hevent_t ev;
  792. memset(&ev, 0, sizeof(ev));
  793. ev.cb = hio_close_event_cb;
  794. ev.userdata = io;
  795. ev.privdata = (void*)(uintptr_t)io->id;
  796. hloop_post_event(io->loop, &ev);
  797. return 0;
  798. }
  799. //------------------high-level apis-------------------------------------------
  800. hio_t* hread(hloop_t* loop, int fd, void* buf, size_t len, hread_cb read_cb) {
  801. hio_t* io = hio_get(loop, fd);
  802. assert(io != NULL);
  803. if (buf && len) {
  804. io->readbuf.base = (char*)buf;
  805. io->readbuf.len = len;
  806. }
  807. if (read_cb) {
  808. io->read_cb = read_cb;
  809. }
  810. hio_read(io);
  811. return io;
  812. }
  813. hio_t* hwrite(hloop_t* loop, int fd, const void* buf, size_t len, hwrite_cb write_cb) {
  814. hio_t* io = hio_get(loop, fd);
  815. assert(io != NULL);
  816. if (write_cb) {
  817. io->write_cb = write_cb;
  818. }
  819. hio_write(io, buf, len);
  820. return io;
  821. }
  822. hio_t* haccept(hloop_t* loop, int listenfd, haccept_cb accept_cb) {
  823. hio_t* io = hio_get(loop, listenfd);
  824. assert(io != NULL);
  825. if (accept_cb) {
  826. io->accept_cb = accept_cb;
  827. }
  828. if (hio_accept(io) != 0) return NULL;
  829. return io;
  830. }
  831. hio_t* hconnect (hloop_t* loop, int connfd, hconnect_cb connect_cb) {
  832. hio_t* io = hio_get(loop, connfd);
  833. assert(io != NULL);
  834. if (connect_cb) {
  835. io->connect_cb = connect_cb;
  836. }
  837. if (hio_connect(io) != 0) return NULL;
  838. return io;
  839. }
  840. void hclose (hloop_t* loop, int fd) {
  841. hio_t* io = hio_get(loop, fd);
  842. assert(io != NULL);
  843. hio_close(io);
  844. }
  845. hio_t* hrecv (hloop_t* loop, int connfd, void* buf, size_t len, hread_cb read_cb) {
  846. //hio_t* io = hio_get(loop, connfd);
  847. //assert(io != NULL);
  848. //io->recv = 1;
  849. //if (io->io_type != HIO_TYPE_SSL) {
  850. //io->io_type = HIO_TYPE_TCP;
  851. //}
  852. return hread(loop, connfd, buf, len, read_cb);
  853. }
  854. hio_t* hsend (hloop_t* loop, int connfd, const void* buf, size_t len, hwrite_cb write_cb) {
  855. //hio_t* io = hio_get(loop, connfd);
  856. //assert(io != NULL);
  857. //io->send = 1;
  858. //if (io->io_type != HIO_TYPE_SSL) {
  859. //io->io_type = HIO_TYPE_TCP;
  860. //}
  861. return hwrite(loop, connfd, buf, len, write_cb);
  862. }
  863. hio_t* hrecvfrom (hloop_t* loop, int sockfd, void* buf, size_t len, hread_cb read_cb) {
  864. //hio_t* io = hio_get(loop, sockfd);
  865. //assert(io != NULL);
  866. //io->recvfrom = 1;
  867. //io->io_type = HIO_TYPE_UDP;
  868. return hread(loop, sockfd, buf, len, read_cb);
  869. }
  870. hio_t* hsendto (hloop_t* loop, int sockfd, const void* buf, size_t len, hwrite_cb write_cb) {
  871. //hio_t* io = hio_get(loop, sockfd);
  872. //assert(io != NULL);
  873. //io->sendto = 1;
  874. //io->io_type = HIO_TYPE_UDP;
  875. return hwrite(loop, sockfd, buf, len, write_cb);
  876. }
  877. //-----------------top-level apis---------------------------------------------
  878. hio_t* hio_create_socket(hloop_t* loop, const char* host, int port, hio_type_e type, hio_side_e side) {
  879. int sock_type = (type & HIO_TYPE_SOCK_STREAM) ? SOCK_STREAM :
  880. (type & HIO_TYPE_SOCK_DGRAM) ? SOCK_DGRAM :
  881. (type & HIO_TYPE_SOCK_RAW) ? SOCK_RAW : -1;
  882. if (sock_type == -1) return NULL;
  883. sockaddr_u addr;
  884. memset(&addr, 0, sizeof(addr));
  885. int ret = -1;
  886. #ifdef ENABLE_UDS
  887. if (port < 0) {
  888. sockaddr_set_path(&addr, host);
  889. ret = 0;
  890. }
  891. #endif
  892. if (port >= 0) {
  893. ret = sockaddr_set_ipport(&addr, host, port);
  894. }
  895. if (ret != 0) {
  896. // fprintf(stderr, "unknown host: %s\n", host);
  897. return NULL;
  898. }
  899. int sockfd = socket(addr.sa.sa_family, sock_type, 0);
  900. if (sockfd < 0) {
  901. perror("socket");
  902. return NULL;
  903. }
  904. hio_t* io = NULL;
  905. if (side == HIO_SERVER_SIDE) {
  906. #ifdef OS_UNIX
  907. so_reuseaddr(sockfd, 1);
  908. // so_reuseport(sockfd, 1);
  909. #endif
  910. if (addr.sa.sa_family == AF_INET6) {
  911. ip_v6only(sockfd, 0);
  912. }
  913. if (bind(sockfd, &addr.sa, sockaddr_len(&addr)) < 0) {
  914. perror("bind");
  915. closesocket(sockfd);
  916. return NULL;
  917. }
  918. if (sock_type == SOCK_STREAM) {
  919. if (listen(sockfd, SOMAXCONN) < 0) {
  920. perror("listen");
  921. closesocket(sockfd);
  922. return NULL;
  923. }
  924. }
  925. }
  926. io = hio_get(loop, sockfd);
  927. assert(io != NULL);
  928. io->io_type = type;
  929. if (side == HIO_SERVER_SIDE) {
  930. hio_set_localaddr(io, &addr.sa, sockaddr_len(&addr));
  931. io->priority = HEVENT_HIGH_PRIORITY;
  932. } else {
  933. hio_set_peeraddr(io, &addr.sa, sockaddr_len(&addr));
  934. }
  935. return io;
  936. }
  937. hio_t* hloop_create_tcp_server (hloop_t* loop, const char* host, int port, haccept_cb accept_cb) {
  938. hio_t* io = hio_create_socket(loop, host, port, HIO_TYPE_TCP, HIO_SERVER_SIDE);
  939. if (io == NULL) return NULL;
  940. hio_setcb_accept(io, accept_cb);
  941. if (hio_accept(io) != 0) return NULL;
  942. return io;
  943. }
  944. hio_t* hloop_create_tcp_client (hloop_t* loop, const char* host, int port, hconnect_cb connect_cb, hclose_cb close_cb) {
  945. hio_t* io = hio_create_socket(loop, host, port, HIO_TYPE_TCP, HIO_CLIENT_SIDE);
  946. if (io == NULL) return NULL;
  947. hio_setcb_connect(io, connect_cb);
  948. hio_setcb_close(io, close_cb);
  949. if (hio_connect(io) != 0) return NULL;
  950. return io;
  951. }
  952. hio_t* hloop_create_ssl_server (hloop_t* loop, const char* host, int port, haccept_cb accept_cb) {
  953. hio_t* io = hio_create_socket(loop, host, port, HIO_TYPE_SSL, HIO_SERVER_SIDE);
  954. if (io == NULL) return NULL;
  955. hio_setcb_accept(io, accept_cb);
  956. if (hio_accept(io) != 0) return NULL;
  957. return io;
  958. }
  959. hio_t* hloop_create_ssl_client (hloop_t* loop, const char* host, int port, hconnect_cb connect_cb, hclose_cb close_cb) {
  960. hio_t* io = hio_create_socket(loop, host, port, HIO_TYPE_SSL, HIO_CLIENT_SIDE);
  961. if (io == NULL) return NULL;
  962. hio_setcb_connect(io, connect_cb);
  963. hio_setcb_close(io, close_cb);
  964. if (hio_connect(io) != 0) return NULL;
  965. return io;
  966. }
  967. hio_t* hloop_create_udp_server(hloop_t* loop, const char* host, int port) {
  968. return hio_create_socket(loop, host, port, HIO_TYPE_UDP, HIO_SERVER_SIDE);
  969. }
  970. hio_t* hloop_create_udp_client(hloop_t* loop, const char* host, int port) {
  971. return hio_create_socket(loop, host, port, HIO_TYPE_UDP, HIO_CLIENT_SIDE);
  972. }
  973. int hio_create_pipe(hloop_t* loop, hio_t* pipeio[2]) {
  974. int pipefd[2];
  975. hio_type_e type = HIO_TYPE_PIPE;
  976. #if defined(OS_UNIX) && HAVE_PIPE
  977. if (pipe(pipefd) != 0) {
  978. hloge("pipe create failed!");
  979. return -1;
  980. }
  981. #else
  982. if (Socketpair(AF_INET, SOCK_STREAM, 0, pipefd) != 0) {
  983. hloge("socketpair create failed!");
  984. return -1;
  985. }
  986. type = HIO_TYPE_TCP;
  987. #endif
  988. pipeio[0] = hio_get(loop, pipefd[0]);
  989. pipeio[1] = hio_get(loop, pipefd[1]);
  990. pipeio[0]->io_type = type;
  991. pipeio[1]->io_type = type;
  992. return 0;
  993. }