hloop.c 27 KB

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