hloop.c 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106
  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. // signals
  360. printd("cleanup signals...\n");
  361. for (int i = 0; i < loop->signals.maxsize; ++i) {
  362. hsignal_t* sig = loop->signals.ptr[i];
  363. HV_FREE(sig);
  364. }
  365. signal_array_cleanup(&loop->signals);
  366. // readbuf
  367. if (loop->readbuf.base && loop->readbuf.len) {
  368. HV_FREE(loop->readbuf.base);
  369. loop->readbuf.base = NULL;
  370. loop->readbuf.len = 0;
  371. }
  372. // iowatcher
  373. iowatcher_cleanup(loop);
  374. // custom_events
  375. hmutex_lock(&loop->custom_events_mutex);
  376. hloop_destroy_eventfds(loop);
  377. event_queue_cleanup(&loop->custom_events);
  378. hmutex_unlock(&loop->custom_events_mutex);
  379. hmutex_destroy(&loop->custom_events_mutex);
  380. }
  381. hloop_t* hloop_new(int flags) {
  382. hloop_t* loop;
  383. HV_ALLOC_SIZEOF(loop);
  384. hloop_init(loop);
  385. loop->flags |= flags;
  386. hlogd("hloop_new tid=%ld", loop->tid);
  387. return loop;
  388. }
  389. void hloop_free(hloop_t** pp) {
  390. if (pp == NULL || *pp == NULL) return;
  391. hloop_t* loop = *pp;
  392. if (loop->status == HLOOP_STATUS_DESTROY) return;
  393. loop->status = HLOOP_STATUS_DESTROY;
  394. hlogd("hloop_free tid=%ld", hv_gettid());
  395. hloop_cleanup(loop);
  396. HV_FREE(loop);
  397. *pp = NULL;
  398. }
  399. // while (loop->status) { hloop_process_events(loop); }
  400. int hloop_run(hloop_t* loop) {
  401. if (loop == NULL) return -1;
  402. if (loop->status == HLOOP_STATUS_RUNNING) return -2;
  403. loop->status = HLOOP_STATUS_RUNNING;
  404. loop->pid = hv_getpid();
  405. loop->tid = hv_gettid();
  406. hlogd("hloop_run tid=%ld", loop->tid);
  407. if (loop->intern_nevents == 0) {
  408. hmutex_lock(&loop->custom_events_mutex);
  409. if (loop->eventfds[EVENTFDS_WRITE_INDEX] == -1) {
  410. hloop_create_eventfds(loop);
  411. }
  412. hmutex_unlock(&loop->custom_events_mutex);
  413. #ifdef DEBUG
  414. htimer_add(loop, hloop_stat_timer_cb, HLOOP_STAT_TIMEOUT, INFINITE);
  415. ++loop->intern_nevents;
  416. #endif
  417. }
  418. while (loop->status != HLOOP_STATUS_STOP) {
  419. if (loop->status == HLOOP_STATUS_PAUSE) {
  420. hv_msleep(HLOOP_PAUSE_TIME);
  421. hloop_update_time(loop);
  422. continue;
  423. }
  424. ++loop->loop_cnt;
  425. if ((loop->flags & HLOOP_FLAG_QUIT_WHEN_NO_ACTIVE_EVENTS) &&
  426. loop->nactives <= loop->intern_nevents) {
  427. break;
  428. }
  429. hloop_process_events(loop, HLOOP_MAX_BLOCK_TIME);
  430. if (loop->flags & HLOOP_FLAG_RUN_ONCE) {
  431. break;
  432. }
  433. }
  434. loop->status = HLOOP_STATUS_STOP;
  435. loop->end_hrtime = gethrtime_us();
  436. if (loop->flags & HLOOP_FLAG_AUTO_FREE) {
  437. hloop_free(&loop);
  438. }
  439. return 0;
  440. }
  441. int hloop_wakeup(hloop_t* loop) {
  442. hevent_t ev;
  443. memset(&ev, 0, sizeof(ev));
  444. hloop_post_event(loop, &ev);
  445. return 0;
  446. }
  447. int hloop_stop(hloop_t* loop) {
  448. if (loop == NULL) return -1;
  449. if (loop->status == HLOOP_STATUS_STOP) return -2;
  450. hlogd("hloop_stop tid=%ld", hv_gettid());
  451. if (hv_gettid() != loop->tid) {
  452. hloop_wakeup(loop);
  453. }
  454. loop->status = HLOOP_STATUS_STOP;
  455. return 0;
  456. }
  457. int hloop_pause(hloop_t* loop) {
  458. if (loop->status == HLOOP_STATUS_RUNNING) {
  459. loop->status = HLOOP_STATUS_PAUSE;
  460. }
  461. return 0;
  462. }
  463. int hloop_resume(hloop_t* loop) {
  464. if (loop->status == HLOOP_STATUS_PAUSE) {
  465. loop->status = HLOOP_STATUS_RUNNING;
  466. }
  467. return 0;
  468. }
  469. hloop_status_e hloop_status(hloop_t* loop) {
  470. return loop->status;
  471. }
  472. void hloop_update_time(hloop_t* loop) {
  473. loop->cur_hrtime = gethrtime_us();
  474. if (hloop_now(loop) != time(NULL)) {
  475. // systemtime changed, we adjust start_ms
  476. loop->start_ms = gettimeofday_ms() - (loop->cur_hrtime - loop->start_hrtime) / 1000;
  477. }
  478. }
  479. uint64_t hloop_now(hloop_t* loop) {
  480. return loop->start_ms / 1000 + (loop->cur_hrtime - loop->start_hrtime) / 1000000;
  481. }
  482. uint64_t hloop_now_ms(hloop_t* loop) {
  483. return loop->start_ms + (loop->cur_hrtime - loop->start_hrtime) / 1000;
  484. }
  485. uint64_t hloop_now_us(hloop_t* loop) {
  486. return loop->start_ms * 1000 + (loop->cur_hrtime - loop->start_hrtime);
  487. }
  488. uint64_t hloop_now_hrtime(hloop_t* loop) {
  489. return loop->cur_hrtime;
  490. }
  491. uint64_t hio_last_read_time(hio_t* io) {
  492. hloop_t* loop = io->loop;
  493. return loop->start_ms + (io->last_read_hrtime - loop->start_hrtime) / 1000;
  494. }
  495. uint64_t hio_last_write_time(hio_t* io) {
  496. hloop_t* loop = io->loop;
  497. return loop->start_ms + (io->last_write_hrtime - loop->start_hrtime) / 1000;
  498. }
  499. long hloop_pid(hloop_t* loop) {
  500. return loop->pid;
  501. }
  502. long hloop_tid(hloop_t* loop) {
  503. return loop->tid;
  504. }
  505. uint64_t hloop_count(hloop_t* loop) {
  506. return loop->loop_cnt;
  507. }
  508. uint32_t hloop_nios(hloop_t* loop) {
  509. return loop->nios;
  510. }
  511. uint32_t hloop_ntimers(hloop_t* loop) {
  512. return loop->ntimers;
  513. }
  514. uint32_t hloop_nidles(hloop_t* loop) {
  515. return loop->nidles;
  516. }
  517. uint32_t hloop_nactives(hloop_t* loop) {
  518. return loop->nactives;
  519. }
  520. void hloop_set_userdata(hloop_t* loop, void* userdata) {
  521. loop->userdata = userdata;
  522. }
  523. void* hloop_userdata(hloop_t* loop) {
  524. return loop->userdata;
  525. }
  526. static hloop_t* s_signal_loop = NULL;
  527. static void signal_handler(int signo) {
  528. if (!s_signal_loop) return;
  529. if (signo >= s_signal_loop->signals.maxsize) return;
  530. hsignal_t* sig = s_signal_loop->signals.ptr[signo];
  531. if (!sig) return;
  532. hloop_post_event(s_signal_loop, sig);
  533. }
  534. hsignal_t* hsignal_add(hloop_t* loop, hsignal_cb cb, int signo) {
  535. int max_signo = 64;
  536. #ifdef _NSIG
  537. max_signo = _NSIG;
  538. #endif
  539. if (signo <= 0 || signo >= max_signo) {
  540. hloge("signo %d over %d!", signo, max_signo);
  541. return NULL;
  542. }
  543. if (loop->signals.maxsize == 0) {
  544. signal_array_init(&loop->signals, max_signo);
  545. }
  546. hsignal_t* sig = loop->signals.ptr[signo];
  547. if (sig == NULL) {
  548. HV_ALLOC_SIZEOF(sig);
  549. sig->loop = loop;
  550. sig->event_type = HEVENT_TYPE_SIGNAL;
  551. // NOTE: use event_id as signo
  552. sig->event_id = signo;
  553. sig->cb = cb;
  554. sig->priority = HEVENT_HIGHEST_PRIORITY;
  555. loop->signals.ptr[signo] = sig;
  556. loop->nsignals++;
  557. }
  558. EVENT_ACTIVE(sig);
  559. s_signal_loop = loop;
  560. signal(signo, signal_handler);
  561. return sig;
  562. }
  563. void hsignal_del(hsignal_t* sig) {
  564. if (!sig->active) return;
  565. hloop_t* loop = sig->loop;
  566. int signo = (int)sig->event_id;
  567. if (signo >= loop->signals.maxsize) return;
  568. loop->signals.ptr[signo] = NULL;
  569. loop->nsignals--;
  570. EVENT_DEL(sig);
  571. }
  572. hidle_t* hidle_add(hloop_t* loop, hidle_cb cb, uint32_t repeat) {
  573. hidle_t* idle;
  574. HV_ALLOC_SIZEOF(idle);
  575. idle->event_type = HEVENT_TYPE_IDLE;
  576. idle->priority = HEVENT_LOWEST_PRIORITY;
  577. idle->repeat = repeat;
  578. list_add(&idle->node, &loop->idles);
  579. EVENT_ADD(loop, idle, cb);
  580. loop->nidles++;
  581. return idle;
  582. }
  583. static void __hidle_del(hidle_t* idle) {
  584. if (idle->destroy) return;
  585. idle->destroy = 1;
  586. list_del(&idle->node);
  587. idle->loop->nidles--;
  588. }
  589. void hidle_del(hidle_t* idle) {
  590. if (!idle->active) return;
  591. __hidle_del(idle);
  592. EVENT_DEL(idle);
  593. }
  594. htimer_t* htimer_add(hloop_t* loop, htimer_cb cb, uint32_t timeout_ms, uint32_t repeat) {
  595. if (timeout_ms == 0) return NULL;
  596. htimeout_t* timer;
  597. HV_ALLOC_SIZEOF(timer);
  598. timer->event_type = HEVENT_TYPE_TIMEOUT;
  599. timer->priority = HEVENT_HIGHEST_PRIORITY;
  600. timer->repeat = repeat;
  601. timer->timeout = timeout_ms;
  602. hloop_update_time(loop);
  603. timer->next_timeout = loop->cur_hrtime + (uint64_t)timeout_ms * 1000;
  604. // NOTE: Limit granularity to 100ms
  605. if (timeout_ms >= 1000 && timeout_ms % 100 == 0) {
  606. timer->next_timeout = timer->next_timeout / 100000 * 100000;
  607. }
  608. heap_insert(&loop->timers, &timer->node);
  609. EVENT_ADD(loop, timer, cb);
  610. loop->ntimers++;
  611. return (htimer_t*)timer;
  612. }
  613. void htimer_reset(htimer_t* timer, uint32_t timeout_ms) {
  614. if (timer->event_type != HEVENT_TYPE_TIMEOUT) {
  615. return;
  616. }
  617. hloop_t* loop = timer->loop;
  618. htimeout_t* timeout = (htimeout_t*)timer;
  619. if (timer->destroy) {
  620. loop->ntimers++;
  621. } else {
  622. heap_remove(&loop->timers, &timer->node);
  623. }
  624. if (timer->repeat == 0) {
  625. timer->repeat = 1;
  626. }
  627. if (timeout_ms > 0) {
  628. timeout->timeout = timeout_ms;
  629. }
  630. timer->next_timeout = loop->cur_hrtime + (uint64_t)timeout->timeout * 1000;
  631. // NOTE: Limit granularity to 100ms
  632. if (timeout->timeout >= 1000 && timeout->timeout % 100 == 0) {
  633. timer->next_timeout = timer->next_timeout / 100000 * 100000;
  634. }
  635. heap_insert(&loop->timers, &timer->node);
  636. EVENT_RESET(timer);
  637. }
  638. htimer_t* htimer_add_period(hloop_t* loop, htimer_cb cb,
  639. int8_t minute, int8_t hour, int8_t day,
  640. int8_t week, int8_t month, uint32_t repeat) {
  641. if (minute > 59 || hour > 23 || day > 31 || week > 6 || month > 12) {
  642. return NULL;
  643. }
  644. hperiod_t* timer;
  645. HV_ALLOC_SIZEOF(timer);
  646. timer->event_type = HEVENT_TYPE_PERIOD;
  647. timer->priority = HEVENT_HIGH_PRIORITY;
  648. timer->repeat = repeat;
  649. timer->minute = minute;
  650. timer->hour = hour;
  651. timer->day = day;
  652. timer->month = month;
  653. timer->week = week;
  654. timer->next_timeout = (uint64_t)cron_next_timeout(minute, hour, day, week, month) * 1000000;
  655. heap_insert(&loop->realtimers, &timer->node);
  656. EVENT_ADD(loop, timer, cb);
  657. loop->ntimers++;
  658. return (htimer_t*)timer;
  659. }
  660. static void __htimer_del(htimer_t* timer) {
  661. if (timer->destroy) return;
  662. if (timer->event_type == HEVENT_TYPE_TIMEOUT) {
  663. heap_remove(&timer->loop->timers, &timer->node);
  664. } else if (timer->event_type == HEVENT_TYPE_PERIOD) {
  665. heap_remove(&timer->loop->realtimers, &timer->node);
  666. }
  667. timer->loop->ntimers--;
  668. timer->destroy = 1;
  669. }
  670. void htimer_del(htimer_t* timer) {
  671. if (!timer->active) return;
  672. __htimer_del(timer);
  673. EVENT_DEL(timer);
  674. }
  675. const char* hio_engine() {
  676. #ifdef EVENT_SELECT
  677. return "select";
  678. #elif defined(EVENT_POLL)
  679. return "poll";
  680. #elif defined(EVENT_EPOLL)
  681. return "epoll";
  682. #elif defined(EVENT_KQUEUE)
  683. return "kqueue";
  684. #elif defined(EVENT_IOCP)
  685. return "iocp";
  686. #elif defined(EVENT_PORT)
  687. return "evport";
  688. #else
  689. return "noevent";
  690. #endif
  691. }
  692. static inline hio_t* __hio_get(hloop_t* loop, int fd) {
  693. if (fd >= loop->ios.maxsize) {
  694. int newsize = ceil2e(fd);
  695. newsize = MAX(newsize, IO_ARRAY_INIT_SIZE);
  696. io_array_resize(&loop->ios, newsize > fd ? newsize : 2*fd);
  697. }
  698. return loop->ios.ptr[fd];
  699. }
  700. hio_t* hio_get(hloop_t* loop, int fd) {
  701. hio_t* io = __hio_get(loop, fd);
  702. if (io == NULL) {
  703. HV_ALLOC_SIZEOF(io);
  704. hio_init(io);
  705. io->event_type = HEVENT_TYPE_IO;
  706. io->loop = loop;
  707. io->fd = fd;
  708. loop->ios.ptr[fd] = io;
  709. }
  710. if (!io->ready) {
  711. hio_ready(io);
  712. }
  713. return io;
  714. }
  715. void hio_detach(hio_t* io) {
  716. hloop_t* loop = io->loop;
  717. int fd = io->fd;
  718. assert(loop != NULL && fd < loop->ios.maxsize);
  719. loop->ios.ptr[fd] = NULL;
  720. }
  721. void hio_attach(hloop_t* loop, hio_t* io) {
  722. int fd = io->fd;
  723. // NOTE: hio was not freed for reused when closed, but attached hio can't be reused,
  724. // so we need to free it if fd exists to avoid memory leak.
  725. hio_t* preio = __hio_get(loop, fd);
  726. if (preio != NULL && preio != io) {
  727. hio_free(preio);
  728. }
  729. io->loop = loop;
  730. // NOTE: use new_loop readbuf
  731. hio_use_loop_readbuf(io);
  732. loop->ios.ptr[fd] = io;
  733. }
  734. bool hio_exists(hloop_t* loop, int fd) {
  735. if (fd >= loop->ios.maxsize) {
  736. return false;
  737. }
  738. return loop->ios.ptr[fd] != NULL;
  739. }
  740. int hio_add(hio_t* io, hio_cb cb, int events) {
  741. printd("hio_add fd=%d io->events=%d events=%d\n", io->fd, io->events, events);
  742. #ifdef OS_WIN
  743. // Windows iowatcher not work on stdio
  744. if (io->fd < 3) return -1;
  745. #endif
  746. hloop_t* loop = io->loop;
  747. if (!io->active) {
  748. EVENT_ADD(loop, io, cb);
  749. loop->nios++;
  750. }
  751. if (!io->ready) {
  752. hio_ready(io);
  753. }
  754. if (cb) {
  755. io->cb = (hevent_cb)cb;
  756. }
  757. if (!(io->events & events)) {
  758. iowatcher_add_event(loop, io->fd, events);
  759. io->events |= events;
  760. }
  761. return 0;
  762. }
  763. int hio_del(hio_t* io, int events) {
  764. printd("hio_del fd=%d io->events=%d events=%d\n", io->fd, io->events, events);
  765. #ifdef OS_WIN
  766. // Windows iowatcher not work on stdio
  767. if (io->fd < 3) return -1;
  768. #endif
  769. if (!io->active) return -1;
  770. if (io->events & events) {
  771. iowatcher_del_event(io->loop, io->fd, events);
  772. io->events &= ~events;
  773. }
  774. if (io->events == 0) {
  775. io->loop->nios--;
  776. // NOTE: not EVENT_DEL, avoid free
  777. EVENT_INACTIVE(io);
  778. }
  779. return 0;
  780. }
  781. static void hio_close_event_cb(hevent_t* ev) {
  782. hio_t* io = (hio_t*)ev->userdata;
  783. uint32_t id = (uintptr_t)ev->privdata;
  784. if (io->id != id) return;
  785. hio_close(io);
  786. }
  787. int hio_close_async(hio_t* io) {
  788. hevent_t ev;
  789. memset(&ev, 0, sizeof(ev));
  790. ev.cb = hio_close_event_cb;
  791. ev.userdata = io;
  792. ev.privdata = (void*)(uintptr_t)io->id;
  793. hloop_post_event(io->loop, &ev);
  794. return 0;
  795. }
  796. //------------------high-level apis-------------------------------------------
  797. hio_t* hread(hloop_t* loop, int fd, void* buf, size_t len, hread_cb read_cb) {
  798. hio_t* io = hio_get(loop, fd);
  799. assert(io != NULL);
  800. if (buf && len) {
  801. io->readbuf.base = (char*)buf;
  802. io->readbuf.len = len;
  803. }
  804. if (read_cb) {
  805. io->read_cb = read_cb;
  806. }
  807. hio_read(io);
  808. return io;
  809. }
  810. hio_t* hwrite(hloop_t* loop, int fd, const void* buf, size_t len, hwrite_cb write_cb) {
  811. hio_t* io = hio_get(loop, fd);
  812. assert(io != NULL);
  813. if (write_cb) {
  814. io->write_cb = write_cb;
  815. }
  816. hio_write(io, buf, len);
  817. return io;
  818. }
  819. hio_t* haccept(hloop_t* loop, int listenfd, haccept_cb accept_cb) {
  820. hio_t* io = hio_get(loop, listenfd);
  821. assert(io != NULL);
  822. if (accept_cb) {
  823. io->accept_cb = accept_cb;
  824. }
  825. if (hio_accept(io) != 0) return NULL;
  826. return io;
  827. }
  828. hio_t* hconnect (hloop_t* loop, int connfd, hconnect_cb connect_cb) {
  829. hio_t* io = hio_get(loop, connfd);
  830. assert(io != NULL);
  831. if (connect_cb) {
  832. io->connect_cb = connect_cb;
  833. }
  834. if (hio_connect(io) != 0) return NULL;
  835. return io;
  836. }
  837. void hclose (hloop_t* loop, int fd) {
  838. hio_t* io = hio_get(loop, fd);
  839. assert(io != NULL);
  840. hio_close(io);
  841. }
  842. hio_t* hrecv (hloop_t* loop, int connfd, void* buf, size_t len, hread_cb read_cb) {
  843. //hio_t* io = hio_get(loop, connfd);
  844. //assert(io != NULL);
  845. //io->recv = 1;
  846. //if (io->io_type != HIO_TYPE_SSL) {
  847. //io->io_type = HIO_TYPE_TCP;
  848. //}
  849. return hread(loop, connfd, buf, len, read_cb);
  850. }
  851. hio_t* hsend (hloop_t* loop, int connfd, const void* buf, size_t len, hwrite_cb write_cb) {
  852. //hio_t* io = hio_get(loop, connfd);
  853. //assert(io != NULL);
  854. //io->send = 1;
  855. //if (io->io_type != HIO_TYPE_SSL) {
  856. //io->io_type = HIO_TYPE_TCP;
  857. //}
  858. return hwrite(loop, connfd, buf, len, write_cb);
  859. }
  860. hio_t* hrecvfrom (hloop_t* loop, int sockfd, void* buf, size_t len, hread_cb read_cb) {
  861. //hio_t* io = hio_get(loop, sockfd);
  862. //assert(io != NULL);
  863. //io->recvfrom = 1;
  864. //io->io_type = HIO_TYPE_UDP;
  865. return hread(loop, sockfd, buf, len, read_cb);
  866. }
  867. hio_t* hsendto (hloop_t* loop, int sockfd, const void* buf, size_t len, hwrite_cb write_cb) {
  868. //hio_t* io = hio_get(loop, sockfd);
  869. //assert(io != NULL);
  870. //io->sendto = 1;
  871. //io->io_type = HIO_TYPE_UDP;
  872. return hwrite(loop, sockfd, buf, len, write_cb);
  873. }
  874. //-----------------top-level apis---------------------------------------------
  875. hio_t* hio_create_socket(hloop_t* loop, const char* host, int port, hio_type_e type, hio_side_e side) {
  876. int sock_type = (type & HIO_TYPE_SOCK_STREAM) ? SOCK_STREAM :
  877. (type & HIO_TYPE_SOCK_DGRAM) ? SOCK_DGRAM :
  878. (type & HIO_TYPE_SOCK_RAW) ? SOCK_RAW : -1;
  879. if (sock_type == -1) return NULL;
  880. sockaddr_u addr;
  881. memset(&addr, 0, sizeof(addr));
  882. int ret = -1;
  883. #ifdef ENABLE_UDS
  884. if (port < 0) {
  885. sockaddr_set_path(&addr, host);
  886. ret = 0;
  887. }
  888. #endif
  889. if (port >= 0) {
  890. ret = sockaddr_set_ipport(&addr, host, port);
  891. }
  892. if (ret != 0) {
  893. // fprintf(stderr, "unknown host: %s\n", host);
  894. return NULL;
  895. }
  896. int sockfd = socket(addr.sa.sa_family, sock_type, 0);
  897. if (sockfd < 0) {
  898. perror("socket");
  899. return NULL;
  900. }
  901. hio_t* io = NULL;
  902. if (side == HIO_SERVER_SIDE) {
  903. #ifdef OS_UNIX
  904. so_reuseaddr(sockfd, 1);
  905. // so_reuseport(sockfd, 1);
  906. #endif
  907. if (addr.sa.sa_family == AF_INET6) {
  908. ip_v6only(sockfd, 0);
  909. }
  910. if (bind(sockfd, &addr.sa, sockaddr_len(&addr)) < 0) {
  911. perror("bind");
  912. closesocket(sockfd);
  913. return NULL;
  914. }
  915. if (sock_type == SOCK_STREAM) {
  916. if (listen(sockfd, SOMAXCONN) < 0) {
  917. perror("listen");
  918. closesocket(sockfd);
  919. return NULL;
  920. }
  921. }
  922. }
  923. io = hio_get(loop, sockfd);
  924. assert(io != NULL);
  925. io->io_type = type;
  926. if (side == HIO_SERVER_SIDE) {
  927. hio_set_localaddr(io, &addr.sa, sockaddr_len(&addr));
  928. io->priority = HEVENT_HIGH_PRIORITY;
  929. } else {
  930. hio_set_peeraddr(io, &addr.sa, sockaddr_len(&addr));
  931. }
  932. return io;
  933. }
  934. hio_t* hloop_create_tcp_server (hloop_t* loop, const char* host, int port, haccept_cb accept_cb) {
  935. hio_t* io = hio_create_socket(loop, host, port, HIO_TYPE_TCP, HIO_SERVER_SIDE);
  936. if (io == NULL) return NULL;
  937. hio_setcb_accept(io, accept_cb);
  938. if (hio_accept(io) != 0) return NULL;
  939. return io;
  940. }
  941. hio_t* hloop_create_tcp_client (hloop_t* loop, const char* host, int port, hconnect_cb connect_cb, hclose_cb close_cb) {
  942. hio_t* io = hio_create_socket(loop, host, port, HIO_TYPE_TCP, HIO_CLIENT_SIDE);
  943. if (io == NULL) return NULL;
  944. hio_setcb_connect(io, connect_cb);
  945. hio_setcb_close(io, close_cb);
  946. if (hio_connect(io) != 0) return NULL;
  947. return io;
  948. }
  949. hio_t* hloop_create_ssl_server (hloop_t* loop, const char* host, int port, haccept_cb accept_cb) {
  950. hio_t* io = hio_create_socket(loop, host, port, HIO_TYPE_SSL, HIO_SERVER_SIDE);
  951. if (io == NULL) return NULL;
  952. hio_setcb_accept(io, accept_cb);
  953. if (hio_accept(io) != 0) return NULL;
  954. return io;
  955. }
  956. hio_t* hloop_create_ssl_client (hloop_t* loop, const char* host, int port, hconnect_cb connect_cb, hclose_cb close_cb) {
  957. hio_t* io = hio_create_socket(loop, host, port, HIO_TYPE_SSL, HIO_CLIENT_SIDE);
  958. if (io == NULL) return NULL;
  959. hio_setcb_connect(io, connect_cb);
  960. hio_setcb_close(io, close_cb);
  961. if (hio_connect(io) != 0) return NULL;
  962. return io;
  963. }
  964. hio_t* hloop_create_udp_server(hloop_t* loop, const char* host, int port) {
  965. return hio_create_socket(loop, host, port, HIO_TYPE_UDP, HIO_SERVER_SIDE);
  966. }
  967. hio_t* hloop_create_udp_client(hloop_t* loop, const char* host, int port) {
  968. return hio_create_socket(loop, host, port, HIO_TYPE_UDP, HIO_CLIENT_SIDE);
  969. }
  970. int hio_create_pipe(hloop_t* loop, hio_t* pipeio[2]) {
  971. int pipefd[2];
  972. hio_type_e type = HIO_TYPE_PIPE;
  973. #if defined(OS_UNIX) && HAVE_PIPE
  974. if (pipe(pipefd) != 0) {
  975. hloge("pipe create failed!");
  976. return -1;
  977. }
  978. #else
  979. if (Socketpair(AF_INET, SOCK_STREAM, 0, pipefd) != 0) {
  980. hloge("socketpair create failed!");
  981. return -1;
  982. }
  983. type = HIO_TYPE_TCP;
  984. #endif
  985. pipeio[0] = hio_get(loop, pipefd[0]);
  986. pipeio[1] = hio_get(loop, pipefd[1]);
  987. pipeio[0]->io_type = type;
  988. pipeio[1]->io_type = type;
  989. return 0;
  990. }