forked from memcached/memcached
-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxy_network.c
1673 lines (1443 loc) · 58.5 KB
/
proxy_network.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
// Functions related to the backend handler thread.
#include "proxy.h"
enum proxy_be_failures {
P_BE_FAIL_TIMEOUT = 0,
P_BE_FAIL_DISCONNECTED,
P_BE_FAIL_CONNECTING,
P_BE_FAIL_READVALIDATE,
P_BE_FAIL_BADVALIDATE,
P_BE_FAIL_WRITING,
P_BE_FAIL_READING,
P_BE_FAIL_PARSING,
P_BE_FAIL_CLOSED,
P_BE_FAIL_UNHANDLEDRES,
P_BE_FAIL_OOM,
P_BE_FAIL_ENDSYNC,
P_BE_FAIL_TRAILINGDATA,
};
const char *proxy_be_failure_text[] = {
[P_BE_FAIL_TIMEOUT] = "timeout",
[P_BE_FAIL_DISCONNECTED] = "disconnected",
[P_BE_FAIL_CONNECTING] = "connecting",
[P_BE_FAIL_READVALIDATE] = "readvalidate",
[P_BE_FAIL_BADVALIDATE] = "badvalidate",
[P_BE_FAIL_WRITING] = "writing",
[P_BE_FAIL_READING] = "reading",
[P_BE_FAIL_PARSING] = "parsing",
[P_BE_FAIL_CLOSED] = "closedsock",
[P_BE_FAIL_UNHANDLEDRES] = "unhandledres",
[P_BE_FAIL_OOM] = "outofmemory",
[P_BE_FAIL_ENDSYNC] = "missingend",
[P_BE_FAIL_TRAILINGDATA] = "trailingdata",
NULL
};
static void proxy_backend_handler(const int fd, const short which, void *arg);
static void proxy_beconn_handler(const int fd, const short which, void *arg);
static void proxy_event_handler(evutil_socket_t fd, short which, void *arg);
static void proxy_event_beconn(evutil_socket_t fd, short which, void *arg);
static void proxy_event_updater(evutil_socket_t fd, short which, void *arg);
static int _prep_pending_write(mcp_backend_t *be);
static bool _post_pending_write(mcp_backend_t *be, ssize_t sent);
static int _flush_pending_write(mcp_backend_t *be);
static void _cleanup_backend(mcp_backend_t *be);
static int _reset_bad_backend(mcp_backend_t *be, enum proxy_be_failures err);
static void _backend_failed(mcp_backend_t *be);
static void _set_event(mcp_backend_t *be, struct event_base *base, int flags, struct timeval t, event_callback_fn callback);
static int proxy_backend_drive_machine(mcp_backend_t *be);
/* Helper routines common to io_uring and libevent modes */
// TODO (v3): doing an inline syscall here, not ideal for uring mode.
// leaving for now since this should be extremely uncommon.
static int _beconn_send_validate(mcp_backend_t *be) {
const char *str = "version\r\n";
const ssize_t len = strlen(str);
ssize_t res = write(mcmc_fd(be->client), str, len);
if (res == -1) {
return -1;
}
// I'm making an opinionated statement that we should be able to write
// "version\r\n" into a fresh socket without hitting EAGAIN.
if (res < len) {
return -1;
}
return 1;
}
// FIXME: make _backend_failed conditionally use _ur() so we can have one call
// in the code and reuse more code like this.
static int _proxy_beconn_checkconnect(mcp_backend_t *be) {
int err = 0;
// We were connecting, now ensure we're properly connected.
if (mcmc_check_nonblock_connect(be->client, &err) != MCMC_OK) {
P_DEBUG("%s: backend failed to connect (%s:%s)\n", __func__, be->name, be->port);
// kick the bad backend, clear the queue, retry later.
// FIXME (v2): if a connect fails, anything currently in the queue
// should be safe to hold up until their timeout.
_reset_bad_backend(be, P_BE_FAIL_CONNECTING);
_backend_failed(be);
return -1;
}
P_DEBUG("%s: backend connected (%s:%s)\n", __func__, be->name, be->port);
be->connecting = false;
be->state = mcp_backend_read;
be->bad = false;
be->failed_count = 0;
be->validating = true;
// TODO: make validation optional.
if (_beconn_send_validate(be) == -1) {
_reset_bad_backend(be, P_BE_FAIL_BADVALIDATE);
_backend_failed(be);
return -1;
} else {
// buffer should be empty during validation stage.
assert(be->rbufused == 0);
return 0;
}
}
static int _proxy_event_handler_dequeue(proxy_event_thread_t *t) {
io_head_t head;
STAILQ_INIT(&head);
STAILQ_INIT(&t->be_head);
// Pull the entire stack of inbound into local queue.
pthread_mutex_lock(&t->mutex);
STAILQ_CONCAT(&head, &t->io_head_in);
pthread_mutex_unlock(&t->mutex);
int io_count = 0;
int be_count = 0;
while (!STAILQ_EMPTY(&head)) {
io_pending_proxy_t *io = STAILQ_FIRST(&head);
io->flushed = false;
// _no_ mutex on backends. they are owned by the event thread.
STAILQ_REMOVE_HEAD(&head, io_next);
// paranoia about moving items between lists.
io->io_next.stqe_next = NULL;
// Need to check on await's before looking at backends, in case it
// doesn't have one.
// Here we're letting an await resume without waiting on the network.
if (io->await_background) {
return_io_pending((io_pending_t *)io);
continue;
}
mcp_backend_t *be = io->backend;
// So the backend can retrieve its event base.
be->event_thread = t;
if (be->bad) {
P_DEBUG("%s: fast failing request to bad backend\n", __func__);
io->client_resp->status = MCMC_ERR;
return_io_pending((io_pending_t *)io);
continue;
}
STAILQ_INSERT_TAIL(&be->io_head, io, io_next);
if (be->io_next == NULL) {
be->io_next = io; // set write flush starting point.
}
be->depth++;
io_count++;
if (!be->stacked) {
be->stacked = true;
// more paranoia about be_next not being overwritten
be->be_next.stqe_next = NULL;
STAILQ_INSERT_TAIL(&t->be_head, be, be_next);
be_count++;
}
}
//P_DEBUG("%s: io/be counts for syscalls [%d/%d]\n", __func__, io_count, be_count);
return io_count;
}
#ifdef HAVE_LIBURING
//static void _proxy_evthr_evset_wnotify(proxy_event_thread_t *t, int notify_fd);
static void _proxy_evthr_evset_be_read(mcp_backend_t *be, char *buf, size_t len, struct __kernel_timespec *ts);
static void _proxy_evthr_evset_be_writev(mcp_backend_t *be, int iovcnt, struct __kernel_timespec *ts);
static void _proxy_evthr_evset_be_wrpoll(mcp_backend_t *be, struct __kernel_timespec *ts);
static void _proxy_evthr_evset_be_retry(mcp_backend_t *be);
static void _proxy_evthr_evset_be_conn(mcp_backend_t *be, struct __kernel_timespec *ts);
static void _proxy_evthr_evset_be_readvalidate(mcp_backend_t *be, char *buf, size_t len, struct __kernel_timespec *ts);
static void _proxy_evthr_evset_notifier(proxy_event_thread_t *t);
static void _proxy_evthr_evset_benotifier(proxy_event_thread_t *t);
static void _proxy_evthr_evset_clock(proxy_event_thread_t *t);
static void proxy_event_updater_ur(void *udata, struct io_uring_cqe *cqe);
static void _backend_failed_ur(mcp_backend_t *be);
struct __kernel_timespec updater_ts = {.tv_sec = 3, .tv_nsec = 0};
static void _flush_pending_write_ur(mcp_backend_t *be) {
// Allow us to be called with an empty stack to prevent dev errors.
if (STAILQ_EMPTY(&be->io_head)) {
return;
}
int iovcnt = _prep_pending_write(be);
// TODO: write timeout.
_proxy_evthr_evset_be_writev(be, iovcnt, &be->event_thread->tunables.read_ur);
}
// TODO: we shouldn't handle reads if a write is pending, so postwrite should
// check for pending read data before going into read mode.
// need be->writing flag to toggle?
static void proxy_backend_postwrite_ur(void *udata, struct io_uring_cqe *cqe) {
mcp_backend_t *be = udata;
P_DEBUG("%s: %d\n", __func__, cqe->res);
assert(cqe->res != -EINVAL);
int sent = cqe->res;
if (sent < 0) {
// FIXME: sent == 0 is disconnected? I keep forgetting.
if (sent == -EAGAIN || sent == -EWOULDBLOCK) {
// didn't do any writing, wait for a writeable socket.
_proxy_evthr_evset_be_wrpoll(be, &be->event_thread->tunables.read_ur);
} else {
_reset_bad_backend(be, P_BE_FAIL_WRITING);
_backend_failed_ur(be);
}
}
if (_post_pending_write(be, sent)) {
// commands were flushed, set read handler.
_proxy_evthr_evset_be_read(be, be->rbuf+be->rbufused, READ_BUFFER_SIZE-be->rbufused, &be->event_thread->tunables.read_ur);
}
if (be->io_next) {
// still have unflushed commands, re-run write command.
// writev can't "block if EAGAIN" in io_uring so far as I can tell, so
// we have to switch to polling mode here.
_proxy_evthr_evset_be_wrpoll(be, &be->event_thread->tunables.read_ur);
}
// TODO: if rbufused != 0, push through drive machine?
}
static void proxy_event_updater_ur(void *udata, struct io_uring_cqe *cqe) {
proxy_event_thread_t *t = udata;
proxy_ctx_t *ctx = t->ctx;
_proxy_evthr_evset_clock(t);
// we reuse the "global stats" lock since it's hardly ever used.
STAT_L(ctx);
memcpy(&t->tunables, &ctx->tunables, sizeof(t->tunables));
STAT_UL(ctx);
}
// No-op at the moment. when the linked timeout fires uring returns the
// linked request (read/write/poll/etc) with an interrupted/timeout/cancelled
// error. So we don't need to explicitly handle timeouts.
// I'm leaving the structure in to simplify the callback routine.
// Since timeouts rarely get called the extra code here shouldn't matter.
static void proxy_backend_timeout_handler_ur(void *udata, struct io_uring_cqe *cqe) {
return;
}
static void proxy_backend_retry_handler_ur(void *udata, struct io_uring_cqe *cqe) {
mcp_backend_t *be = udata;
_proxy_evthr_evset_be_conn(be, &be->event_thread->tunables.connect_ur);
}
static void _proxy_evthr_evset_be_retry(mcp_backend_t *be) {
struct io_uring_sqe *sqe;
if (be->ur_te_ev.set)
return;
be->ur_te_ev.cb = proxy_backend_retry_handler_ur;
be->ur_te_ev.udata = be;
sqe = io_uring_get_sqe(&be->event_thread->ring);
// TODO (v2): NULL?
io_uring_prep_timeout(sqe, &be->event_thread->tunables.retry_ur, 0, 0);
io_uring_sqe_set_data(sqe, &be->ur_te_ev);
be->ur_te_ev.set = true;
}
static void _backend_failed_ur(mcp_backend_t *be) {
if (++be->failed_count > be->event_thread->tunables.backend_failure_limit) {
P_DEBUG("%s: marking backend as bad\n", __func__);
be->bad = true;
_proxy_evthr_evset_be_retry(be);
STAT_INCR(be->event_thread->ctx, backend_marked_bad, 1);
} else {
_proxy_evthr_evset_be_conn(be, &be->event_thread->tunables.connect_ur);
STAT_INCR(be->event_thread->ctx, backend_failed, 1);
}
}
// read handler.
static void proxy_backend_handler_ur(void *udata, struct io_uring_cqe *cqe) {
mcp_backend_t *be = udata;
int bread = cqe->res;
// Error or disconnection.
if (bread <= 0) {
_reset_bad_backend(be, P_BE_FAIL_DISCONNECTED);
_backend_failed_ur(be);
return;
}
be->rbufused += bread;
int res = proxy_backend_drive_machine(be);
if (res != 0) {
_reset_bad_backend(be, res);
_backend_failed_ur(be);
return;
}
// TODO (v2): when exactly do we need to reset the backend handler?
if (!STAILQ_EMPTY(&be->io_head)) {
_proxy_evthr_evset_be_read(be, be->rbuf+be->rbufused, READ_BUFFER_SIZE-be->rbufused, &be->event_thread->tunables.read_ur);
}
}
static void proxy_backend_wrhandler_ur(void *udata, struct io_uring_cqe *cqe) {
mcp_backend_t *be = udata;
be->can_write = true;
_flush_pending_write_ur(be);
_proxy_evthr_evset_be_read(be, be->rbuf+be->rbufused, READ_BUFFER_SIZE-be->rbufused, &be->event_thread->tunables.read_ur);
}
// a backend with an outstanding new connection has become writeable.
// check validity.
// TODO: this gets an error if cancelled right?
static void proxy_backend_beconn_ur(void *udata, struct io_uring_cqe *cqe) {
mcp_backend_t *be = udata;
int err = 0;
assert(be->connecting);
/* if (_proxy_beconn_checkconnect(be) == -1) {
return;
} */
// We were connecting, now ensure we're properly connected.
if (mcmc_check_nonblock_connect(be->client, &err) != MCMC_OK) {
P_DEBUG("%s: backend failed to connect (%s:%s)\n", __func__, be->name, be->port);
// kick the bad backend, clear the queue, retry later.
// FIXME (v2): if a connect fails, anything currently in the queue
// should be safe to hold up until their timeout.
_reset_bad_backend(be, P_BE_FAIL_CONNECTING);
_backend_failed_ur(be);
return;
}
P_DEBUG("%s: backend connected (%s:%s)\n", __func__, be->name, be->port);
be->connecting = false;
be->state = mcp_backend_read;
be->bad = false;
be->failed_count = 0;
be->validating = true;
// TODO: make validation optional.
if (_beconn_send_validate(be) == -1) {
_reset_bad_backend(be, P_BE_FAIL_BADVALIDATE);
_backend_failed_ur(be);
return;
} else {
// buffer should be empty during validation stage.
assert(be->rbufused == 0);
}
// TODO: make validation optional.
// set next handler on recv for validity check.
_proxy_evthr_evset_be_readvalidate(be, be->rbuf, READ_BUFFER_SIZE, &be->event_thread->tunables.read_ur);
}
// TODO: share more code with proxy_beconn_handler
static void proxy_backend_beconn_validate_ur(void *udata, struct io_uring_cqe *cqe) {
mcp_backend_t *be = udata;
mcmc_resp_t r;
assert(be->validating);
assert(cqe->res != -EINVAL);
P_DEBUG("%s: checking validation: %d\n", __func__, cqe->res);
int bread = cqe->res;
// Error or disconnection.
if (bread <= 0) {
_reset_bad_backend(be, P_BE_FAIL_DISCONNECTED);
_backend_failed_ur(be);
return;
}
be->rbufused += bread;
int status = mcmc_parse_buf(be->client, be->rbuf, be->rbufused, &r);
if (status == MCMC_ERR) {
// Needed more data for a version line, somehow. For the uring code
// we'll treat that as an error, for now.
// TODO: re-schedule self if r.code == MCMC_WANT_READ.
_reset_bad_backend(be, P_BE_FAIL_READVALIDATE);
_backend_failed_ur(be);
return;
}
if (r.code != MCMC_CODE_VERSION) {
_reset_bad_backend(be, P_BE_FAIL_BADVALIDATE);
_backend_failed_ur(be);
return;
}
be->validating = false;
be->rbufused = 0;
// Passed validation, don't need to re-read, flush any pending writes.
_flush_pending_write(be);
}
// TODO (v3): much code shared with proxy_event_beconn, should be able to
// abstract out.
// TODO (v3): further optimization would move the mcmc_connect() socket
// creation to uring.
static void proxy_beconn_handler_ur(void *udata, struct io_uring_cqe *cqe) {
proxy_event_thread_t *t = udata;
P_DEBUG("%s: got wakeup: %d\n", __func__, cqe->res);
// liburing always uses eventfd for the notifier.
// *cqe has our result.
assert(cqe->res != -EINVAL);
if (cqe->res != sizeof(eventfd_t)) {
P_DEBUG("%s: cqe->res: %d\n", __func__, cqe->res);
// FIXME (v2): figure out if this is impossible, and how to handle if not.
assert(1 == 0);
}
// need to re-arm the listener every time.
_proxy_evthr_evset_benotifier(t);
beconn_head_t head;
STAILQ_INIT(&head);
pthread_mutex_lock(&t->mutex);
STAILQ_CONCAT(&head, &t->beconn_head_in);
pthread_mutex_unlock(&t->mutex);
mcp_backend_t *be = NULL;
// be can be freed by the loop, so can't use STAILQ_FOREACH.
while (!STAILQ_EMPTY(&head)) {
be = STAILQ_FIRST(&head);
STAILQ_REMOVE_HEAD(&head, beconn_next);
if (be->transferred) {
// If this object was already transferred here, we're being
// signalled to clean it up and free.
_cleanup_backend(be);
} else {
be->transferred = true;
be->event_thread = t;
int status = mcmc_connect(be->client, be->name, be->port, be->connect_flags);
if (status == MCMC_CONNECTING || status == MCMC_CONNECTED) {
// if we're already connected for some reason, still push it
// through the connection handler to keep the code unified. It
// will auto-wake because the socket is writeable.
be->connecting = true;
be->can_write = false;
_proxy_evthr_evset_be_conn(be, &t->tunables.connect_ur);
} else {
_reset_bad_backend(be, P_BE_FAIL_CONNECTING);
_backend_failed_ur(be);
}
}
}
}
static void proxy_event_handler_ur(void *udata, struct io_uring_cqe *cqe) {
proxy_event_thread_t *t = udata;
// liburing always uses eventfd for the notifier.
// *cqe has our result.
assert(cqe->res != -EINVAL);
if (cqe->res != sizeof(eventfd_t)) {
P_DEBUG("%s: cqe->res: %d\n", __func__, cqe->res);
// FIXME (v2): figure out if this is impossible, and how to handle if not.
assert(1 == 0);
}
// need to re-arm the listener every time.
_proxy_evthr_evset_notifier(t);
// TODO (v2): sqe queues for writing to backends
// - _ur handler for backend write completion is to set a read event and
// re-submit. ugh.
// Should be possible to have standing reads, but flow is harder and lets
// optimize that later. (ie; allow matching reads to a request but don't
// actually dequeue anything until both read and write are confirmed)
if (_proxy_event_handler_dequeue(t) == 0) {
//P_DEBUG("%s: no IO's to complete\n", __func__);
return;
}
// Re-walk each backend and check set event as required.
mcp_backend_t *be = NULL;
// TODO (v2): for each backend, queue writev's into sqe's
// move the backend sqe bits into a write complete handler
STAILQ_FOREACH(be, &t->be_head, be_next) {
be->stacked = false;
if (be->connecting || be->validating) {
P_DEBUG("%s: deferring IO pending connecting\n", __func__);
} else {
_flush_pending_write_ur(be);
}
}
}
static void _proxy_evthr_evset_be_readvalidate(mcp_backend_t *be, char *buf, size_t len, struct __kernel_timespec *ts) {
P_DEBUG("%s: setting: %lu\n", __func__, len);
struct io_uring_sqe *sqe;
if (be->ur_rd_ev.set) {
P_DEBUG("%s: already set\n", __func__);
return;
}
be->ur_rd_ev.cb = proxy_backend_beconn_validate_ur;
be->ur_rd_ev.udata = be;
sqe = io_uring_get_sqe(&be->event_thread->ring);
// FIXME (v2): NULL?
assert(be->rbuf != NULL);
io_uring_prep_recv(sqe, mcmc_fd(be->client), buf, len, 0);
io_uring_sqe_set_data(sqe, &be->ur_rd_ev);
be->ur_rd_ev.set = true;
sqe->flags |= IOSQE_IO_LINK;
// add a timeout.
be->ur_te_ev.cb = proxy_backend_timeout_handler_ur;
be->ur_te_ev.udata = be;
sqe = io_uring_get_sqe(&be->event_thread->ring);
io_uring_prep_link_timeout(sqe, ts, 0);
io_uring_sqe_set_data(sqe, &be->ur_te_ev);
}
// reuse the write handler event for pending connections.
static void _proxy_evthr_evset_be_conn(mcp_backend_t *be, struct __kernel_timespec *ts) {
struct io_uring_sqe *sqe;
P_DEBUG("%s: setting\n", __func__);
if (be->ur_wr_ev.set)
return;
be->ur_wr_ev.cb = proxy_backend_beconn_ur;
be->ur_wr_ev.udata = be;
sqe = io_uring_get_sqe(&be->event_thread->ring);
// FIXME (v2): NULL?
io_uring_prep_poll_add(sqe, mcmc_fd(be->client), POLLOUT);
io_uring_sqe_set_data(sqe, &be->ur_wr_ev);
be->ur_wr_ev.set = true;
sqe->flags |= IOSQE_IO_LINK;
// add a timeout.
// FIXME: do I need to change this at all?
be->ur_te_ev.cb = proxy_backend_timeout_handler_ur;
be->ur_te_ev.udata = be;
sqe = io_uring_get_sqe(&be->event_thread->ring);
io_uring_prep_link_timeout(sqe, ts, 0);
io_uring_sqe_set_data(sqe, &be->ur_te_ev);
}
// reusing the ur_wr_ev.
static void _proxy_evthr_evset_be_writev(mcp_backend_t *be, int iovcnt, struct __kernel_timespec *ts) {
struct io_uring_sqe *sqe;
if (be->ur_wr_ev.set)
return;
be->ur_wr_ev.cb = proxy_backend_postwrite_ur;
be->ur_wr_ev.udata = be;
sqe = io_uring_get_sqe(&be->event_thread->ring);
// FIXME (v2): NULL?
if (iovcnt == 1) {
io_uring_prep_write(sqe, mcmc_fd(be->client), be->write_iovs[0].iov_base, be->write_iovs[0].iov_len, 0);
} else {
io_uring_prep_writev(sqe, mcmc_fd(be->client), be->write_iovs, iovcnt, 0);
}
io_uring_sqe_set_data(sqe, &be->ur_wr_ev);
be->ur_wr_ev.set = true;
sqe->flags |= IOSQE_IO_LINK;
// add a timeout.
be->ur_te_ev.cb = proxy_backend_timeout_handler_ur;
be->ur_te_ev.udata = be;
sqe = io_uring_get_sqe(&be->event_thread->ring);
io_uring_prep_link_timeout(sqe, ts, 0);
io_uring_sqe_set_data(sqe, &be->ur_te_ev);
}
static void _proxy_evthr_evset_be_wrpoll(mcp_backend_t *be, struct __kernel_timespec *ts) {
struct io_uring_sqe *sqe;
if (be->ur_wr_ev.set)
return;
be->ur_wr_ev.cb = proxy_backend_wrhandler_ur;
be->ur_wr_ev.udata = be;
sqe = io_uring_get_sqe(&be->event_thread->ring);
// FIXME (v2): NULL?
io_uring_prep_poll_add(sqe, mcmc_fd(be->client), POLLOUT);
io_uring_sqe_set_data(sqe, &be->ur_wr_ev);
be->ur_wr_ev.set = true;
sqe->flags |= IOSQE_IO_LINK;
// add a timeout.
be->ur_te_ev.cb = proxy_backend_timeout_handler_ur;
be->ur_te_ev.udata = be;
sqe = io_uring_get_sqe(&be->event_thread->ring);
io_uring_prep_link_timeout(sqe, ts, 0);
io_uring_sqe_set_data(sqe, &be->ur_te_ev);
}
static void _proxy_evthr_evset_be_read(mcp_backend_t *be, char *buf, size_t len, struct __kernel_timespec *ts) {
P_DEBUG("%s: setting: %lu\n", __func__, len);
struct io_uring_sqe *sqe;
if (be->ur_rd_ev.set) {
P_DEBUG("%s: already set\n", __func__);
return;
}
be->ur_rd_ev.cb = proxy_backend_handler_ur;
be->ur_rd_ev.udata = be;
sqe = io_uring_get_sqe(&be->event_thread->ring);
// FIXME (v2): NULL?
assert(be->rbuf != NULL);
io_uring_prep_recv(sqe, mcmc_fd(be->client), buf, len, 0);
io_uring_sqe_set_data(sqe, &be->ur_rd_ev);
be->ur_rd_ev.set = true;
sqe->flags |= IOSQE_IO_LINK;
// add a timeout.
// TODO (v2): we can pre-set the event data and avoid always re-doing it here.
be->ur_te_ev.cb = proxy_backend_timeout_handler_ur;
be->ur_te_ev.udata = be;
sqe = io_uring_get_sqe(&be->event_thread->ring);
io_uring_prep_link_timeout(sqe, ts, 0);
io_uring_sqe_set_data(sqe, &be->ur_te_ev);
}
// FIXME: can this be inside the function?
//static eventfd_t dummy_event = 1;
// TODO: in newer versions of uring we can set ignore success?
/*static void _proxy_evthr_evset_wnotify(proxy_event_thread_t *t, int notify_fd) {
struct io_uring_sqe *sqe;
sqe = io_uring_get_sqe(&t->ring);
// FIXME (v2) NULL?
io_uring_prep_write(sqe, notify_fd, &dummy_event, sizeof(dummy_event), 0);
io_uring_sqe_set_data(sqe, NULL);
}*/
static void _proxy_evthr_evset_clock(proxy_event_thread_t *t) {
struct io_uring_sqe *sqe;
sqe = io_uring_get_sqe(&t->ring);
// FIXME (v2): NULL?
io_uring_prep_timeout(sqe, &updater_ts, 0, 0);
io_uring_sqe_set_data(sqe, &t->ur_clock_event);
t->ur_clock_event.set = true;
}
static void _proxy_evthr_evset_benotifier(proxy_event_thread_t *t) {
struct io_uring_sqe *sqe;
P_DEBUG("%s: setting: %d\n", __func__, t->ur_benotify_event.set);
if (t->ur_benotify_event.set)
return;
t->ur_benotify_event.cb = proxy_beconn_handler_ur;
t->ur_benotify_event.udata = t;
sqe = io_uring_get_sqe(&t->ring);
// FIXME (v2): NULL?
io_uring_prep_read(sqe, t->be_event_fd, &t->beevent_counter, sizeof(eventfd_t), 0);
io_uring_sqe_set_data(sqe, &t->ur_benotify_event);
}
static void _proxy_evthr_evset_notifier(proxy_event_thread_t *t) {
struct io_uring_sqe *sqe;
P_DEBUG("%s: setting: %d\n", __func__, t->ur_notify_event.set);
if (t->ur_notify_event.set)
return;
t->ur_notify_event.cb = proxy_event_handler_ur;
t->ur_notify_event.udata = t;
sqe = io_uring_get_sqe(&t->ring);
// FIXME (v2): NULL?
io_uring_prep_read(sqe, t->event_fd, &t->event_counter, sizeof(eventfd_t), 0);
io_uring_sqe_set_data(sqe, &t->ur_notify_event);
}
// TODO (v2): IOURING_FEAT_NODROP: uring_submit() should return -EBUSY if out of CQ
// events slots. Therefore might starve SQE's if we were low beforehand.
// - when uring events are armed, they should link into an STAILQ
// - after all cqe's are processed from the loop, walk the queued events
// - generate SQE's as necessary, bailing if we run out before running out of
// events.
// - submit the SQE's
// - if it bails on -EBUSY due to too many CQE's, run the CQE loop again
// - submit if there were pending SQE's before resuming walking the event
// chain.
//
// Think this is the best compromise; doesn't use temporary memory for
// processing CQE's, and we already have dedicated memory for the SQE side of
// things so adding a little more for an STAILQ is fine.
// Until then this code will deadlock and die if -EBUSY happens.
void *proxy_event_thread_ur(void *arg) {
proxy_event_thread_t *t = arg;
struct io_uring_cqe *cqe;
P_DEBUG("%s: starting\n", __func__);
logger_create(); // TODO (v2): add logger to struct
while (1) {
P_DEBUG("%s: submit and wait\n", __func__);
io_uring_submit_and_wait(&t->ring, 1);
//P_DEBUG("%s: sqe submitted: %d\n", __func__, ret);
uint32_t head = 0;
uint32_t count = 0;
io_uring_for_each_cqe(&t->ring, head, cqe) {
P_DEBUG("%s: got a CQE [count:%d]\n", __func__, count);
proxy_event_t *pe = io_uring_cqe_get_data(cqe);
if (pe != NULL) {
pe->set = false;
pe->cb(pe->udata, cqe);
}
count++;
}
P_DEBUG("%s: advancing [count:%d]\n", __func__, count);
io_uring_cq_advance(&t->ring, count);
}
return NULL;
}
#endif // HAVE_LIBURING
// We need to get timeout/retry/etc updates to the event thread(s)
// occasionally. I'd like to have a better inteface around this where updates
// are shipped directly; but this is good enough to start with.
static void proxy_event_updater(evutil_socket_t fd, short which, void *arg) {
proxy_event_thread_t *t = arg;
proxy_ctx_t *ctx = t->ctx;
// TODO (v2): double check how much of this boilerplate is still necessary?
// reschedule the clock event.
evtimer_del(&t->clock_event);
evtimer_set(&t->clock_event, proxy_event_updater, t);
event_base_set(t->base, &t->clock_event);
struct timeval rate = {.tv_sec = 3, .tv_usec = 0};
evtimer_add(&t->clock_event, &rate);
// we reuse the "global stats" lock since it's hardly ever used.
STAT_L(ctx);
memcpy(&t->tunables, &ctx->tunables, sizeof(t->tunables));
STAT_UL(ctx);
}
static void _cleanup_backend(mcp_backend_t *be) {
#ifdef HAVE_LIBURING
if (be->event_thread->use_uring) {
// TODO: cancel any live uring events.
} else {
#endif
// remove any pending events.
int pending = 0;
if (event_initialized(&be->event)) {
pending = event_pending(&be->event, EV_READ|EV_WRITE|EV_TIMEOUT, NULL);
}
if ((pending & (EV_READ|EV_WRITE|EV_TIMEOUT)) != 0) {
event_del(&be->event); // an error to call event_del() without event.
}
#ifdef HAVE_LIBURING
}
#endif
// - assert on empty queue
assert(STAILQ_EMPTY(&be->io_head));
mcmc_disconnect(be->client);
// - free be->client
free(be->client);
// - free be->rbuf
free(be->rbuf);
// - free *be
free(be);
}
// event handler for injecting backends for processing
// currently just for initiating connections the first time.
static void proxy_event_beconn(evutil_socket_t fd, short which, void *arg) {
proxy_event_thread_t *t = arg;
#ifdef USE_EVENTFD
uint64_t u;
if (read(fd, &u, sizeof(uint64_t)) != sizeof(uint64_t)) {
// Temporary error or wasn't actually ready to read somehow.
return;
}
#else
char buf[1];
if (read(fd, buf, 1) != 1) {
P_DEBUG("%s: pipe read failed\n", __func__);
return;
}
#endif
beconn_head_t head;
struct timeval tmp_time = t->tunables.connect;
STAILQ_INIT(&head);
pthread_mutex_lock(&t->mutex);
STAILQ_CONCAT(&head, &t->beconn_head_in);
pthread_mutex_unlock(&t->mutex);
// Think we should reuse this code path for manually instructing backends
// to disable/etc but not coding for that generically. We just need to
// check the state of the backend when it reaches here or some flags at
// least.
// FIXME: another ->stacked flag?
// Either that or remove the STAILQ code and just using an array of
// ptr's.
mcp_backend_t *be = NULL;
// be can be freed by the loop, so can't use STAILQ_FOREACH.
while (!STAILQ_EMPTY(&head)) {
be = STAILQ_FIRST(&head);
STAILQ_REMOVE_HEAD(&head, beconn_next);
if (be->transferred) {
// If this object was already transferred here, we're being
// signalled to clean it up and free.
_cleanup_backend(be);
} else {
be->transferred = true;
be->event_thread = t;
int status = mcmc_connect(be->client, be->name, be->port, be->connect_flags);
if (status == MCMC_CONNECTING || status == MCMC_CONNECTED) {
// if we're already connected for some reason, still push it
// through the connection handler to keep the code unified. It
// will auto-wake because the socket is writeable.
be->connecting = true;
be->can_write = false;
_set_event(be, t->base, EV_WRITE|EV_TIMEOUT, tmp_time, proxy_beconn_handler);
} else {
_reset_bad_backend(be, P_BE_FAIL_CONNECTING);
_backend_failed(be);
}
}
}
}
// event handler for executing backend requests
static void proxy_event_handler(evutil_socket_t fd, short which, void *arg) {
proxy_event_thread_t *t = arg;
#ifdef USE_EVENTFD
uint64_t u;
if (read(fd, &u, sizeof(uint64_t)) != sizeof(uint64_t)) {
// Temporary error or wasn't actually ready to read somehow.
return;
}
#else
char buf[1];
// TODO (v2): This is a lot more fatal than it should be. can it fail? can
// it blow up the server?
// TODO (v2): a cross-platform method of speeding this up would be nice. With
// event fds we can queue N events and wakeup once here.
// If we're pulling one byte out of the pipe at a time here it'll just
// wake us up too often.
// If the pipe is O_NONBLOCK then maybe just a larger read would work?
if (read(fd, buf, 1) != 1) {
P_DEBUG("%s: pipe read failed\n", __func__);
return;
}
#endif
if (_proxy_event_handler_dequeue(t) == 0) {
//P_DEBUG("%s: no IO's to complete\n", __func__);
return;
}
// Re-walk each backend and check set event as required.
mcp_backend_t *be = NULL;
struct timeval tmp_time = t->tunables.read;
// FIXME (v2): _set_event() is buggy, see notes on function.
STAILQ_FOREACH(be, &t->be_head, be_next) {
be->stacked = false;
int flags = 0;
if (be->connecting || be->validating) {
P_DEBUG("%s: deferring IO pending connecting (%s:%s)\n", __func__, be->name, be->port);
} else {
flags = _flush_pending_write(be);
if (flags == -1) {
_reset_bad_backend(be, P_BE_FAIL_WRITING);
_backend_failed(be);
} else {
flags = be->can_write ? EV_READ|EV_TIMEOUT : EV_READ|EV_WRITE|EV_TIMEOUT;
_set_event(be, t->base, flags, tmp_time, proxy_backend_handler);
}
}
}
}
void *proxy_event_thread(void *arg) {
proxy_event_thread_t *t = arg;
logger_create(); // TODO (v2): add logger ptr to structure
event_base_loop(t->base, 0);
event_base_free(t->base);
// TODO (v2): join bt threads, free array.
return NULL;
}
// FIXME (v2): if we use the newer API the various pending checks can be adjusted.
static void _set_event(mcp_backend_t *be, struct event_base *base, int flags, struct timeval t, event_callback_fn callback) {
// FIXME (v2): chicken and egg.
// can't check if pending if the structure is was calloc'ed (sigh)
// don't want to double test here. should be able to event_assign but
// not add anything during initialization, but need the owner thread's
// event base.
int pending = 0;
if (event_initialized(&be->event)) {
pending = event_pending(&be->event, EV_READ|EV_WRITE|EV_TIMEOUT, NULL);
}
if ((pending & (EV_READ|EV_WRITE|EV_TIMEOUT)) != 0) {
event_del(&be->event); // replace existing event.
}
// if we can't write, we could be connecting.
// TODO (v2): always check for READ in case some commands were sent
// successfully? The flags could be tracked on *be and reset in the
// handler, perhaps?
event_assign(&be->event, base, mcmc_fd(be->client),
flags, callback, be);
event_add(&be->event, &t);
}
// NOTES:
// - mcp_backend_read: grab req_stack_head, do things
// read -> next, want_read -> next | read_end, etc.
// issue: want read back to read_end as necessary. special state?
// - it's fine: p->client_resp->type.
// - mcp_backend_next: advance, consume, etc.
// TODO (v2): second argument with enum for a specific error.
// - probably just for logging. for app if any of these errors shouldn't
// result in killing the request stack!
static int proxy_backend_drive_machine(mcp_backend_t *be) {
bool stop = false;
io_pending_proxy_t *p = NULL;
int flags = 0;
p = STAILQ_FIRST(&be->io_head);
if (p == NULL) {
// got a read event, but nothing was queued.
// probably means a disconnect event.
// TODO (v2): could probably confirm this by attempting to read the
// socket, getsockopt, or something else simply for logging or
// statistical purposes.
// In this case we know it's going to be a close so error.
flags = P_BE_FAIL_CLOSED;
P_DEBUG("%s: read event but nothing in IO queue\n", __func__);
return flags;
}
while (!stop) {
mcp_resp_t *r;
switch(be->state) {
case mcp_backend_read:
assert(p != NULL);
// FIXME: remove the _read state?
be->state = mcp_backend_parse;
break;
case mcp_backend_parse:
r = p->client_resp;
r->status = mcmc_parse_buf(be->client, be->rbuf, be->rbufused, &r->resp);
if (r->status == MCMC_ERR) {
P_DEBUG("%s: mcmc_read failed [%d]\n", __func__, r->status);
if (r->resp.code == MCMC_WANT_READ) {
return 0;