hloop.c 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076
  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. #define HLOOP_PAUSE_TIME 10 // ms
  12. #define HLOOP_MAX_BLOCK_TIME 100 // ms
  13. #define HLOOP_STAT_TIMEOUT 60000 // ms
  14. #define IO_ARRAY_INIT_SIZE 1024
  15. #define CUSTOM_EVENT_QUEUE_INIT_SIZE 16
  16. #define SOCKPAIR_WRITE_INDEX 0
  17. #define SOCKPAIR_READ_INDEX 1
  18. static void __hidle_del(hidle_t* idle);
  19. static void __htimer_del(htimer_t* timer);
  20. static int timers_compare(const struct heap_node* lhs, const struct heap_node* rhs) {
  21. return TIMER_ENTRY(lhs)->next_timeout < TIMER_ENTRY(rhs)->next_timeout;
  22. }
  23. static int hloop_process_idles(hloop_t* loop) {
  24. int nidles = 0;
  25. struct list_node* node = loop->idles.next;
  26. hidle_t* idle = NULL;
  27. while (node != &loop->idles) {
  28. idle = IDLE_ENTRY(node);
  29. node = node->next;
  30. if (idle->repeat != INFINITE) {
  31. --idle->repeat;
  32. }
  33. if (idle->repeat == 0) {
  34. // NOTE: Just mark it as destroy and remove from list.
  35. // Real deletion occurs after hloop_process_pendings.
  36. __hidle_del(idle);
  37. }
  38. EVENT_PENDING(idle);
  39. ++nidles;
  40. }
  41. return nidles;
  42. }
  43. static int hloop_process_timers(hloop_t* loop) {
  44. int ntimers = 0;
  45. htimer_t* timer = NULL;
  46. uint64_t now_hrtime = hloop_now_hrtime(loop);
  47. while (loop->timers.root) {
  48. // NOTE: root of minheap has min timeout.
  49. timer = TIMER_ENTRY(loop->timers.root);
  50. if (timer->next_timeout > now_hrtime) {
  51. break;
  52. }
  53. if (timer->repeat != INFINITE) {
  54. --timer->repeat;
  55. }
  56. if (timer->repeat == 0) {
  57. // NOTE: Just mark it as destroy and remove from heap.
  58. // Real deletion occurs after hloop_process_pendings.
  59. __htimer_del(timer);
  60. }
  61. else {
  62. // NOTE: calc next timeout, then re-insert heap.
  63. heap_dequeue(&loop->timers);
  64. if (timer->event_type == HEVENT_TYPE_TIMEOUT) {
  65. while (timer->next_timeout <= now_hrtime) {
  66. timer->next_timeout += (uint64_t)((htimeout_t*)timer)->timeout * 1000;
  67. }
  68. }
  69. else if (timer->event_type == HEVENT_TYPE_PERIOD) {
  70. hperiod_t* period = (hperiod_t*)timer;
  71. timer->next_timeout = (uint64_t)cron_next_timeout(period->minute, period->hour, period->day,
  72. period->week, period->month) * 1000000;
  73. }
  74. heap_insert(&loop->timers, &timer->node);
  75. }
  76. EVENT_PENDING(timer);
  77. ++ntimers;
  78. }
  79. return ntimers;
  80. }
  81. static int hloop_process_ios(hloop_t* loop, int timeout) {
  82. // That is to call IO multiplexing function such as select, poll, epoll, etc.
  83. int nevents = iowatcher_poll_events(loop, timeout);
  84. if (nevents < 0) {
  85. hlogd("poll_events error=%d", -nevents);
  86. }
  87. return nevents < 0 ? 0 : nevents;
  88. }
  89. static int hloop_process_pendings(hloop_t* loop) {
  90. if (loop->npendings == 0) return 0;
  91. hevent_t* cur = NULL;
  92. hevent_t* next = NULL;
  93. int ncbs = 0;
  94. // NOTE: invoke event callback from high to low sorted by priority.
  95. for (int i = HEVENT_PRIORITY_SIZE-1; i >= 0; --i) {
  96. cur = loop->pendings[i];
  97. while (cur) {
  98. next = cur->pending_next;
  99. if (cur->pending) {
  100. if (cur->active && cur->cb) {
  101. cur->cb(cur);
  102. ++ncbs;
  103. }
  104. cur->pending = 0;
  105. // NOTE: Now we can safely delete event marked as destroy.
  106. if (cur->destroy) {
  107. EVENT_DEL(cur);
  108. }
  109. }
  110. cur = next;
  111. }
  112. loop->pendings[i] = NULL;
  113. }
  114. loop->npendings = 0;
  115. return ncbs;
  116. }
  117. // hloop_process_ios -> hloop_process_timers -> hloop_process_idles -> hloop_process_pendings
  118. static int hloop_process_events(hloop_t* loop) {
  119. // ios -> timers -> idles
  120. int nios, ntimers, nidles;
  121. nios = ntimers = nidles = 0;
  122. // calc blocktime
  123. int32_t blocktime = HLOOP_MAX_BLOCK_TIME;
  124. if (loop->timers.root) {
  125. hloop_update_time(loop);
  126. uint64_t next_min_timeout = TIMER_ENTRY(loop->timers.root)->next_timeout;
  127. int64_t blocktime_us = next_min_timeout - hloop_now_hrtime(loop);
  128. if (blocktime_us <= 0) goto process_timers;
  129. blocktime = blocktime_us / 1000;
  130. ++blocktime;
  131. blocktime = MIN(blocktime, HLOOP_MAX_BLOCK_TIME);
  132. }
  133. if (loop->nios) {
  134. nios = hloop_process_ios(loop, blocktime);
  135. } else {
  136. hv_msleep(blocktime);
  137. }
  138. hloop_update_time(loop);
  139. // wakeup by hloop_stop
  140. if (loop->status == HLOOP_STATUS_STOP) {
  141. return 0;
  142. }
  143. process_timers:
  144. if (loop->ntimers) {
  145. ntimers = hloop_process_timers(loop);
  146. }
  147. int npendings = loop->npendings;
  148. if (npendings == 0) {
  149. if (loop->nidles) {
  150. nidles= hloop_process_idles(loop);
  151. }
  152. }
  153. int ncbs = hloop_process_pendings(loop);
  154. // printd("blocktime=%d nios=%d/%u ntimers=%d/%u nidles=%d/%u nactives=%d npendings=%d ncbs=%d\n",
  155. // blocktime, nios, loop->nios, ntimers, loop->ntimers, nidles, loop->nidles,
  156. // loop->nactives, npendings, ncbs);
  157. return ncbs;
  158. }
  159. static void hloop_stat_timer_cb(htimer_t* timer) {
  160. hloop_t* loop = timer->loop;
  161. // hlog_set_level(LOG_LEVEL_DEBUG);
  162. hlogd("[loop] pid=%ld tid=%ld uptime=%lluus cnt=%llu nactives=%u nios=%d ntimers=%d nidles=%u",
  163. loop->pid, loop->tid, loop->cur_hrtime - loop->start_hrtime, loop->loop_cnt,
  164. loop->nactives, loop->nios, loop->ntimers, loop->nidles);
  165. }
  166. static void sockpair_read_cb(hio_t* io, void* buf, int readbytes) {
  167. hloop_t* loop = io->loop;
  168. hevent_t* pev = NULL;
  169. hevent_t ev;
  170. for (int i = 0; i < readbytes; ++i) {
  171. hmutex_lock(&loop->custom_events_mutex);
  172. if (event_queue_empty(&loop->custom_events)) {
  173. goto unlock;
  174. }
  175. pev = event_queue_front(&loop->custom_events);
  176. if (pev == NULL) {
  177. goto unlock;
  178. }
  179. ev = *pev;
  180. event_queue_pop_front(&loop->custom_events);
  181. // NOTE: unlock before cb, avoid deadlock if hloop_post_event called in cb.
  182. hmutex_unlock(&loop->custom_events_mutex);
  183. if (ev.cb) {
  184. ev.cb(&ev);
  185. }
  186. }
  187. return;
  188. unlock:
  189. hmutex_unlock(&loop->custom_events_mutex);
  190. }
  191. void hloop_post_event(hloop_t* loop, hevent_t* ev) {
  192. char buf = '1';
  193. if (loop->sockpair[0] == -1 || loop->sockpair[1] == -1) {
  194. hlogw("socketpair not created!");
  195. return;
  196. }
  197. if (ev->loop == NULL) {
  198. ev->loop = loop;
  199. }
  200. if (ev->event_type == 0) {
  201. ev->event_type = HEVENT_TYPE_CUSTOM;
  202. }
  203. if (ev->event_id == 0) {
  204. ev->event_id = hloop_next_event_id();
  205. }
  206. hmutex_lock(&loop->custom_events_mutex);
  207. hwrite(loop, loop->sockpair[SOCKPAIR_WRITE_INDEX], &buf, 1, NULL);
  208. event_queue_push_back(&loop->custom_events, ev);
  209. hmutex_unlock(&loop->custom_events_mutex);
  210. }
  211. static void hloop_init(hloop_t* loop) {
  212. #ifdef OS_WIN
  213. static int s_wsa_initialized = 0;
  214. if (s_wsa_initialized == 0) {
  215. s_wsa_initialized = 1;
  216. WSADATA wsadata;
  217. WSAStartup(MAKEWORD(2,2), &wsadata);
  218. }
  219. #endif
  220. #ifdef SIGPIPE
  221. // NOTE: if not ignore SIGPIPE, write twice when peer close will lead to exit process by SIGPIPE.
  222. signal(SIGPIPE, SIG_IGN);
  223. #endif
  224. loop->status = HLOOP_STATUS_STOP;
  225. loop->pid = hv_getpid();
  226. loop->tid = hv_gettid();
  227. // idles
  228. list_init(&loop->idles);
  229. // timers
  230. heap_init(&loop->timers, timers_compare);
  231. // ios
  232. io_array_init(&loop->ios, IO_ARRAY_INIT_SIZE);
  233. // readbuf
  234. loop->readbuf.len = HLOOP_READ_BUFSIZE;
  235. HV_ALLOC(loop->readbuf.base, loop->readbuf.len);
  236. // iowatcher
  237. iowatcher_init(loop);
  238. // custom_events
  239. hmutex_init(&loop->custom_events_mutex);
  240. event_queue_init(&loop->custom_events, CUSTOM_EVENT_QUEUE_INIT_SIZE);
  241. loop->sockpair[0] = loop->sockpair[1] = -1;
  242. if (Socketpair(AF_INET, SOCK_STREAM, 0, loop->sockpair) != 0) {
  243. hloge("socketpair create failed!");
  244. }
  245. // NOTE: init start_time here, because htimer_add use it.
  246. loop->start_ms = gettimeofday_ms();
  247. loop->start_hrtime = loop->cur_hrtime = gethrtime_us();
  248. }
  249. static void hloop_cleanup(hloop_t* loop) {
  250. // pendings
  251. printd("cleanup pendings...\n");
  252. for (int i = 0; i < HEVENT_PRIORITY_SIZE; ++i) {
  253. loop->pendings[i] = NULL;
  254. }
  255. // ios
  256. printd("cleanup ios...\n");
  257. for (int i = 0; i < loop->ios.maxsize; ++i) {
  258. hio_t* io = loop->ios.ptr[i];
  259. if (io) {
  260. hio_free(io);
  261. }
  262. }
  263. io_array_cleanup(&loop->ios);
  264. // idles
  265. printd("cleanup idles...\n");
  266. struct list_node* node = loop->idles.next;
  267. hidle_t* idle;
  268. while (node != &loop->idles) {
  269. idle = IDLE_ENTRY(node);
  270. node = node->next;
  271. HV_FREE(idle);
  272. }
  273. list_init(&loop->idles);
  274. // timers
  275. printd("cleanup timers...\n");
  276. htimer_t* timer;
  277. while (loop->timers.root) {
  278. timer = TIMER_ENTRY(loop->timers.root);
  279. heap_dequeue(&loop->timers);
  280. HV_FREE(timer);
  281. }
  282. heap_init(&loop->timers, NULL);
  283. // readbuf
  284. if (loop->readbuf.base && loop->readbuf.len) {
  285. HV_FREE(loop->readbuf.base);
  286. loop->readbuf.base = NULL;
  287. loop->readbuf.len = 0;
  288. }
  289. // iowatcher
  290. iowatcher_cleanup(loop);
  291. // custom_events
  292. hmutex_lock(&loop->custom_events_mutex);
  293. if (loop->sockpair[0] != -1 && loop->sockpair[1] != -1) {
  294. closesocket(loop->sockpair[0]);
  295. closesocket(loop->sockpair[1]);
  296. loop->sockpair[0] = loop->sockpair[1] = -1;
  297. }
  298. event_queue_cleanup(&loop->custom_events);
  299. hmutex_unlock(&loop->custom_events_mutex);
  300. hmutex_destroy(&loop->custom_events_mutex);
  301. }
  302. hloop_t* hloop_new(int flags) {
  303. hloop_t* loop;
  304. HV_ALLOC_SIZEOF(loop);
  305. hloop_init(loop);
  306. loop->flags |= flags;
  307. return loop;
  308. }
  309. void hloop_free(hloop_t** pp) {
  310. if (pp && *pp) {
  311. hloop_cleanup(*pp);
  312. HV_FREE(*pp);
  313. *pp = NULL;
  314. }
  315. }
  316. // while(loop->status) { hloop_process_events(loop); }
  317. int hloop_run(hloop_t* loop) {
  318. if (loop == NULL) return -1;
  319. if (loop->status == HLOOP_STATUS_RUNNING) return -2;
  320. loop->status = HLOOP_STATUS_RUNNING;
  321. loop->pid = hv_getpid();
  322. loop->tid = hv_gettid();
  323. if (loop->intern_nevents == 0) {
  324. if (loop->sockpair[0] != -1 && loop->sockpair[1] != -1) {
  325. hread(loop, loop->sockpair[SOCKPAIR_READ_INDEX], loop->readbuf.base, loop->readbuf.len, sockpair_read_cb);
  326. ++loop->intern_nevents;
  327. }
  328. #ifdef DEBUG
  329. htimer_add(loop, hloop_stat_timer_cb, HLOOP_STAT_TIMEOUT, INFINITE);
  330. ++loop->intern_nevents;
  331. #endif
  332. }
  333. while (loop->status != HLOOP_STATUS_STOP) {
  334. if (loop->status == HLOOP_STATUS_PAUSE) {
  335. hv_msleep(HLOOP_PAUSE_TIME);
  336. hloop_update_time(loop);
  337. continue;
  338. }
  339. ++loop->loop_cnt;
  340. if (loop->nactives <= loop->intern_nevents && loop->flags & HLOOP_FLAG_QUIT_WHEN_NO_ACTIVE_EVENTS) {
  341. break;
  342. }
  343. hloop_process_events(loop);
  344. if (loop->flags & HLOOP_FLAG_RUN_ONCE) {
  345. break;
  346. }
  347. }
  348. loop->status = HLOOP_STATUS_STOP;
  349. loop->end_hrtime = gethrtime_us();
  350. if (loop->flags & HLOOP_FLAG_AUTO_FREE) {
  351. hloop_cleanup(loop);
  352. HV_FREE(loop);
  353. }
  354. return 0;
  355. }
  356. int hloop_wakeup(hloop_t* loop) {
  357. hevent_t ev;
  358. memset(&ev, 0, sizeof(ev));
  359. hloop_post_event(loop, &ev);
  360. return 0;
  361. }
  362. static void hloop_stop_event_cb(hevent_t* ev) {
  363. ev->loop->status = HLOOP_STATUS_STOP;
  364. }
  365. int hloop_stop(hloop_t* loop) {
  366. loop->status = HLOOP_STATUS_STOP;
  367. if (hv_gettid() != loop->tid) {
  368. hevent_t ev;
  369. memset(&ev, 0, sizeof(ev));
  370. ev.priority = HEVENT_HIGHEST_PRIORITY;
  371. ev.cb = hloop_stop_event_cb;
  372. hloop_post_event(loop, &ev);
  373. }
  374. return 0;
  375. }
  376. int hloop_pause(hloop_t* loop) {
  377. if (loop->status == HLOOP_STATUS_RUNNING) {
  378. loop->status = HLOOP_STATUS_PAUSE;
  379. }
  380. return 0;
  381. }
  382. int hloop_resume(hloop_t* loop) {
  383. if (loop->status == HLOOP_STATUS_PAUSE) {
  384. loop->status = HLOOP_STATUS_RUNNING;
  385. }
  386. return 0;
  387. }
  388. hloop_status_e hloop_status(hloop_t* loop) {
  389. return loop->status;
  390. }
  391. void hloop_update_time(hloop_t* loop) {
  392. loop->cur_hrtime = gethrtime_us();
  393. if (ABS((int64_t)hloop_now(loop) - (int64_t)time(NULL)) > 1) {
  394. // systemtime changed, we adjust start_ms
  395. loop->start_ms = gettimeofday_ms() - (loop->cur_hrtime - loop->start_hrtime) / 1000;
  396. }
  397. }
  398. uint64_t hloop_now(hloop_t* loop) {
  399. return loop->start_ms / 1000 + (loop->cur_hrtime - loop->start_hrtime) / 1000000;
  400. }
  401. uint64_t hloop_now_ms(hloop_t* loop) {
  402. return loop->start_ms + (loop->cur_hrtime - loop->start_hrtime) / 1000;
  403. }
  404. uint64_t hloop_now_hrtime(hloop_t* loop) {
  405. return loop->start_ms * 1000 + (loop->cur_hrtime - loop->start_hrtime);
  406. }
  407. long hloop_pid(hloop_t* loop) {
  408. return loop->pid;
  409. }
  410. long hloop_tid(hloop_t* loop) {
  411. return loop->tid;
  412. }
  413. void hloop_set_userdata(hloop_t* loop, void* userdata) {
  414. loop->userdata = userdata;
  415. }
  416. void* hloop_userdata(hloop_t* loop) {
  417. return loop->userdata;
  418. }
  419. hidle_t* hidle_add(hloop_t* loop, hidle_cb cb, uint32_t repeat) {
  420. hidle_t* idle;
  421. HV_ALLOC_SIZEOF(idle);
  422. idle->event_type = HEVENT_TYPE_IDLE;
  423. idle->priority = HEVENT_LOWEST_PRIORITY;
  424. idle->repeat = repeat;
  425. list_add(&idle->node, &loop->idles);
  426. EVENT_ADD(loop, idle, cb);
  427. loop->nidles++;
  428. return idle;
  429. }
  430. static void __hidle_del(hidle_t* idle) {
  431. if (idle->destroy) return;
  432. idle->destroy = 1;
  433. list_del(&idle->node);
  434. idle->loop->nidles--;
  435. }
  436. void hidle_del(hidle_t* idle) {
  437. if (!idle->active) return;
  438. __hidle_del(idle);
  439. EVENT_DEL(idle);
  440. }
  441. htimer_t* htimer_add(hloop_t* loop, htimer_cb cb, uint32_t timeout, uint32_t repeat) {
  442. if (timeout == 0) return NULL;
  443. htimeout_t* timer;
  444. HV_ALLOC_SIZEOF(timer);
  445. timer->event_type = HEVENT_TYPE_TIMEOUT;
  446. timer->priority = HEVENT_HIGHEST_PRIORITY;
  447. timer->repeat = repeat;
  448. timer->timeout = timeout;
  449. hloop_update_time(loop);
  450. timer->next_timeout = hloop_now_hrtime(loop) + (uint64_t)timeout*1000;
  451. // NOTE: Limit granularity to 100ms
  452. if (timeout >= 1000 && timeout % 100 == 0) {
  453. timer->next_timeout = timer->next_timeout / 100000 * 100000;
  454. }
  455. heap_insert(&loop->timers, &timer->node);
  456. EVENT_ADD(loop, timer, cb);
  457. loop->ntimers++;
  458. return (htimer_t*)timer;
  459. }
  460. void htimer_reset(htimer_t* timer) {
  461. if (timer->event_type != HEVENT_TYPE_TIMEOUT) {
  462. return;
  463. }
  464. hloop_t* loop = timer->loop;
  465. htimeout_t* timeout = (htimeout_t*)timer;
  466. if (timer->destroy) {
  467. loop->ntimers++;
  468. } else {
  469. heap_remove(&loop->timers, &timer->node);
  470. }
  471. if (timer->repeat == 0) {
  472. timer->repeat = 1;
  473. }
  474. timer->next_timeout = hloop_now_hrtime(loop) + (uint64_t)timeout->timeout*1000;
  475. // NOTE: Limit granularity to 100ms
  476. if (timeout->timeout >= 1000 && timeout->timeout % 100 == 0) {
  477. timer->next_timeout = timer->next_timeout / 100000 * 100000;
  478. }
  479. heap_insert(&loop->timers, &timer->node);
  480. EVENT_RESET(timer);
  481. }
  482. htimer_t* htimer_add_period(hloop_t* loop, htimer_cb cb,
  483. int8_t minute, int8_t hour, int8_t day,
  484. int8_t week, int8_t month, uint32_t repeat) {
  485. if (minute > 59 || hour > 23 || day > 31 || week > 6 || month > 12) {
  486. return NULL;
  487. }
  488. hperiod_t* timer;
  489. HV_ALLOC_SIZEOF(timer);
  490. timer->event_type = HEVENT_TYPE_PERIOD;
  491. timer->priority = HEVENT_HIGH_PRIORITY;
  492. timer->repeat = repeat;
  493. timer->minute = minute;
  494. timer->hour = hour;
  495. timer->day = day;
  496. timer->month = month;
  497. timer->week = week;
  498. timer->next_timeout = (uint64_t)cron_next_timeout(minute, hour, day, week, month) * 1000000;
  499. heap_insert(&loop->timers, &timer->node);
  500. EVENT_ADD(loop, timer, cb);
  501. loop->ntimers++;
  502. return (htimer_t*)timer;
  503. }
  504. static void __htimer_del(htimer_t* timer) {
  505. if (timer->destroy) return;
  506. heap_remove(&timer->loop->timers, &timer->node);
  507. timer->loop->ntimers--;
  508. timer->destroy = 1;
  509. }
  510. void htimer_del(htimer_t* timer) {
  511. if (!timer->active) return;
  512. __htimer_del(timer);
  513. EVENT_DEL(timer);
  514. }
  515. const char* hio_engine() {
  516. #ifdef EVENT_SELECT
  517. return "select";
  518. #elif defined(EVENT_POLL)
  519. return "poll";
  520. #elif defined(EVENT_EPOLL)
  521. return "epoll";
  522. #elif defined(EVENT_KQUEUE)
  523. return "kqueue";
  524. #elif defined(EVENT_IOCP)
  525. return "iocp";
  526. #elif defined(EVENT_PORT)
  527. return "evport";
  528. #else
  529. return "noevent";
  530. #endif
  531. }
  532. static void fill_io_type(hio_t* io) {
  533. int type = 0;
  534. socklen_t optlen = sizeof(int);
  535. int ret = getsockopt(io->fd, SOL_SOCKET, SO_TYPE, (char*)&type, &optlen);
  536. printd("getsockopt SO_TYPE fd=%d ret=%d type=%d errno=%d\n", io->fd, ret, type, socket_errno());
  537. if (ret == 0) {
  538. switch (type) {
  539. case SOCK_STREAM: io->io_type = HIO_TYPE_TCP; break;
  540. case SOCK_DGRAM: io->io_type = HIO_TYPE_UDP; break;
  541. case SOCK_RAW: io->io_type = HIO_TYPE_IP; break;
  542. default: io->io_type = HIO_TYPE_SOCKET; break;
  543. }
  544. }
  545. else if (socket_errno() == ENOTSOCK) {
  546. switch (io->fd) {
  547. case 0: io->io_type = HIO_TYPE_STDIN; break;
  548. case 1: io->io_type = HIO_TYPE_STDOUT; break;
  549. case 2: io->io_type = HIO_TYPE_STDERR; break;
  550. default: io->io_type = HIO_TYPE_FILE; break;
  551. }
  552. }
  553. else {
  554. io->io_type = HIO_TYPE_TCP;
  555. }
  556. }
  557. static void hio_socket_init(hio_t* io) {
  558. // nonblocking
  559. nonblocking(io->fd);
  560. // fill io->localaddr io->peeraddr
  561. if (io->localaddr == NULL) {
  562. HV_ALLOC(io->localaddr, sizeof(sockaddr_u));
  563. }
  564. if (io->peeraddr == NULL) {
  565. HV_ALLOC(io->peeraddr, sizeof(sockaddr_u));
  566. }
  567. socklen_t addrlen = sizeof(sockaddr_u);
  568. int ret = getsockname(io->fd, io->localaddr, &addrlen);
  569. printd("getsockname fd=%d ret=%d errno=%d\n", io->fd, ret, socket_errno());
  570. // NOTE:
  571. // tcp_server peeraddr set by accept
  572. // udp_server peeraddr set by recvfrom
  573. // tcp_client/udp_client peeraddr set by hio_setpeeraddr
  574. if (io->io_type == HIO_TYPE_TCP || io->io_type == HIO_TYPE_SSL) {
  575. // tcp acceptfd
  576. addrlen = sizeof(sockaddr_u);
  577. ret = getpeername(io->fd, io->peeraddr, &addrlen);
  578. printd("getpeername fd=%d ret=%d errno=%d\n", io->fd, ret, socket_errno());
  579. }
  580. }
  581. void hio_init(hio_t* io) {
  582. // alloc localaddr,peeraddr when hio_socket_init
  583. /*
  584. if (io->localaddr == NULL) {
  585. HV_ALLOC(io->localaddr, sizeof(sockaddr_u));
  586. }
  587. if (io->peeraddr == NULL) {
  588. HV_ALLOC(io->peeraddr, sizeof(sockaddr_u));
  589. }
  590. */
  591. // write_queue init when hwrite try_write failed
  592. // write_queue_init(&io->write_queue, 4);
  593. hrecursive_mutex_init(&io->write_mutex);
  594. }
  595. void hio_ready(hio_t* io) {
  596. if (io->ready) return;
  597. // flags
  598. io->ready = 1;
  599. io->closed = 0;
  600. io->accept = io->connect = io->connectex = 0;
  601. io->recv = io->send = 0;
  602. io->recvfrom = io->sendto = 0;
  603. io->close = 0;
  604. // public:
  605. io->id = hio_next_id();
  606. io->io_type = HIO_TYPE_UNKNOWN;
  607. io->error = 0;
  608. io->events = io->revents = 0;
  609. // readbuf
  610. io->alloced_readbuf = 0;
  611. io->readbuf.base = io->loop->readbuf.base;
  612. io->readbuf.len = io->loop->readbuf.len;
  613. io->readbuf.offset = 0;
  614. // callbacks
  615. io->read_cb = NULL;
  616. io->write_cb = NULL;
  617. io->close_cb = NULL;
  618. io->accept_cb = NULL;
  619. io->connect_cb = NULL;
  620. // timers
  621. io->connect_timeout = 0;
  622. io->connect_timer = NULL;
  623. io->close_timeout = 0;
  624. io->close_timer = NULL;
  625. io->keepalive_timeout = 0;
  626. io->keepalive_timer = NULL;
  627. io->heartbeat_interval = 0;
  628. io->heartbeat_fn = NULL;
  629. io->heartbeat_timer = NULL;
  630. // upstream
  631. io->upstream_io = NULL;
  632. // unpack
  633. io->unpack_setting = NULL;
  634. // private:
  635. io->event_index[0] = io->event_index[1] = -1;
  636. io->hovlp = NULL;
  637. io->ssl = NULL;
  638. // io_type
  639. fill_io_type(io);
  640. if (io->io_type & HIO_TYPE_SOCKET) {
  641. hio_socket_init(io);
  642. }
  643. }
  644. void hio_done(hio_t* io) {
  645. if (!io->ready) return;
  646. io->ready = 0;
  647. hio_del(io, HV_RDWR);
  648. // readbuf
  649. hio_free_readbuf(io);
  650. // write_queue
  651. offset_buf_t* pbuf = NULL;
  652. hrecursive_mutex_lock(&io->write_mutex);
  653. while (!write_queue_empty(&io->write_queue)) {
  654. pbuf = write_queue_front(&io->write_queue);
  655. HV_FREE(pbuf->base);
  656. write_queue_pop_front(&io->write_queue);
  657. }
  658. write_queue_cleanup(&io->write_queue);
  659. hrecursive_mutex_unlock(&io->write_mutex);
  660. }
  661. void hio_free(hio_t* io) {
  662. if (io == NULL) return;
  663. // NOTE: call hio_done to cleanup write_queue
  664. hio_done(io);
  665. // NOTE: call hio_close to call hclose_cb
  666. hio_close(io);
  667. hrecursive_mutex_destroy(&io->write_mutex);
  668. HV_FREE(io->localaddr);
  669. HV_FREE(io->peeraddr);
  670. HV_FREE(io);
  671. }
  672. bool hio_is_opened(hio_t* io) {
  673. if (io == NULL) return false;
  674. return io->ready == 1 && io->closed == 0;
  675. }
  676. bool hio_is_closed(hio_t* io) {
  677. if (io == NULL) return true;
  678. return io->ready == 0 && io->closed == 1;
  679. }
  680. hio_t* hio_get(hloop_t* loop, int fd) {
  681. if (fd >= loop->ios.maxsize) {
  682. int newsize = ceil2e(fd);
  683. io_array_resize(&loop->ios, newsize > fd ? newsize : 2*fd);
  684. }
  685. hio_t* io = loop->ios.ptr[fd];
  686. if (io == NULL) {
  687. HV_ALLOC_SIZEOF(io);
  688. hio_init(io);
  689. io->event_type = HEVENT_TYPE_IO;
  690. io->loop = loop;
  691. io->fd = fd;
  692. loop->ios.ptr[fd] = io;
  693. }
  694. if (!io->ready) {
  695. hio_ready(io);
  696. }
  697. return io;
  698. }
  699. void hio_detach(hio_t* io) {
  700. hloop_t* loop = io->loop;
  701. int fd = io->fd;
  702. assert(loop != NULL && fd < loop->ios.maxsize);
  703. loop->ios.ptr[fd] = NULL;
  704. }
  705. void hio_attach(hloop_t* loop, hio_t* io) {
  706. int fd = io->fd;
  707. if (fd >= loop->ios.maxsize) {
  708. int newsize = ceil2e(fd);
  709. io_array_resize(&loop->ios, newsize > fd ? newsize : 2*fd);
  710. }
  711. if (loop->ios.ptr[fd] == NULL) {
  712. io->loop = loop;
  713. // NOTE: use new_loop readbuf
  714. io->readbuf.base = loop->readbuf.base;
  715. io->readbuf.len = loop->readbuf.len;
  716. loop->ios.ptr[fd] = io;
  717. }
  718. }
  719. int hio_add(hio_t* io, hio_cb cb, int events) {
  720. printd("hio_add fd=%d io->events=%d events=%d\n", io->fd, io->events, events);
  721. #ifdef OS_WIN
  722. // Windows iowatcher not work on stdio
  723. if (io->fd < 3) return -1;
  724. #endif
  725. hloop_t* loop = io->loop;
  726. if (!io->active) {
  727. EVENT_ADD(loop, io, cb);
  728. loop->nios++;
  729. }
  730. if (!io->ready) {
  731. hio_ready(io);
  732. }
  733. if (cb) {
  734. io->cb = (hevent_cb)cb;
  735. }
  736. if (!(io->events & events)) {
  737. iowatcher_add_event(loop, io->fd, events);
  738. io->events |= events;
  739. }
  740. return 0;
  741. }
  742. int hio_del(hio_t* io, int events) {
  743. printd("hio_del fd=%d io->events=%d events=%d\n", io->fd, io->events, events);
  744. #ifdef OS_WIN
  745. // Windows iowatcher not work on stdio
  746. if (io->fd < 3) return -1;
  747. #endif
  748. if (!io->active) return -1;
  749. if (io->events & events) {
  750. iowatcher_del_event(io->loop, io->fd, events);
  751. io->events &= ~events;
  752. }
  753. if (io->events == 0) {
  754. io->loop->nios--;
  755. // NOTE: not EVENT_DEL, avoid free
  756. EVENT_INACTIVE(io);
  757. }
  758. return 0;
  759. }
  760. static void hio_close_event_cb(hevent_t* ev) {
  761. hio_t* io = (hio_t*)ev->userdata;
  762. uint32_t id = (uintptr_t)ev->privdata;
  763. if (io->id != id) return;
  764. hio_close(io);
  765. }
  766. int hio_close_async(hio_t* io) {
  767. hevent_t ev;
  768. memset(&ev, 0, sizeof(ev));
  769. ev.cb = hio_close_event_cb;
  770. ev.userdata = io;
  771. ev.privdata = (void*)(uintptr_t)io->id;
  772. ev.priority = HEVENT_HIGH_PRIORITY;
  773. hloop_post_event(io->loop, &ev);
  774. return 0;
  775. }
  776. hio_t* hread(hloop_t* loop, int fd, void* buf, size_t len, hread_cb read_cb) {
  777. hio_t* io = hio_get(loop, fd);
  778. assert(io != NULL);
  779. if (buf && len) {
  780. io->readbuf.base = (char*)buf;
  781. io->readbuf.len = len;
  782. }
  783. if (read_cb) {
  784. io->read_cb = read_cb;
  785. }
  786. hio_read(io);
  787. return io;
  788. }
  789. hio_t* hwrite(hloop_t* loop, int fd, const void* buf, size_t len, hwrite_cb write_cb) {
  790. hio_t* io = hio_get(loop, fd);
  791. assert(io != NULL);
  792. if (write_cb) {
  793. io->write_cb = write_cb;
  794. }
  795. hio_write(io, buf, len);
  796. return io;
  797. }
  798. hio_t* haccept(hloop_t* loop, int listenfd, haccept_cb accept_cb) {
  799. hio_t* io = hio_get(loop, listenfd);
  800. assert(io != NULL);
  801. if (accept_cb) {
  802. io->accept_cb = accept_cb;
  803. }
  804. hio_accept(io);
  805. return io;
  806. }
  807. hio_t* hconnect (hloop_t* loop, int connfd, hconnect_cb connect_cb) {
  808. hio_t* io = hio_get(loop, connfd);
  809. assert(io != NULL);
  810. if (connect_cb) {
  811. io->connect_cb = connect_cb;
  812. }
  813. hio_connect(io);
  814. return io;
  815. }
  816. void hclose (hloop_t* loop, int fd) {
  817. hio_t* io = hio_get(loop, fd);
  818. assert(io != NULL);
  819. hio_close(io);
  820. }
  821. hio_t* hrecv (hloop_t* loop, int connfd, void* buf, size_t len, hread_cb read_cb) {
  822. //hio_t* io = hio_get(loop, connfd);
  823. //assert(io != NULL);
  824. //io->recv = 1;
  825. //if (io->io_type != HIO_TYPE_SSL) {
  826. //io->io_type = HIO_TYPE_TCP;
  827. //}
  828. return hread(loop, connfd, buf, len, read_cb);
  829. }
  830. hio_t* hsend (hloop_t* loop, int connfd, const void* buf, size_t len, hwrite_cb write_cb) {
  831. //hio_t* io = hio_get(loop, connfd);
  832. //assert(io != NULL);
  833. //io->send = 1;
  834. //if (io->io_type != HIO_TYPE_SSL) {
  835. //io->io_type = HIO_TYPE_TCP;
  836. //}
  837. return hwrite(loop, connfd, buf, len, write_cb);
  838. }
  839. hio_t* hrecvfrom (hloop_t* loop, int sockfd, void* buf, size_t len, hread_cb read_cb) {
  840. //hio_t* io = hio_get(loop, sockfd);
  841. //assert(io != NULL);
  842. //io->recvfrom = 1;
  843. //io->io_type = HIO_TYPE_UDP;
  844. return hread(loop, sockfd, buf, len, read_cb);
  845. }
  846. hio_t* hsendto (hloop_t* loop, int sockfd, const void* buf, size_t len, hwrite_cb write_cb) {
  847. //hio_t* io = hio_get(loop, sockfd);
  848. //assert(io != NULL);
  849. //io->sendto = 1;
  850. //io->io_type = HIO_TYPE_UDP;
  851. return hwrite(loop, sockfd, buf, len, write_cb);
  852. }
  853. hio_t* hio_create(hloop_t* loop, const char* host, int port, int type) {
  854. sockaddr_u peeraddr;
  855. memset(&peeraddr, 0, sizeof(peeraddr));
  856. int ret = sockaddr_set_ipport(&peeraddr, host, port);
  857. if (ret != 0) {
  858. //printf("unknown host: %s\n", host);
  859. return NULL;
  860. }
  861. int connfd = socket(peeraddr.sa.sa_family, type, 0);
  862. if (connfd < 0) {
  863. perror("socket");
  864. return NULL;
  865. }
  866. hio_t* io = hio_get(loop, connfd);
  867. assert(io != NULL);
  868. hio_set_peeraddr(io, &peeraddr.sa, sockaddr_len(&peeraddr));
  869. return io;
  870. }
  871. hio_t* hloop_create_tcp_server (hloop_t* loop, const char* host, int port, haccept_cb accept_cb) {
  872. int listenfd = Listen(port, host);
  873. if (listenfd < 0) {
  874. return NULL;
  875. }
  876. hio_t* io = haccept(loop, listenfd, accept_cb);
  877. if (io == NULL) {
  878. closesocket(listenfd);
  879. }
  880. return io;
  881. }
  882. hio_t* hloop_create_tcp_client (hloop_t* loop, const char* host, int port, hconnect_cb connect_cb) {
  883. hio_t* io = hio_create(loop, host, port, SOCK_STREAM);
  884. if (io == NULL) return NULL;
  885. hconnect(loop, io->fd, connect_cb);
  886. return io;
  887. }
  888. hio_t* hloop_create_ssl_server (hloop_t* loop, const char* host, int port, haccept_cb accept_cb) {
  889. hio_t* io = hloop_create_tcp_server(loop, host, port, accept_cb);
  890. if (io == NULL) return NULL;
  891. hio_enable_ssl(io);
  892. return io;
  893. }
  894. hio_t* hloop_create_ssl_client (hloop_t* loop, const char* host, int port, hconnect_cb connect_cb) {
  895. hio_t* io = hio_create(loop, host, port, SOCK_STREAM);
  896. if (io == NULL) return NULL;
  897. hio_enable_ssl(io);
  898. hconnect(loop, io->fd, connect_cb);
  899. return io;
  900. }
  901. hio_t* hloop_create_udp_server(hloop_t* loop, const char* host, int port) {
  902. int bindfd = Bind(port, host, SOCK_DGRAM);
  903. if (bindfd < 0) {
  904. return NULL;
  905. }
  906. return hio_get(loop, bindfd);
  907. }
  908. hio_t* hloop_create_udp_client(hloop_t* loop, const char* host, int port) {
  909. return hio_create(loop, host, port, SOCK_DGRAM);
  910. }
  911. // upstream
  912. void hio_read_upstream(hio_t* io) {
  913. hio_t* upstream_io = io->upstream_io;
  914. if (upstream_io) {
  915. hio_read(io);
  916. hio_read(upstream_io);
  917. }
  918. }
  919. void hio_write_upstream(hio_t* io, void* buf, int bytes) {
  920. hio_t* upstream_io = io->upstream_io;
  921. if (upstream_io) {
  922. hio_write(upstream_io, buf, bytes);
  923. }
  924. }
  925. void hio_close_upstream(hio_t* io) {
  926. hio_t* upstream_io = io->upstream_io;
  927. if (upstream_io) {
  928. hio_close(upstream_io);
  929. }
  930. }
  931. void hio_setup_upstream(hio_t* io1, hio_t* io2) {
  932. io1->upstream_io = io2;
  933. io2->upstream_io = io1;
  934. hio_setcb_read(io1, hio_write_upstream);
  935. hio_setcb_read(io2, hio_write_upstream);
  936. }
  937. hio_t* hio_get_upstream(hio_t* io) {
  938. return io->upstream_io;
  939. }
  940. hio_t* hio_setup_tcp_upstream(hio_t* io, const char* host, int port, int ssl) {
  941. hio_t* upstream_io = hio_create(io->loop, host, port, SOCK_STREAM);
  942. if (upstream_io == NULL) return NULL;
  943. if (ssl) hio_enable_ssl(upstream_io);
  944. hio_setup_upstream(io, upstream_io);
  945. hio_setcb_close(io, hio_close_upstream);
  946. hio_setcb_close(upstream_io, hio_close_upstream);
  947. hconnect(io->loop, upstream_io->fd, hio_read_upstream);
  948. return upstream_io;
  949. }
  950. hio_t* hio_setup_udp_upstream(hio_t* io, const char* host, int port) {
  951. hio_t* upstream_io = hio_create(io->loop, host, port, SOCK_DGRAM);
  952. if (upstream_io == NULL) return NULL;
  953. hio_setup_upstream(io, upstream_io);
  954. hio_read_upstream(io);
  955. return upstream_io;
  956. }