hloop.c 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067
  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. hloge("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. heap_insert(&loop->timers, &timer->node);
  452. EVENT_ADD(loop, timer, cb);
  453. loop->ntimers++;
  454. return (htimer_t*)timer;
  455. }
  456. void htimer_reset(htimer_t* timer) {
  457. if (timer->event_type != HEVENT_TYPE_TIMEOUT) {
  458. return;
  459. }
  460. hloop_t* loop = timer->loop;
  461. htimeout_t* timeout = (htimeout_t*)timer;
  462. if (timer->destroy) {
  463. loop->ntimers++;
  464. } else {
  465. heap_remove(&loop->timers, &timer->node);
  466. }
  467. if (timer->repeat == 0) {
  468. timer->repeat = 1;
  469. }
  470. timer->next_timeout = hloop_now_hrtime(loop) + (uint64_t)timeout->timeout*1000;
  471. heap_insert(&loop->timers, &timer->node);
  472. EVENT_RESET(timer);
  473. }
  474. htimer_t* htimer_add_period(hloop_t* loop, htimer_cb cb,
  475. int8_t minute, int8_t hour, int8_t day,
  476. int8_t week, int8_t month, uint32_t repeat) {
  477. if (minute > 59 || hour > 23 || day > 31 || week > 6 || month > 12) {
  478. return NULL;
  479. }
  480. hperiod_t* timer;
  481. HV_ALLOC_SIZEOF(timer);
  482. timer->event_type = HEVENT_TYPE_PERIOD;
  483. timer->priority = HEVENT_HIGH_PRIORITY;
  484. timer->repeat = repeat;
  485. timer->minute = minute;
  486. timer->hour = hour;
  487. timer->day = day;
  488. timer->month = month;
  489. timer->week = week;
  490. timer->next_timeout = (uint64_t)cron_next_timeout(minute, hour, day, week, month) * 1000000;
  491. heap_insert(&loop->timers, &timer->node);
  492. EVENT_ADD(loop, timer, cb);
  493. loop->ntimers++;
  494. return (htimer_t*)timer;
  495. }
  496. static void __htimer_del(htimer_t* timer) {
  497. if (timer->destroy) return;
  498. heap_remove(&timer->loop->timers, &timer->node);
  499. timer->loop->ntimers--;
  500. timer->destroy = 1;
  501. }
  502. void htimer_del(htimer_t* timer) {
  503. if (!timer->active) return;
  504. __htimer_del(timer);
  505. EVENT_DEL(timer);
  506. }
  507. const char* hio_engine() {
  508. #ifdef EVENT_SELECT
  509. return "select";
  510. #elif defined(EVENT_POLL)
  511. return "poll";
  512. #elif defined(EVENT_EPOLL)
  513. return "epoll";
  514. #elif defined(EVENT_KQUEUE)
  515. return "kqueue";
  516. #elif defined(EVENT_IOCP)
  517. return "iocp";
  518. #elif defined(EVENT_PORT)
  519. return "evport";
  520. #else
  521. return "noevent";
  522. #endif
  523. }
  524. static void fill_io_type(hio_t* io) {
  525. int type = 0;
  526. socklen_t optlen = sizeof(int);
  527. int ret = getsockopt(io->fd, SOL_SOCKET, SO_TYPE, (char*)&type, &optlen);
  528. printd("getsockopt SO_TYPE fd=%d ret=%d type=%d errno=%d\n", io->fd, ret, type, socket_errno());
  529. if (ret == 0) {
  530. switch (type) {
  531. case SOCK_STREAM: io->io_type = HIO_TYPE_TCP; break;
  532. case SOCK_DGRAM: io->io_type = HIO_TYPE_UDP; break;
  533. case SOCK_RAW: io->io_type = HIO_TYPE_IP; break;
  534. default: io->io_type = HIO_TYPE_SOCKET; break;
  535. }
  536. }
  537. else if (socket_errno() == ENOTSOCK) {
  538. switch (io->fd) {
  539. case 0: io->io_type = HIO_TYPE_STDIN; break;
  540. case 1: io->io_type = HIO_TYPE_STDOUT; break;
  541. case 2: io->io_type = HIO_TYPE_STDERR; break;
  542. default: io->io_type = HIO_TYPE_FILE; break;
  543. }
  544. }
  545. else {
  546. io->io_type = HIO_TYPE_TCP;
  547. }
  548. }
  549. static void hio_socket_init(hio_t* io) {
  550. // nonblocking
  551. nonblocking(io->fd);
  552. // fill io->localaddr io->peeraddr
  553. if (io->localaddr == NULL) {
  554. HV_ALLOC(io->localaddr, sizeof(sockaddr_u));
  555. }
  556. if (io->peeraddr == NULL) {
  557. HV_ALLOC(io->peeraddr, sizeof(sockaddr_u));
  558. }
  559. socklen_t addrlen = sizeof(sockaddr_u);
  560. int ret = getsockname(io->fd, io->localaddr, &addrlen);
  561. printd("getsockname fd=%d ret=%d errno=%d\n", io->fd, ret, socket_errno());
  562. // NOTE:
  563. // tcp_server peeraddr set by accept
  564. // udp_server peeraddr set by recvfrom
  565. // tcp_client/udp_client peeraddr set by hio_setpeeraddr
  566. if (io->io_type == HIO_TYPE_TCP || io->io_type == HIO_TYPE_SSL) {
  567. // tcp acceptfd
  568. addrlen = sizeof(sockaddr_u);
  569. ret = getpeername(io->fd, io->peeraddr, &addrlen);
  570. printd("getpeername fd=%d ret=%d errno=%d\n", io->fd, ret, socket_errno());
  571. }
  572. }
  573. void hio_init(hio_t* io) {
  574. // alloc localaddr,peeraddr when hio_socket_init
  575. /*
  576. if (io->localaddr == NULL) {
  577. HV_ALLOC(io->localaddr, sizeof(sockaddr_u));
  578. }
  579. if (io->peeraddr == NULL) {
  580. HV_ALLOC(io->peeraddr, sizeof(sockaddr_u));
  581. }
  582. */
  583. // write_queue init when hwrite try_write failed
  584. // write_queue_init(&io->write_queue, 4);
  585. hrecursive_mutex_init(&io->write_mutex);
  586. }
  587. void hio_ready(hio_t* io) {
  588. if (io->ready) return;
  589. // flags
  590. io->ready = 1;
  591. io->closed = 0;
  592. io->accept = io->connect = io->connectex = 0;
  593. io->recv = io->send = 0;
  594. io->recvfrom = io->sendto = 0;
  595. io->close = 0;
  596. // public:
  597. io->id = hio_next_id();
  598. io->io_type = HIO_TYPE_UNKNOWN;
  599. io->error = 0;
  600. io->events = io->revents = 0;
  601. // readbuf
  602. io->readbuf.base = io->loop->readbuf.base;
  603. io->readbuf.len = io->loop->readbuf.len;
  604. io->readbuf.offset = 0;
  605. // callbacks
  606. io->read_cb = NULL;
  607. io->write_cb = NULL;
  608. io->close_cb = NULL;
  609. io->accept_cb = NULL;
  610. io->connect_cb = NULL;
  611. // timers
  612. io->connect_timeout = 0;
  613. io->connect_timer = NULL;
  614. io->close_timeout = 0;
  615. io->close_timer = NULL;
  616. io->keepalive_timeout = 0;
  617. io->keepalive_timer = NULL;
  618. io->heartbeat_interval = 0;
  619. io->heartbeat_fn = NULL;
  620. io->heartbeat_timer = NULL;
  621. // upstream
  622. io->upstream_io = NULL;
  623. // unpack
  624. io->unpack_setting = NULL;
  625. // private:
  626. io->event_index[0] = io->event_index[1] = -1;
  627. io->hovlp = NULL;
  628. io->ssl = NULL;
  629. // io_type
  630. fill_io_type(io);
  631. if (io->io_type & HIO_TYPE_SOCKET) {
  632. hio_socket_init(io);
  633. }
  634. }
  635. void hio_done(hio_t* io) {
  636. if (!io->ready) return;
  637. io->ready = 0;
  638. hio_del(io, HV_RDWR);
  639. // readbuf
  640. hio_unset_unpack(io);
  641. // write_queue
  642. offset_buf_t* pbuf = NULL;
  643. hrecursive_mutex_lock(&io->write_mutex);
  644. while (!write_queue_empty(&io->write_queue)) {
  645. pbuf = write_queue_front(&io->write_queue);
  646. HV_FREE(pbuf->base);
  647. write_queue_pop_front(&io->write_queue);
  648. }
  649. write_queue_cleanup(&io->write_queue);
  650. hrecursive_mutex_unlock(&io->write_mutex);
  651. }
  652. void hio_free(hio_t* io) {
  653. if (io == NULL) return;
  654. // NOTE: call hio_done to cleanup write_queue
  655. hio_done(io);
  656. // NOTE: call hio_close to call hclose_cb
  657. hio_close(io);
  658. hrecursive_mutex_destroy(&io->write_mutex);
  659. HV_FREE(io->localaddr);
  660. HV_FREE(io->peeraddr);
  661. HV_FREE(io);
  662. }
  663. bool hio_is_opened(hio_t* io) {
  664. if (io == NULL) return false;
  665. return io->ready == 1 && io->closed == 0;
  666. }
  667. bool hio_is_closed(hio_t* io) {
  668. if (io == NULL) return true;
  669. return io->ready == 0 && io->closed == 1;
  670. }
  671. hio_t* hio_get(hloop_t* loop, int fd) {
  672. if (fd >= loop->ios.maxsize) {
  673. int newsize = ceil2e(fd);
  674. io_array_resize(&loop->ios, newsize > fd ? newsize : 2*fd);
  675. }
  676. hio_t* io = loop->ios.ptr[fd];
  677. if (io == NULL) {
  678. HV_ALLOC_SIZEOF(io);
  679. hio_init(io);
  680. io->event_type = HEVENT_TYPE_IO;
  681. io->loop = loop;
  682. io->fd = fd;
  683. loop->ios.ptr[fd] = io;
  684. }
  685. if (!io->ready) {
  686. hio_ready(io);
  687. }
  688. return io;
  689. }
  690. void hio_detach(hio_t* io) {
  691. hloop_t* loop = io->loop;
  692. int fd = io->fd;
  693. assert(loop != NULL && fd < loop->ios.maxsize);
  694. loop->ios.ptr[fd] = NULL;
  695. }
  696. void hio_attach(hloop_t* loop, hio_t* io) {
  697. int fd = io->fd;
  698. if (fd >= loop->ios.maxsize) {
  699. int newsize = ceil2e(fd);
  700. io_array_resize(&loop->ios, newsize > fd ? newsize : 2*fd);
  701. }
  702. if (loop->ios.ptr[fd] == NULL) {
  703. io->loop = loop;
  704. // NOTE: use new_loop readbuf
  705. io->readbuf.base = loop->readbuf.base;
  706. io->readbuf.len = loop->readbuf.len;
  707. loop->ios.ptr[fd] = io;
  708. }
  709. }
  710. int hio_add(hio_t* io, hio_cb cb, int events) {
  711. printd("hio_add fd=%d io->events=%d events=%d\n", io->fd, io->events, events);
  712. #ifdef OS_WIN
  713. // Windows iowatcher not work on stdio
  714. if (io->fd < 3) return -1;
  715. #endif
  716. hloop_t* loop = io->loop;
  717. if (!io->active) {
  718. EVENT_ADD(loop, io, cb);
  719. loop->nios++;
  720. }
  721. if (!io->ready) {
  722. hio_ready(io);
  723. }
  724. if (cb) {
  725. io->cb = (hevent_cb)cb;
  726. }
  727. if (!(io->events & events)) {
  728. iowatcher_add_event(loop, io->fd, events);
  729. io->events |= events;
  730. }
  731. return 0;
  732. }
  733. int hio_del(hio_t* io, int events) {
  734. printd("hio_del fd=%d io->events=%d events=%d\n", io->fd, io->events, events);
  735. #ifdef OS_WIN
  736. // Windows iowatcher not work on stdio
  737. if (io->fd < 3) return -1;
  738. #endif
  739. if (!io->active) return -1;
  740. if (io->events & events) {
  741. iowatcher_del_event(io->loop, io->fd, events);
  742. io->events &= ~events;
  743. }
  744. if (io->events == 0) {
  745. io->loop->nios--;
  746. // NOTE: not EVENT_DEL, avoid free
  747. EVENT_INACTIVE(io);
  748. }
  749. return 0;
  750. }
  751. static void hio_close_event_cb(hevent_t* ev) {
  752. hio_t* io = (hio_t*)ev->userdata;
  753. uint32_t id = (uintptr_t)ev->privdata;
  754. if (io->id != id) return;
  755. hio_close(io);
  756. }
  757. int hio_close_async(hio_t* io) {
  758. hevent_t ev;
  759. memset(&ev, 0, sizeof(ev));
  760. ev.cb = hio_close_event_cb;
  761. ev.userdata = io;
  762. ev.privdata = (void*)(uintptr_t)io->id;
  763. ev.priority = HEVENT_HIGH_PRIORITY;
  764. hloop_post_event(io->loop, &ev);
  765. return 0;
  766. }
  767. hio_t* hread(hloop_t* loop, int fd, void* buf, size_t len, hread_cb read_cb) {
  768. hio_t* io = hio_get(loop, fd);
  769. assert(io != NULL);
  770. if (buf && len) {
  771. io->readbuf.base = (char*)buf;
  772. io->readbuf.len = len;
  773. }
  774. if (read_cb) {
  775. io->read_cb = read_cb;
  776. }
  777. hio_read(io);
  778. return io;
  779. }
  780. hio_t* hwrite(hloop_t* loop, int fd, const void* buf, size_t len, hwrite_cb write_cb) {
  781. hio_t* io = hio_get(loop, fd);
  782. assert(io != NULL);
  783. if (write_cb) {
  784. io->write_cb = write_cb;
  785. }
  786. hio_write(io, buf, len);
  787. return io;
  788. }
  789. hio_t* haccept(hloop_t* loop, int listenfd, haccept_cb accept_cb) {
  790. hio_t* io = hio_get(loop, listenfd);
  791. assert(io != NULL);
  792. if (accept_cb) {
  793. io->accept_cb = accept_cb;
  794. }
  795. hio_accept(io);
  796. return io;
  797. }
  798. hio_t* hconnect (hloop_t* loop, int connfd, hconnect_cb connect_cb) {
  799. hio_t* io = hio_get(loop, connfd);
  800. assert(io != NULL);
  801. if (connect_cb) {
  802. io->connect_cb = connect_cb;
  803. }
  804. hio_connect(io);
  805. return io;
  806. }
  807. void hclose (hloop_t* loop, int fd) {
  808. hio_t* io = hio_get(loop, fd);
  809. assert(io != NULL);
  810. hio_close(io);
  811. }
  812. hio_t* hrecv (hloop_t* loop, int connfd, void* buf, size_t len, hread_cb read_cb) {
  813. //hio_t* io = hio_get(loop, connfd);
  814. //assert(io != NULL);
  815. //io->recv = 1;
  816. //if (io->io_type != HIO_TYPE_SSL) {
  817. //io->io_type = HIO_TYPE_TCP;
  818. //}
  819. return hread(loop, connfd, buf, len, read_cb);
  820. }
  821. hio_t* hsend (hloop_t* loop, int connfd, const void* buf, size_t len, hwrite_cb write_cb) {
  822. //hio_t* io = hio_get(loop, connfd);
  823. //assert(io != NULL);
  824. //io->send = 1;
  825. //if (io->io_type != HIO_TYPE_SSL) {
  826. //io->io_type = HIO_TYPE_TCP;
  827. //}
  828. return hwrite(loop, connfd, buf, len, write_cb);
  829. }
  830. hio_t* hrecvfrom (hloop_t* loop, int sockfd, void* buf, size_t len, hread_cb read_cb) {
  831. //hio_t* io = hio_get(loop, sockfd);
  832. //assert(io != NULL);
  833. //io->recvfrom = 1;
  834. //io->io_type = HIO_TYPE_UDP;
  835. return hread(loop, sockfd, buf, len, read_cb);
  836. }
  837. hio_t* hsendto (hloop_t* loop, int sockfd, const void* buf, size_t len, hwrite_cb write_cb) {
  838. //hio_t* io = hio_get(loop, sockfd);
  839. //assert(io != NULL);
  840. //io->sendto = 1;
  841. //io->io_type = HIO_TYPE_UDP;
  842. return hwrite(loop, sockfd, buf, len, write_cb);
  843. }
  844. hio_t* hio_create(hloop_t* loop, const char* host, int port, int type) {
  845. sockaddr_u peeraddr;
  846. memset(&peeraddr, 0, sizeof(peeraddr));
  847. int ret = sockaddr_set_ipport(&peeraddr, host, port);
  848. if (ret != 0) {
  849. //printf("unknown host: %s\n", host);
  850. return NULL;
  851. }
  852. int connfd = socket(peeraddr.sa.sa_family, type, 0);
  853. if (connfd < 0) {
  854. perror("socket");
  855. return NULL;
  856. }
  857. hio_t* io = hio_get(loop, connfd);
  858. assert(io != NULL);
  859. hio_set_peeraddr(io, &peeraddr.sa, sockaddr_len(&peeraddr));
  860. return io;
  861. }
  862. hio_t* hloop_create_tcp_server (hloop_t* loop, const char* host, int port, haccept_cb accept_cb) {
  863. int listenfd = Listen(port, host);
  864. if (listenfd < 0) {
  865. return NULL;
  866. }
  867. hio_t* io = haccept(loop, listenfd, accept_cb);
  868. if (io == NULL) {
  869. closesocket(listenfd);
  870. }
  871. return io;
  872. }
  873. hio_t* hloop_create_tcp_client (hloop_t* loop, const char* host, int port, hconnect_cb connect_cb) {
  874. hio_t* io = hio_create(loop, host, port, SOCK_STREAM);
  875. if (io == NULL) return NULL;
  876. hconnect(loop, io->fd, connect_cb);
  877. return io;
  878. }
  879. hio_t* hloop_create_ssl_server (hloop_t* loop, const char* host, int port, haccept_cb accept_cb) {
  880. hio_t* io = hloop_create_tcp_server(loop, host, port, accept_cb);
  881. if (io == NULL) return NULL;
  882. hio_enable_ssl(io);
  883. return io;
  884. }
  885. hio_t* hloop_create_ssl_client (hloop_t* loop, const char* host, int port, hconnect_cb connect_cb) {
  886. hio_t* io = hio_create(loop, host, port, SOCK_STREAM);
  887. if (io == NULL) return NULL;
  888. hio_enable_ssl(io);
  889. hconnect(loop, io->fd, connect_cb);
  890. return io;
  891. }
  892. hio_t* hloop_create_udp_server(hloop_t* loop, const char* host, int port) {
  893. int bindfd = Bind(port, host, SOCK_DGRAM);
  894. if (bindfd < 0) {
  895. return NULL;
  896. }
  897. return hio_get(loop, bindfd);
  898. }
  899. hio_t* hloop_create_udp_client(hloop_t* loop, const char* host, int port) {
  900. return hio_create(loop, host, port, SOCK_DGRAM);
  901. }
  902. // upstream
  903. void hio_read_upstream(hio_t* io) {
  904. hio_t* upstream_io = io->upstream_io;
  905. if (upstream_io) {
  906. hio_read(io);
  907. hio_read(upstream_io);
  908. }
  909. }
  910. void hio_write_upstream(hio_t* io, void* buf, int bytes) {
  911. hio_t* upstream_io = io->upstream_io;
  912. if (upstream_io) {
  913. hio_write(upstream_io, buf, bytes);
  914. }
  915. }
  916. void hio_close_upstream(hio_t* io) {
  917. hio_t* upstream_io = io->upstream_io;
  918. if (upstream_io) {
  919. hio_close(upstream_io);
  920. }
  921. }
  922. void hio_setup_upstream(hio_t* io1, hio_t* io2) {
  923. io1->upstream_io = io2;
  924. io2->upstream_io = io1;
  925. hio_setcb_read(io1, hio_write_upstream);
  926. hio_setcb_read(io2, hio_write_upstream);
  927. }
  928. hio_t* hio_get_upstream(hio_t* io) {
  929. return io->upstream_io;
  930. }
  931. hio_t* hio_setup_tcp_upstream(hio_t* io, const char* host, int port, int ssl) {
  932. hio_t* upstream_io = hio_create(io->loop, host, port, SOCK_STREAM);
  933. if (upstream_io == NULL) return NULL;
  934. if (ssl) hio_enable_ssl(upstream_io);
  935. hio_setup_upstream(io, upstream_io);
  936. hio_setcb_close(io, hio_close_upstream);
  937. hio_setcb_close(upstream_io, hio_close_upstream);
  938. hconnect(io->loop, upstream_io->fd, hio_read_upstream);
  939. return upstream_io;
  940. }
  941. hio_t* hio_setup_udp_upstream(hio_t* io, const char* host, int port) {
  942. hio_t* upstream_io = hio_create(io->loop, host, port, SOCK_DGRAM);
  943. if (upstream_io == NULL) return NULL;
  944. hio_setup_upstream(io, upstream_io);
  945. hio_read_upstream(io);
  946. return upstream_io;
  947. }