hloop.c 31 KB

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