1
0

hloop.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986
  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. uint64_t hloop_count(hloop_t* loop) {
  465. return loop->loop_cnt;
  466. }
  467. uint32_t hloop_nios(hloop_t* loop) {
  468. return loop->nios;
  469. }
  470. uint32_t hloop_ntimers(hloop_t* loop) {
  471. return loop->ntimers;
  472. }
  473. uint32_t hloop_nidles(hloop_t* loop) {
  474. return loop->nidles;
  475. }
  476. uint32_t hloop_nactives(hloop_t* loop) {
  477. return loop->nactives;
  478. }
  479. void hloop_set_userdata(hloop_t* loop, void* userdata) {
  480. loop->userdata = userdata;
  481. }
  482. void* hloop_userdata(hloop_t* loop) {
  483. return loop->userdata;
  484. }
  485. hidle_t* hidle_add(hloop_t* loop, hidle_cb cb, uint32_t repeat) {
  486. hidle_t* idle;
  487. HV_ALLOC_SIZEOF(idle);
  488. idle->event_type = HEVENT_TYPE_IDLE;
  489. idle->priority = HEVENT_LOWEST_PRIORITY;
  490. idle->repeat = repeat;
  491. list_add(&idle->node, &loop->idles);
  492. EVENT_ADD(loop, idle, cb);
  493. loop->nidles++;
  494. return idle;
  495. }
  496. static void __hidle_del(hidle_t* idle) {
  497. if (idle->destroy) return;
  498. idle->destroy = 1;
  499. list_del(&idle->node);
  500. idle->loop->nidles--;
  501. }
  502. void hidle_del(hidle_t* idle) {
  503. if (!idle->active) return;
  504. __hidle_del(idle);
  505. EVENT_DEL(idle);
  506. }
  507. htimer_t* htimer_add(hloop_t* loop, htimer_cb cb, uint32_t timeout, uint32_t repeat) {
  508. if (timeout == 0) return NULL;
  509. htimeout_t* timer;
  510. HV_ALLOC_SIZEOF(timer);
  511. timer->event_type = HEVENT_TYPE_TIMEOUT;
  512. timer->priority = HEVENT_HIGHEST_PRIORITY;
  513. timer->repeat = repeat;
  514. timer->timeout = timeout;
  515. hloop_update_time(loop);
  516. timer->next_timeout = hloop_now_hrtime(loop) + (uint64_t)timeout*1000;
  517. // NOTE: Limit granularity to 100ms
  518. if (timeout >= 1000 && timeout % 100 == 0) {
  519. timer->next_timeout = timer->next_timeout / 100000 * 100000;
  520. }
  521. heap_insert(&loop->timers, &timer->node);
  522. EVENT_ADD(loop, timer, cb);
  523. loop->ntimers++;
  524. return (htimer_t*)timer;
  525. }
  526. void htimer_reset(htimer_t* timer) {
  527. if (timer->event_type != HEVENT_TYPE_TIMEOUT) {
  528. return;
  529. }
  530. hloop_t* loop = timer->loop;
  531. htimeout_t* timeout = (htimeout_t*)timer;
  532. if (timer->destroy) {
  533. loop->ntimers++;
  534. } else {
  535. heap_remove(&loop->timers, &timer->node);
  536. }
  537. if (timer->repeat == 0) {
  538. timer->repeat = 1;
  539. }
  540. timer->next_timeout = hloop_now_hrtime(loop) + (uint64_t)timeout->timeout*1000;
  541. // NOTE: Limit granularity to 100ms
  542. if (timeout->timeout >= 1000 && timeout->timeout % 100 == 0) {
  543. timer->next_timeout = timer->next_timeout / 100000 * 100000;
  544. }
  545. heap_insert(&loop->timers, &timer->node);
  546. EVENT_RESET(timer);
  547. }
  548. htimer_t* htimer_add_period(hloop_t* loop, htimer_cb cb,
  549. int8_t minute, int8_t hour, int8_t day,
  550. int8_t week, int8_t month, uint32_t repeat) {
  551. if (minute > 59 || hour > 23 || day > 31 || week > 6 || month > 12) {
  552. return NULL;
  553. }
  554. hperiod_t* timer;
  555. HV_ALLOC_SIZEOF(timer);
  556. timer->event_type = HEVENT_TYPE_PERIOD;
  557. timer->priority = HEVENT_HIGH_PRIORITY;
  558. timer->repeat = repeat;
  559. timer->minute = minute;
  560. timer->hour = hour;
  561. timer->day = day;
  562. timer->month = month;
  563. timer->week = week;
  564. timer->next_timeout = (uint64_t)cron_next_timeout(minute, hour, day, week, month) * 1000000;
  565. heap_insert(&loop->timers, &timer->node);
  566. EVENT_ADD(loop, timer, cb);
  567. loop->ntimers++;
  568. return (htimer_t*)timer;
  569. }
  570. static void __htimer_del(htimer_t* timer) {
  571. if (timer->destroy) return;
  572. heap_remove(&timer->loop->timers, &timer->node);
  573. timer->loop->ntimers--;
  574. timer->destroy = 1;
  575. }
  576. void htimer_del(htimer_t* timer) {
  577. if (!timer->active) return;
  578. __htimer_del(timer);
  579. EVENT_DEL(timer);
  580. }
  581. const char* hio_engine() {
  582. #ifdef EVENT_SELECT
  583. return "select";
  584. #elif defined(EVENT_POLL)
  585. return "poll";
  586. #elif defined(EVENT_EPOLL)
  587. return "epoll";
  588. #elif defined(EVENT_KQUEUE)
  589. return "kqueue";
  590. #elif defined(EVENT_IOCP)
  591. return "iocp";
  592. #elif defined(EVENT_PORT)
  593. return "evport";
  594. #else
  595. return "noevent";
  596. #endif
  597. }
  598. hio_t* hio_get(hloop_t* loop, int fd) {
  599. if (fd >= loop->ios.maxsize) {
  600. int newsize = ceil2e(fd);
  601. io_array_resize(&loop->ios, newsize > fd ? newsize : 2*fd);
  602. }
  603. hio_t* io = loop->ios.ptr[fd];
  604. if (io == NULL) {
  605. HV_ALLOC_SIZEOF(io);
  606. hio_init(io);
  607. io->event_type = HEVENT_TYPE_IO;
  608. io->loop = loop;
  609. io->fd = fd;
  610. loop->ios.ptr[fd] = io;
  611. }
  612. if (!io->ready) {
  613. hio_ready(io);
  614. }
  615. return io;
  616. }
  617. void hio_detach(hio_t* io) {
  618. hloop_t* loop = io->loop;
  619. int fd = io->fd;
  620. assert(loop != NULL && fd < loop->ios.maxsize);
  621. loop->ios.ptr[fd] = NULL;
  622. }
  623. void hio_attach(hloop_t* loop, hio_t* io) {
  624. int fd = io->fd;
  625. if (fd >= loop->ios.maxsize) {
  626. int newsize = ceil2e(fd);
  627. io_array_resize(&loop->ios, newsize > fd ? newsize : 2*fd);
  628. }
  629. // NOTE: hio was not freed for reused when closed, but attached hio can't be reused,
  630. // so we need to free it if fd exists to avoid memory leak.
  631. hio_t* preio = loop->ios.ptr[fd];
  632. if (preio != NULL && preio != io) {
  633. hio_free(preio);
  634. }
  635. io->loop = loop;
  636. // NOTE: use new_loop readbuf
  637. io->readbuf.base = loop->readbuf.base;
  638. io->readbuf.len = loop->readbuf.len;
  639. loop->ios.ptr[fd] = io;
  640. }
  641. bool hio_exists(hloop_t* loop, int fd) {
  642. if (fd >= loop->ios.maxsize) {
  643. return false;
  644. }
  645. return loop->ios.ptr[fd] != NULL;
  646. }
  647. int hio_add(hio_t* io, hio_cb cb, int events) {
  648. printd("hio_add fd=%d io->events=%d events=%d\n", io->fd, io->events, events);
  649. #ifdef OS_WIN
  650. // Windows iowatcher not work on stdio
  651. if (io->fd < 3) return -1;
  652. #endif
  653. hloop_t* loop = io->loop;
  654. if (!io->active) {
  655. EVENT_ADD(loop, io, cb);
  656. loop->nios++;
  657. }
  658. if (!io->ready) {
  659. hio_ready(io);
  660. }
  661. if (cb) {
  662. io->cb = (hevent_cb)cb;
  663. }
  664. if (!(io->events & events)) {
  665. iowatcher_add_event(loop, io->fd, events);
  666. io->events |= events;
  667. }
  668. return 0;
  669. }
  670. int hio_del(hio_t* io, int events) {
  671. printd("hio_del fd=%d io->events=%d events=%d\n", io->fd, io->events, events);
  672. #ifdef OS_WIN
  673. // Windows iowatcher not work on stdio
  674. if (io->fd < 3) return -1;
  675. #endif
  676. if (!io->active) return -1;
  677. if (io->events & events) {
  678. iowatcher_del_event(io->loop, io->fd, events);
  679. io->events &= ~events;
  680. }
  681. if (io->events == 0) {
  682. io->loop->nios--;
  683. // NOTE: not EVENT_DEL, avoid free
  684. EVENT_INACTIVE(io);
  685. }
  686. return 0;
  687. }
  688. static void hio_close_event_cb(hevent_t* ev) {
  689. hio_t* io = (hio_t*)ev->userdata;
  690. uint32_t id = (uintptr_t)ev->privdata;
  691. if (io->id != id) return;
  692. hio_close(io);
  693. }
  694. int hio_close_async(hio_t* io) {
  695. hevent_t ev;
  696. memset(&ev, 0, sizeof(ev));
  697. ev.cb = hio_close_event_cb;
  698. ev.userdata = io;
  699. ev.privdata = (void*)(uintptr_t)io->id;
  700. hloop_post_event(io->loop, &ev);
  701. return 0;
  702. }
  703. //------------------high-level apis-------------------------------------------
  704. hio_t* hread(hloop_t* loop, int fd, void* buf, size_t len, hread_cb read_cb) {
  705. hio_t* io = hio_get(loop, fd);
  706. assert(io != NULL);
  707. if (buf && len) {
  708. io->readbuf.base = (char*)buf;
  709. io->readbuf.len = len;
  710. }
  711. if (read_cb) {
  712. io->read_cb = read_cb;
  713. }
  714. hio_read(io);
  715. return io;
  716. }
  717. hio_t* hwrite(hloop_t* loop, int fd, const void* buf, size_t len, hwrite_cb write_cb) {
  718. hio_t* io = hio_get(loop, fd);
  719. assert(io != NULL);
  720. if (write_cb) {
  721. io->write_cb = write_cb;
  722. }
  723. hio_write(io, buf, len);
  724. return io;
  725. }
  726. hio_t* haccept(hloop_t* loop, int listenfd, haccept_cb accept_cb) {
  727. hio_t* io = hio_get(loop, listenfd);
  728. assert(io != NULL);
  729. if (accept_cb) {
  730. io->accept_cb = accept_cb;
  731. }
  732. if (hio_accept(io) != 0) return NULL;
  733. return io;
  734. }
  735. hio_t* hconnect (hloop_t* loop, int connfd, hconnect_cb connect_cb) {
  736. hio_t* io = hio_get(loop, connfd);
  737. assert(io != NULL);
  738. if (connect_cb) {
  739. io->connect_cb = connect_cb;
  740. }
  741. if (hio_connect(io) != 0) return NULL;
  742. return io;
  743. }
  744. void hclose (hloop_t* loop, int fd) {
  745. hio_t* io = hio_get(loop, fd);
  746. assert(io != NULL);
  747. hio_close(io);
  748. }
  749. hio_t* hrecv (hloop_t* loop, int connfd, void* buf, size_t len, hread_cb read_cb) {
  750. //hio_t* io = hio_get(loop, connfd);
  751. //assert(io != NULL);
  752. //io->recv = 1;
  753. //if (io->io_type != HIO_TYPE_SSL) {
  754. //io->io_type = HIO_TYPE_TCP;
  755. //}
  756. return hread(loop, connfd, buf, len, read_cb);
  757. }
  758. hio_t* hsend (hloop_t* loop, int connfd, const void* buf, size_t len, hwrite_cb write_cb) {
  759. //hio_t* io = hio_get(loop, connfd);
  760. //assert(io != NULL);
  761. //io->send = 1;
  762. //if (io->io_type != HIO_TYPE_SSL) {
  763. //io->io_type = HIO_TYPE_TCP;
  764. //}
  765. return hwrite(loop, connfd, buf, len, write_cb);
  766. }
  767. hio_t* hrecvfrom (hloop_t* loop, int sockfd, void* buf, size_t len, hread_cb read_cb) {
  768. //hio_t* io = hio_get(loop, sockfd);
  769. //assert(io != NULL);
  770. //io->recvfrom = 1;
  771. //io->io_type = HIO_TYPE_UDP;
  772. return hread(loop, sockfd, buf, len, read_cb);
  773. }
  774. hio_t* hsendto (hloop_t* loop, int sockfd, const void* buf, size_t len, hwrite_cb write_cb) {
  775. //hio_t* io = hio_get(loop, sockfd);
  776. //assert(io != NULL);
  777. //io->sendto = 1;
  778. //io->io_type = HIO_TYPE_UDP;
  779. return hwrite(loop, sockfd, buf, len, write_cb);
  780. }
  781. //-----------------top-level apis---------------------------------------------
  782. hio_t* hio_create_socket(hloop_t* loop, const char* host, int port, hio_type_e type, hio_side_e side) {
  783. int sock_type = type & HIO_TYPE_SOCK_STREAM ? SOCK_STREAM :
  784. type & HIO_TYPE_SOCK_DGRAM ? SOCK_DGRAM :
  785. type & HIO_TYPE_SOCK_RAW ? SOCK_RAW : -1;
  786. if (sock_type == -1) return NULL;
  787. sockaddr_u addr;
  788. memset(&addr, 0, sizeof(addr));
  789. int ret = -1;
  790. #ifdef ENABLE_UDS
  791. if (port < 0) {
  792. sockaddr_set_path(&addr, host);
  793. ret = 0;
  794. }
  795. #endif
  796. if (port >= 0) {
  797. ret = sockaddr_set_ipport(&addr, host, port);
  798. }
  799. if (ret != 0) {
  800. // fprintf(stderr, "unknown host: %s\n", host);
  801. return NULL;
  802. }
  803. int sockfd = socket(addr.sa.sa_family, sock_type, 0);
  804. if (sockfd < 0) {
  805. perror("socket");
  806. return NULL;
  807. }
  808. hio_t* io = NULL;
  809. if (side == HIO_SERVER_SIDE) {
  810. #ifdef SO_REUSEADDR
  811. // NOTE: SO_REUSEADDR allow to reuse sockaddr of TIME_WAIT status
  812. int reuseaddr = 1;
  813. if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuseaddr, sizeof(int)) < 0) {
  814. perror("setsockopt");
  815. closesocket(sockfd);
  816. return NULL;
  817. }
  818. #endif
  819. if (bind(sockfd, &addr.sa, sockaddr_len(&addr)) < 0) {
  820. perror("bind");
  821. closesocket(sockfd);
  822. return NULL;
  823. }
  824. if (sock_type == SOCK_STREAM) {
  825. if (listen(sockfd, SOMAXCONN) < 0) {
  826. perror("listen");
  827. closesocket(sockfd);
  828. return NULL;
  829. }
  830. }
  831. }
  832. io = hio_get(loop, sockfd);
  833. assert(io != NULL);
  834. io->io_type = type;
  835. if (side == HIO_SERVER_SIDE) {
  836. hio_set_localaddr(io, &addr.sa, sockaddr_len(&addr));
  837. io->priority = HEVENT_HIGH_PRIORITY;
  838. } else {
  839. hio_set_peeraddr(io, &addr.sa, sockaddr_len(&addr));
  840. }
  841. return io;
  842. }
  843. hio_t* hloop_create_tcp_server (hloop_t* loop, const char* host, int port, haccept_cb accept_cb) {
  844. hio_t* io = hio_create_socket(loop, host, port, HIO_TYPE_TCP, HIO_SERVER_SIDE);
  845. if (io == NULL) return NULL;
  846. hio_setcb_accept(io, accept_cb);
  847. if (hio_accept(io) != 0) return NULL;
  848. return io;
  849. }
  850. hio_t* hloop_create_tcp_client (hloop_t* loop, const char* host, int port, hconnect_cb connect_cb) {
  851. hio_t* io = hio_create_socket(loop, host, port, HIO_TYPE_TCP, HIO_CLIENT_SIDE);
  852. if (io == NULL) return NULL;
  853. hio_setcb_connect(io, connect_cb);
  854. if (hio_connect(io) != 0) return NULL;
  855. return io;
  856. }
  857. hio_t* hloop_create_ssl_server (hloop_t* loop, const char* host, int port, haccept_cb accept_cb) {
  858. hio_t* io = hio_create_socket(loop, host, port, HIO_TYPE_SSL, HIO_SERVER_SIDE);
  859. if (io == NULL) return NULL;
  860. hio_setcb_accept(io, accept_cb);
  861. if (hio_accept(io) != 0) return NULL;
  862. return io;
  863. }
  864. hio_t* hloop_create_ssl_client (hloop_t* loop, const char* host, int port, hconnect_cb connect_cb) {
  865. hio_t* io = hio_create_socket(loop, host, port, HIO_TYPE_SSL, HIO_CLIENT_SIDE);
  866. if (io == NULL) return NULL;
  867. hio_setcb_connect(io, connect_cb);
  868. if (hio_connect(io) != 0) return NULL;
  869. return io;
  870. }
  871. hio_t* hloop_create_udp_server(hloop_t* loop, const char* host, int port) {
  872. return hio_create_socket(loop, host, port, HIO_TYPE_UDP, HIO_SERVER_SIDE);
  873. }
  874. hio_t* hloop_create_udp_client(hloop_t* loop, const char* host, int port) {
  875. return hio_create_socket(loop, host, port, HIO_TYPE_UDP, HIO_CLIENT_SIDE);
  876. }