hloop.c 29 KB

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