hloop.c 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013
  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. static int hloop_process_events(hloop_t* loop) {
  127. // ios -> timers -> idles
  128. int nios, ntimers, nidles;
  129. nios = ntimers = nidles = 0;
  130. // calc blocktime
  131. int32_t blocktime_ms = HLOOP_MAX_BLOCK_TIME;
  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, HLOOP_MAX_BLOCK_TIME);
  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. }
  173. static void hloop_stat_timer_cb(htimer_t* timer) {
  174. hloop_t* loop = timer->loop;
  175. // hlog_set_level(LOG_LEVEL_DEBUG);
  176. hlogd("[loop] pid=%ld tid=%ld uptime=%lluus cnt=%llu nactives=%u nios=%u ntimers=%u nidles=%u",
  177. loop->pid, loop->tid, loop->cur_hrtime - loop->start_hrtime, loop->loop_cnt,
  178. loop->nactives, loop->nios, loop->ntimers, loop->nidles);
  179. }
  180. static void eventfd_read_cb(hio_t* io, void* buf, int readbytes) {
  181. hloop_t* loop = io->loop;
  182. hevent_t* pev = NULL;
  183. hevent_t ev;
  184. uint64_t count = readbytes;
  185. #if defined(OS_UNIX) && HAVE_EVENTFD
  186. assert(readbytes == sizeof(count));
  187. count = *(uint64_t*)buf;
  188. #endif
  189. for (uint64_t i = 0; i < count; ++i) {
  190. hmutex_lock(&loop->custom_events_mutex);
  191. if (event_queue_empty(&loop->custom_events)) {
  192. goto unlock;
  193. }
  194. pev = event_queue_front(&loop->custom_events);
  195. if (pev == NULL) {
  196. goto unlock;
  197. }
  198. ev = *pev;
  199. event_queue_pop_front(&loop->custom_events);
  200. // NOTE: unlock before cb, avoid deadlock if hloop_post_event called in cb.
  201. hmutex_unlock(&loop->custom_events_mutex);
  202. if (ev.cb) {
  203. ev.cb(&ev);
  204. }
  205. }
  206. return;
  207. unlock:
  208. hmutex_unlock(&loop->custom_events_mutex);
  209. }
  210. static int hloop_create_eventfds(hloop_t* loop) {
  211. #if defined(OS_UNIX) && HAVE_EVENTFD
  212. int efd = eventfd(0, 0);
  213. if (efd < 0) {
  214. hloge("eventfd create failed!");
  215. return -1;
  216. }
  217. loop->eventfds[0] = loop->eventfds[1] = efd;
  218. #elif defined(OS_UNIX) && HAVE_PIPE
  219. if (pipe(loop->eventfds) != 0) {
  220. hloge("pipe create failed!");
  221. return -1;
  222. }
  223. #else
  224. if (Socketpair(AF_INET, SOCK_STREAM, 0, loop->eventfds) != 0) {
  225. hloge("socketpair create failed!");
  226. return -1;
  227. }
  228. #endif
  229. hio_t* io = hread(loop, loop->eventfds[EVENTFDS_READ_INDEX], loop->readbuf.base, loop->readbuf.len, eventfd_read_cb);
  230. io->priority = HEVENT_HIGH_PRIORITY;
  231. ++loop->intern_nevents;
  232. return 0;
  233. }
  234. static void hloop_destroy_eventfds(hloop_t* loop) {
  235. #if defined(OS_UNIX) && HAVE_EVENTFD
  236. // NOTE: eventfd has only one fd
  237. SAFE_CLOSE(loop->eventfds[0]);
  238. #elif defined(OS_UNIX) && HAVE_PIPE
  239. SAFE_CLOSE(loop->eventfds[0]);
  240. SAFE_CLOSE(loop->eventfds[1]);
  241. #else
  242. // NOTE: Avoid duplication closesocket in hio_cleanup
  243. // SAFE_CLOSESOCKET(loop->eventfds[EVENTFDS_READ_INDEX]);
  244. SAFE_CLOSESOCKET(loop->eventfds[EVENTFDS_WRITE_INDEX]);
  245. #endif
  246. loop->eventfds[0] = loop->eventfds[1] = -1;
  247. }
  248. void hloop_post_event(hloop_t* loop, hevent_t* ev) {
  249. if (ev->loop == NULL) {
  250. ev->loop = loop;
  251. }
  252. if (ev->event_type == 0) {
  253. ev->event_type = HEVENT_TYPE_CUSTOM;
  254. }
  255. if (ev->event_id == 0) {
  256. ev->event_id = hloop_next_event_id();
  257. }
  258. int nwrite = 0;
  259. uint64_t count = 1;
  260. hmutex_lock(&loop->custom_events_mutex);
  261. if (loop->eventfds[EVENTFDS_WRITE_INDEX] == -1) {
  262. if (hloop_create_eventfds(loop) != 0) {
  263. goto unlock;
  264. }
  265. }
  266. #if defined(OS_UNIX) && HAVE_EVENTFD
  267. nwrite = write(loop->eventfds[EVENTFDS_WRITE_INDEX], &count, sizeof(count));
  268. #elif defined(OS_UNIX) && HAVE_PIPE
  269. nwrite = write(loop->eventfds[EVENTFDS_WRITE_INDEX], "e", 1);
  270. #else
  271. nwrite = send(loop->eventfds[EVENTFDS_WRITE_INDEX], "e", 1, 0);
  272. #endif
  273. if (nwrite <= 0) {
  274. hloge("hloop_post_event failed!");
  275. goto unlock;
  276. }
  277. event_queue_push_back(&loop->custom_events, ev);
  278. unlock:
  279. hmutex_unlock(&loop->custom_events_mutex);
  280. }
  281. static void hloop_init(hloop_t* loop) {
  282. #ifdef OS_WIN
  283. WSAInit();
  284. #endif
  285. #ifdef SIGPIPE
  286. // NOTE: if not ignore SIGPIPE, write twice when peer close will lead to exit process by SIGPIPE.
  287. signal(SIGPIPE, SIG_IGN);
  288. #endif
  289. loop->status = HLOOP_STATUS_STOP;
  290. loop->pid = hv_getpid();
  291. loop->tid = hv_gettid();
  292. // idles
  293. list_init(&loop->idles);
  294. // timers
  295. heap_init(&loop->timers, timers_compare);
  296. heap_init(&loop->realtimers, timers_compare);
  297. // ios
  298. io_array_init(&loop->ios, IO_ARRAY_INIT_SIZE);
  299. // readbuf
  300. loop->readbuf.len = HLOOP_READ_BUFSIZE;
  301. HV_ALLOC(loop->readbuf.base, loop->readbuf.len);
  302. // iowatcher
  303. iowatcher_init(loop);
  304. // custom_events
  305. hmutex_init(&loop->custom_events_mutex);
  306. event_queue_init(&loop->custom_events, CUSTOM_EVENT_QUEUE_INIT_SIZE);
  307. // NOTE: hloop_create_eventfds when hloop_post_event or hloop_run
  308. loop->eventfds[0] = loop->eventfds[1] = -1;
  309. // NOTE: init start_time here, because htimer_add use it.
  310. loop->start_ms = gettimeofday_ms();
  311. loop->start_hrtime = loop->cur_hrtime = gethrtime_us();
  312. }
  313. static void hloop_cleanup(hloop_t* loop) {
  314. // pendings
  315. printd("cleanup pendings...\n");
  316. for (int i = 0; i < HEVENT_PRIORITY_SIZE; ++i) {
  317. loop->pendings[i] = NULL;
  318. }
  319. // ios
  320. printd("cleanup ios...\n");
  321. for (int i = 0; i < loop->ios.maxsize; ++i) {
  322. hio_t* io = loop->ios.ptr[i];
  323. if (io) {
  324. hio_free(io);
  325. }
  326. }
  327. io_array_cleanup(&loop->ios);
  328. // idles
  329. printd("cleanup idles...\n");
  330. struct list_node* node = loop->idles.next;
  331. hidle_t* idle;
  332. while (node != &loop->idles) {
  333. idle = IDLE_ENTRY(node);
  334. node = node->next;
  335. HV_FREE(idle);
  336. }
  337. list_init(&loop->idles);
  338. // timers
  339. printd("cleanup timers...\n");
  340. htimer_t* timer;
  341. while (loop->timers.root) {
  342. timer = TIMER_ENTRY(loop->timers.root);
  343. heap_dequeue(&loop->timers);
  344. HV_FREE(timer);
  345. }
  346. heap_init(&loop->timers, NULL);
  347. while (loop->realtimers.root) {
  348. timer = TIMER_ENTRY(loop->realtimers.root);
  349. heap_dequeue(&loop->realtimers);
  350. HV_FREE(timer);
  351. }
  352. heap_init(&loop->realtimers, NULL);
  353. // readbuf
  354. if (loop->readbuf.base && loop->readbuf.len) {
  355. HV_FREE(loop->readbuf.base);
  356. loop->readbuf.base = NULL;
  357. loop->readbuf.len = 0;
  358. }
  359. // iowatcher
  360. iowatcher_cleanup(loop);
  361. // custom_events
  362. hmutex_lock(&loop->custom_events_mutex);
  363. hloop_destroy_eventfds(loop);
  364. event_queue_cleanup(&loop->custom_events);
  365. hmutex_unlock(&loop->custom_events_mutex);
  366. hmutex_destroy(&loop->custom_events_mutex);
  367. }
  368. hloop_t* hloop_new(int flags) {
  369. hloop_t* loop;
  370. HV_ALLOC_SIZEOF(loop);
  371. hloop_init(loop);
  372. loop->flags |= flags;
  373. return loop;
  374. }
  375. void hloop_free(hloop_t** pp) {
  376. if (pp && *pp) {
  377. hloop_cleanup(*pp);
  378. HV_FREE(*pp);
  379. *pp = NULL;
  380. }
  381. }
  382. // while (loop->status) { hloop_process_events(loop); }
  383. int hloop_run(hloop_t* loop) {
  384. if (loop == NULL) return -1;
  385. if (loop->status == HLOOP_STATUS_RUNNING) return -2;
  386. loop->status = HLOOP_STATUS_RUNNING;
  387. loop->pid = hv_getpid();
  388. loop->tid = hv_gettid();
  389. if (loop->intern_nevents == 0) {
  390. hmutex_lock(&loop->custom_events_mutex);
  391. if (loop->eventfds[EVENTFDS_WRITE_INDEX] == -1) {
  392. hloop_create_eventfds(loop);
  393. }
  394. hmutex_unlock(&loop->custom_events_mutex);
  395. #ifdef DEBUG
  396. htimer_add(loop, hloop_stat_timer_cb, HLOOP_STAT_TIMEOUT, INFINITE);
  397. ++loop->intern_nevents;
  398. #endif
  399. }
  400. while (loop->status != HLOOP_STATUS_STOP) {
  401. if (loop->status == HLOOP_STATUS_PAUSE) {
  402. hv_msleep(HLOOP_PAUSE_TIME);
  403. hloop_update_time(loop);
  404. continue;
  405. }
  406. ++loop->loop_cnt;
  407. if ((loop->flags & HLOOP_FLAG_QUIT_WHEN_NO_ACTIVE_EVENTS) &&
  408. loop->nactives <= loop->intern_nevents) {
  409. break;
  410. }
  411. hloop_process_events(loop);
  412. if (loop->flags & HLOOP_FLAG_RUN_ONCE) {
  413. break;
  414. }
  415. }
  416. loop->status = HLOOP_STATUS_STOP;
  417. loop->end_hrtime = gethrtime_us();
  418. if (loop->flags & HLOOP_FLAG_AUTO_FREE) {
  419. hloop_cleanup(loop);
  420. HV_FREE(loop);
  421. }
  422. return 0;
  423. }
  424. int hloop_wakeup(hloop_t* loop) {
  425. hevent_t ev;
  426. memset(&ev, 0, sizeof(ev));
  427. hloop_post_event(loop, &ev);
  428. return 0;
  429. }
  430. int hloop_stop(hloop_t* loop) {
  431. if (hv_gettid() != loop->tid) {
  432. hloop_wakeup(loop);
  433. }
  434. loop->status = HLOOP_STATUS_STOP;
  435. return 0;
  436. }
  437. int hloop_pause(hloop_t* loop) {
  438. if (loop->status == HLOOP_STATUS_RUNNING) {
  439. loop->status = HLOOP_STATUS_PAUSE;
  440. }
  441. return 0;
  442. }
  443. int hloop_resume(hloop_t* loop) {
  444. if (loop->status == HLOOP_STATUS_PAUSE) {
  445. loop->status = HLOOP_STATUS_RUNNING;
  446. }
  447. return 0;
  448. }
  449. hloop_status_e hloop_status(hloop_t* loop) {
  450. return loop->status;
  451. }
  452. void hloop_update_time(hloop_t* loop) {
  453. loop->cur_hrtime = gethrtime_us();
  454. if (hloop_now(loop) != time(NULL)) {
  455. // systemtime changed, we adjust start_ms
  456. loop->start_ms = gettimeofday_ms() - (loop->cur_hrtime - loop->start_hrtime) / 1000;
  457. }
  458. }
  459. uint64_t hloop_now(hloop_t* loop) {
  460. return loop->start_ms / 1000 + (loop->cur_hrtime - loop->start_hrtime) / 1000000;
  461. }
  462. uint64_t hloop_now_ms(hloop_t* loop) {
  463. return loop->start_ms + (loop->cur_hrtime - loop->start_hrtime) / 1000;
  464. }
  465. uint64_t hloop_now_us(hloop_t* loop) {
  466. return loop->start_ms * 1000 + (loop->cur_hrtime - loop->start_hrtime);
  467. }
  468. uint64_t hloop_now_hrtime(hloop_t* loop) {
  469. return loop->cur_hrtime;
  470. }
  471. uint64_t hio_last_read_time(hio_t* io) {
  472. hloop_t* loop = io->loop;
  473. return loop->start_ms + (io->last_read_hrtime - loop->start_hrtime) / 1000;
  474. }
  475. uint64_t hio_last_write_time(hio_t* io) {
  476. hloop_t* loop = io->loop;
  477. return loop->start_ms + (io->last_write_hrtime - loop->start_hrtime) / 1000;
  478. }
  479. long hloop_pid(hloop_t* loop) {
  480. return loop->pid;
  481. }
  482. long hloop_tid(hloop_t* loop) {
  483. return loop->tid;
  484. }
  485. uint64_t hloop_count(hloop_t* loop) {
  486. return loop->loop_cnt;
  487. }
  488. uint32_t hloop_nios(hloop_t* loop) {
  489. return loop->nios;
  490. }
  491. uint32_t hloop_ntimers(hloop_t* loop) {
  492. return loop->ntimers;
  493. }
  494. uint32_t hloop_nidles(hloop_t* loop) {
  495. return loop->nidles;
  496. }
  497. uint32_t hloop_nactives(hloop_t* loop) {
  498. return loop->nactives;
  499. }
  500. void hloop_set_userdata(hloop_t* loop, void* userdata) {
  501. loop->userdata = userdata;
  502. }
  503. void* hloop_userdata(hloop_t* loop) {
  504. return loop->userdata;
  505. }
  506. hidle_t* hidle_add(hloop_t* loop, hidle_cb cb, uint32_t repeat) {
  507. hidle_t* idle;
  508. HV_ALLOC_SIZEOF(idle);
  509. idle->event_type = HEVENT_TYPE_IDLE;
  510. idle->priority = HEVENT_LOWEST_PRIORITY;
  511. idle->repeat = repeat;
  512. list_add(&idle->node, &loop->idles);
  513. EVENT_ADD(loop, idle, cb);
  514. loop->nidles++;
  515. return idle;
  516. }
  517. static void __hidle_del(hidle_t* idle) {
  518. if (idle->destroy) return;
  519. idle->destroy = 1;
  520. list_del(&idle->node);
  521. idle->loop->nidles--;
  522. }
  523. void hidle_del(hidle_t* idle) {
  524. if (!idle->active) return;
  525. __hidle_del(idle);
  526. EVENT_DEL(idle);
  527. }
  528. htimer_t* htimer_add(hloop_t* loop, htimer_cb cb, uint32_t timeout_ms, uint32_t repeat) {
  529. if (timeout_ms == 0) return NULL;
  530. htimeout_t* timer;
  531. HV_ALLOC_SIZEOF(timer);
  532. timer->event_type = HEVENT_TYPE_TIMEOUT;
  533. timer->priority = HEVENT_HIGHEST_PRIORITY;
  534. timer->repeat = repeat;
  535. timer->timeout = timeout_ms;
  536. hloop_update_time(loop);
  537. timer->next_timeout = loop->cur_hrtime + (uint64_t)timeout_ms * 1000;
  538. // NOTE: Limit granularity to 100ms
  539. if (timeout_ms >= 1000 && timeout_ms % 100 == 0) {
  540. timer->next_timeout = timer->next_timeout / 100000 * 100000;
  541. }
  542. heap_insert(&loop->timers, &timer->node);
  543. EVENT_ADD(loop, timer, cb);
  544. loop->ntimers++;
  545. return (htimer_t*)timer;
  546. }
  547. void htimer_reset(htimer_t* timer, uint32_t timeout_ms) {
  548. if (timer->event_type != HEVENT_TYPE_TIMEOUT) {
  549. return;
  550. }
  551. hloop_t* loop = timer->loop;
  552. htimeout_t* timeout = (htimeout_t*)timer;
  553. if (timer->destroy) {
  554. loop->ntimers++;
  555. } else {
  556. heap_remove(&loop->timers, &timer->node);
  557. }
  558. if (timer->repeat == 0) {
  559. timer->repeat = 1;
  560. }
  561. if (timeout_ms > 0) {
  562. timeout->timeout = timeout_ms;
  563. }
  564. timer->next_timeout = loop->cur_hrtime + (uint64_t)timeout->timeout * 1000;
  565. // NOTE: Limit granularity to 100ms
  566. if (timeout->timeout >= 1000 && timeout->timeout % 100 == 0) {
  567. timer->next_timeout = timer->next_timeout / 100000 * 100000;
  568. }
  569. heap_insert(&loop->timers, &timer->node);
  570. EVENT_RESET(timer);
  571. }
  572. htimer_t* htimer_add_period(hloop_t* loop, htimer_cb cb,
  573. int8_t minute, int8_t hour, int8_t day,
  574. int8_t week, int8_t month, uint32_t repeat) {
  575. if (minute > 59 || hour > 23 || day > 31 || week > 6 || month > 12) {
  576. return NULL;
  577. }
  578. hperiod_t* timer;
  579. HV_ALLOC_SIZEOF(timer);
  580. timer->event_type = HEVENT_TYPE_PERIOD;
  581. timer->priority = HEVENT_HIGH_PRIORITY;
  582. timer->repeat = repeat;
  583. timer->minute = minute;
  584. timer->hour = hour;
  585. timer->day = day;
  586. timer->month = month;
  587. timer->week = week;
  588. timer->next_timeout = (uint64_t)cron_next_timeout(minute, hour, day, week, month) * 1000000;
  589. heap_insert(&loop->realtimers, &timer->node);
  590. EVENT_ADD(loop, timer, cb);
  591. loop->ntimers++;
  592. return (htimer_t*)timer;
  593. }
  594. static void __htimer_del(htimer_t* timer) {
  595. if (timer->destroy) return;
  596. if (timer->event_type == HEVENT_TYPE_TIMEOUT) {
  597. heap_remove(&timer->loop->timers, &timer->node);
  598. } else if (timer->event_type == HEVENT_TYPE_PERIOD) {
  599. heap_remove(&timer->loop->realtimers, &timer->node);
  600. }
  601. timer->loop->ntimers--;
  602. timer->destroy = 1;
  603. }
  604. void htimer_del(htimer_t* timer) {
  605. if (!timer->active) return;
  606. __htimer_del(timer);
  607. EVENT_DEL(timer);
  608. }
  609. const char* hio_engine() {
  610. #ifdef EVENT_SELECT
  611. return "select";
  612. #elif defined(EVENT_POLL)
  613. return "poll";
  614. #elif defined(EVENT_EPOLL)
  615. return "epoll";
  616. #elif defined(EVENT_KQUEUE)
  617. return "kqueue";
  618. #elif defined(EVENT_IOCP)
  619. return "iocp";
  620. #elif defined(EVENT_PORT)
  621. return "evport";
  622. #else
  623. return "noevent";
  624. #endif
  625. }
  626. hio_t* hio_get(hloop_t* loop, int fd) {
  627. if (fd >= loop->ios.maxsize) {
  628. int newsize = ceil2e(fd);
  629. io_array_resize(&loop->ios, newsize > fd ? newsize : 2*fd);
  630. }
  631. hio_t* io = loop->ios.ptr[fd];
  632. if (io == NULL) {
  633. HV_ALLOC_SIZEOF(io);
  634. hio_init(io);
  635. io->event_type = HEVENT_TYPE_IO;
  636. io->loop = loop;
  637. io->fd = fd;
  638. loop->ios.ptr[fd] = io;
  639. }
  640. if (!io->ready) {
  641. hio_ready(io);
  642. }
  643. return io;
  644. }
  645. void hio_detach(hio_t* io) {
  646. hloop_t* loop = io->loop;
  647. int fd = io->fd;
  648. assert(loop != NULL && fd < loop->ios.maxsize);
  649. loop->ios.ptr[fd] = NULL;
  650. }
  651. void hio_attach(hloop_t* loop, hio_t* io) {
  652. int fd = io->fd;
  653. if (fd >= loop->ios.maxsize) {
  654. int newsize = ceil2e(fd);
  655. io_array_resize(&loop->ios, newsize > fd ? newsize : 2*fd);
  656. }
  657. // NOTE: hio was not freed for reused when closed, but attached hio can't be reused,
  658. // so we need to free it if fd exists to avoid memory leak.
  659. hio_t* preio = loop->ios.ptr[fd];
  660. if (preio != NULL && preio != io) {
  661. hio_free(preio);
  662. }
  663. io->loop = loop;
  664. // NOTE: use new_loop readbuf
  665. io->readbuf.base = loop->readbuf.base;
  666. io->readbuf.len = loop->readbuf.len;
  667. loop->ios.ptr[fd] = io;
  668. }
  669. bool hio_exists(hloop_t* loop, int fd) {
  670. if (fd >= loop->ios.maxsize) {
  671. return false;
  672. }
  673. return loop->ios.ptr[fd] != NULL;
  674. }
  675. int hio_add(hio_t* io, hio_cb cb, int events) {
  676. printd("hio_add fd=%d io->events=%d events=%d\n", io->fd, io->events, events);
  677. #ifdef OS_WIN
  678. // Windows iowatcher not work on stdio
  679. if (io->fd < 3) return -1;
  680. #endif
  681. hloop_t* loop = io->loop;
  682. if (!io->active) {
  683. EVENT_ADD(loop, io, cb);
  684. loop->nios++;
  685. }
  686. if (!io->ready) {
  687. hio_ready(io);
  688. }
  689. if (cb) {
  690. io->cb = (hevent_cb)cb;
  691. }
  692. if (!(io->events & events)) {
  693. iowatcher_add_event(loop, io->fd, events);
  694. io->events |= events;
  695. }
  696. return 0;
  697. }
  698. int hio_del(hio_t* io, int events) {
  699. printd("hio_del fd=%d io->events=%d events=%d\n", io->fd, io->events, events);
  700. #ifdef OS_WIN
  701. // Windows iowatcher not work on stdio
  702. if (io->fd < 3) return -1;
  703. #endif
  704. if (!io->active) return -1;
  705. if (io->events & events) {
  706. iowatcher_del_event(io->loop, io->fd, events);
  707. io->events &= ~events;
  708. }
  709. if (io->events == 0) {
  710. io->loop->nios--;
  711. // NOTE: not EVENT_DEL, avoid free
  712. EVENT_INACTIVE(io);
  713. }
  714. return 0;
  715. }
  716. static void hio_close_event_cb(hevent_t* ev) {
  717. hio_t* io = (hio_t*)ev->userdata;
  718. uint32_t id = (uintptr_t)ev->privdata;
  719. if (io->id != id) return;
  720. hio_close(io);
  721. }
  722. int hio_close_async(hio_t* io) {
  723. hevent_t ev;
  724. memset(&ev, 0, sizeof(ev));
  725. ev.cb = hio_close_event_cb;
  726. ev.userdata = io;
  727. ev.privdata = (void*)(uintptr_t)io->id;
  728. hloop_post_event(io->loop, &ev);
  729. return 0;
  730. }
  731. //------------------high-level apis-------------------------------------------
  732. hio_t* hread(hloop_t* loop, int fd, void* buf, size_t len, hread_cb read_cb) {
  733. hio_t* io = hio_get(loop, fd);
  734. assert(io != NULL);
  735. if (buf && len) {
  736. io->readbuf.base = (char*)buf;
  737. io->readbuf.len = len;
  738. }
  739. if (read_cb) {
  740. io->read_cb = read_cb;
  741. }
  742. hio_read(io);
  743. return io;
  744. }
  745. hio_t* hwrite(hloop_t* loop, int fd, const void* buf, size_t len, hwrite_cb write_cb) {
  746. hio_t* io = hio_get(loop, fd);
  747. assert(io != NULL);
  748. if (write_cb) {
  749. io->write_cb = write_cb;
  750. }
  751. hio_write(io, buf, len);
  752. return io;
  753. }
  754. hio_t* haccept(hloop_t* loop, int listenfd, haccept_cb accept_cb) {
  755. hio_t* io = hio_get(loop, listenfd);
  756. assert(io != NULL);
  757. if (accept_cb) {
  758. io->accept_cb = accept_cb;
  759. }
  760. if (hio_accept(io) != 0) return NULL;
  761. return io;
  762. }
  763. hio_t* hconnect (hloop_t* loop, int connfd, hconnect_cb connect_cb) {
  764. hio_t* io = hio_get(loop, connfd);
  765. assert(io != NULL);
  766. if (connect_cb) {
  767. io->connect_cb = connect_cb;
  768. }
  769. if (hio_connect(io) != 0) return NULL;
  770. return io;
  771. }
  772. void hclose (hloop_t* loop, int fd) {
  773. hio_t* io = hio_get(loop, fd);
  774. assert(io != NULL);
  775. hio_close(io);
  776. }
  777. hio_t* hrecv (hloop_t* loop, int connfd, void* buf, size_t len, hread_cb read_cb) {
  778. //hio_t* io = hio_get(loop, connfd);
  779. //assert(io != NULL);
  780. //io->recv = 1;
  781. //if (io->io_type != HIO_TYPE_SSL) {
  782. //io->io_type = HIO_TYPE_TCP;
  783. //}
  784. return hread(loop, connfd, buf, len, read_cb);
  785. }
  786. hio_t* hsend (hloop_t* loop, int connfd, const void* buf, size_t len, hwrite_cb write_cb) {
  787. //hio_t* io = hio_get(loop, connfd);
  788. //assert(io != NULL);
  789. //io->send = 1;
  790. //if (io->io_type != HIO_TYPE_SSL) {
  791. //io->io_type = HIO_TYPE_TCP;
  792. //}
  793. return hwrite(loop, connfd, buf, len, write_cb);
  794. }
  795. hio_t* hrecvfrom (hloop_t* loop, int sockfd, void* buf, size_t len, hread_cb read_cb) {
  796. //hio_t* io = hio_get(loop, sockfd);
  797. //assert(io != NULL);
  798. //io->recvfrom = 1;
  799. //io->io_type = HIO_TYPE_UDP;
  800. return hread(loop, sockfd, buf, len, read_cb);
  801. }
  802. hio_t* hsendto (hloop_t* loop, int sockfd, const void* buf, size_t len, hwrite_cb write_cb) {
  803. //hio_t* io = hio_get(loop, sockfd);
  804. //assert(io != NULL);
  805. //io->sendto = 1;
  806. //io->io_type = HIO_TYPE_UDP;
  807. return hwrite(loop, sockfd, buf, len, write_cb);
  808. }
  809. //-----------------top-level apis---------------------------------------------
  810. hio_t* hio_create_socket(hloop_t* loop, const char* host, int port, hio_type_e type, hio_side_e side) {
  811. int sock_type = (type & HIO_TYPE_SOCK_STREAM) ? SOCK_STREAM :
  812. (type & HIO_TYPE_SOCK_DGRAM) ? SOCK_DGRAM :
  813. (type & HIO_TYPE_SOCK_RAW) ? SOCK_RAW : -1;
  814. if (sock_type == -1) return NULL;
  815. sockaddr_u addr;
  816. memset(&addr, 0, sizeof(addr));
  817. int ret = -1;
  818. #ifdef ENABLE_UDS
  819. if (port < 0) {
  820. sockaddr_set_path(&addr, host);
  821. ret = 0;
  822. }
  823. #endif
  824. if (port >= 0) {
  825. ret = sockaddr_set_ipport(&addr, host, port);
  826. }
  827. if (ret != 0) {
  828. // fprintf(stderr, "unknown host: %s\n", host);
  829. return NULL;
  830. }
  831. int sockfd = socket(addr.sa.sa_family, sock_type, 0);
  832. if (sockfd < 0) {
  833. perror("socket");
  834. return NULL;
  835. }
  836. hio_t* io = NULL;
  837. if (side == HIO_SERVER_SIDE) {
  838. #ifdef OS_UNIX
  839. so_reuseaddr(sockfd, 1);
  840. // so_reuseport(sockfd, 1);
  841. #endif
  842. if (bind(sockfd, &addr.sa, sockaddr_len(&addr)) < 0) {
  843. perror("bind");
  844. closesocket(sockfd);
  845. return NULL;
  846. }
  847. if (sock_type == SOCK_STREAM) {
  848. if (listen(sockfd, SOMAXCONN) < 0) {
  849. perror("listen");
  850. closesocket(sockfd);
  851. return NULL;
  852. }
  853. }
  854. }
  855. io = hio_get(loop, sockfd);
  856. assert(io != NULL);
  857. io->io_type = type;
  858. if (side == HIO_SERVER_SIDE) {
  859. hio_set_localaddr(io, &addr.sa, sockaddr_len(&addr));
  860. io->priority = HEVENT_HIGH_PRIORITY;
  861. } else {
  862. hio_set_peeraddr(io, &addr.sa, sockaddr_len(&addr));
  863. }
  864. return io;
  865. }
  866. hio_t* hloop_create_tcp_server (hloop_t* loop, const char* host, int port, haccept_cb accept_cb) {
  867. hio_t* io = hio_create_socket(loop, host, port, HIO_TYPE_TCP, HIO_SERVER_SIDE);
  868. if (io == NULL) return NULL;
  869. hio_setcb_accept(io, accept_cb);
  870. if (hio_accept(io) != 0) return NULL;
  871. return io;
  872. }
  873. hio_t* hloop_create_tcp_client (hloop_t* loop, const char* host, int port, hconnect_cb connect_cb, hclose_cb close_cb) {
  874. hio_t* io = hio_create_socket(loop, host, port, HIO_TYPE_TCP, HIO_CLIENT_SIDE);
  875. if (io == NULL) return NULL;
  876. hio_setcb_connect(io, connect_cb);
  877. hio_setcb_close(io, close_cb);
  878. if (hio_connect(io) != 0) return NULL;
  879. return io;
  880. }
  881. hio_t* hloop_create_ssl_server (hloop_t* loop, const char* host, int port, haccept_cb accept_cb) {
  882. hio_t* io = hio_create_socket(loop, host, port, HIO_TYPE_SSL, HIO_SERVER_SIDE);
  883. if (io == NULL) return NULL;
  884. hio_setcb_accept(io, accept_cb);
  885. if (hio_accept(io) != 0) return NULL;
  886. return io;
  887. }
  888. hio_t* hloop_create_ssl_client (hloop_t* loop, const char* host, int port, hconnect_cb connect_cb, hclose_cb close_cb) {
  889. hio_t* io = hio_create_socket(loop, host, port, HIO_TYPE_SSL, HIO_CLIENT_SIDE);
  890. if (io == NULL) return NULL;
  891. hio_setcb_connect(io, connect_cb);
  892. hio_setcb_close(io, close_cb);
  893. if (hio_connect(io) != 0) return NULL;
  894. return io;
  895. }
  896. hio_t* hloop_create_udp_server(hloop_t* loop, const char* host, int port) {
  897. return hio_create_socket(loop, host, port, HIO_TYPE_UDP, HIO_SERVER_SIDE);
  898. }
  899. hio_t* hloop_create_udp_client(hloop_t* loop, const char* host, int port) {
  900. return hio_create_socket(loop, host, port, HIO_TYPE_UDP, HIO_CLIENT_SIDE);
  901. }