-
Notifications
You must be signed in to change notification settings - Fork 2
/
mcshredder.c
3267 lines (2879 loc) · 96.7 KB
/
mcshredder.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 -*- */
/*
* mc-shredder - burn-in load test client
*
* https://github.com/memcached/mcshredder
*
* Copyright 2023 Cache Forge LLC. All rights reserved.
*
* Use and distribution licensed under the BSD license. See
* the LICENSE file for full text.
*
* Authors:
* dormando <[email protected]>
*/
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <pthread.h>
#include <unistd.h>
#include <getopt.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <time.h>
#include <stdbool.h>
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
#include <sys/eventfd.h>
#include <liburing.h>
#include <poll.h> // POLLOUT for liburing.
#include "mcshredder.h"
#include "vendor/mcmc/mcmc.h"
#include "queue.h"
#include "itoa_ljust.h"
#define XXH_INLINE_ALL
#include "xxhash.h"
#define PRING_QUEUE_SQ_ENTRIES 1024
#define PRING_QUEUE_CQ_ENTRIES 4096
// min available SQE's before we run a callback.
// means this is the max number of SQE's a callback can safely fetch.
#define PRING_MIN_SQE 4
// avoiding some hacks for finding member size.
#define SOCK_MAX 100
#define BUF_INITIAL_SIZE 1<<15
#define WBUF_INITIAL_SIZE 16384
#define RBUF_INITIAL_SIZE 65536
#define KEY_MAX_LENGTH 250
#define REQ_MAX_LENGTH KEY_MAX_LENGTH * 2
#define NSEC_PER_SEC 1000000000
#define PARSER_MAX_TOKENS 24
#define PARSER_MAXLEN USHRT_MAX-1
char sock_path_default[SOCK_MAX];
// TODO: This is a global timeout just to get code started.
// Note that timeouts must be stable until the sqe is submitted, so any
// timeouts have to exist on the func structure.
struct __kernel_timespec timeout_default = { .tv_sec = 0, .tv_nsec = 500000000 };
// time to wait before attempting to reconnect after an error.
struct __kernel_timespec timeout_retry = { .tv_sec = 0, .tv_nsec = 500000000 };
struct mcs_thread;
struct mcs_func;
struct mcs_ctx;
static void register_lua_libs(lua_State *L);
static void mcs_queue_cb(void *udata, struct io_uring_cqe *cqe);
static int mcs_func_lua(struct mcs_func *f);
static int mcs_func_run(void *udata);
static void mcs_start_limiter(struct mcs_func *f);
static void _mcs_cleanup_thread(struct mcs_thread *t);
static bool mcs_postread(struct mcs_func *f, struct mcs_func_client *c);
typedef void (*event_cb)(void *udata, struct io_uring_cqe *cqe);
struct mcs_event {
void *udata;
event_cb cb;
queue_cb qcb;
};
struct mcs_f_rate {
int rate;
uint64_t period; // stored in nanoseconds.
struct __kernel_timespec delta; // period / rate in timespec format
struct __kernel_timespec next; // next absolute time to schedule the alarm for
struct __kernel_timespec start; // post-connect start offset
};
// governs when to naturally reconnect
struct mcs_f_reconn {
unsigned int every; // how often to reconnect
unsigned int after; // counter until next reconnect
};
enum mcs_lua_yield {
mcs_luayield_write = 0,
mcs_luayield_write_factory,
mcs_luayield_flush,
mcs_luayield_disconnect,
mcs_luayield_read,
mcs_luayield_sleep,
mcs_luayield_outwait,
mcs_luayield_c_conn,
mcs_luayield_c_read,
mcs_luayield_c_readline,
mcs_luayield_c_write,
mcs_luayield_c_write_factory,
mcs_luayield_c_flush,
};
enum mcs_req_type {
mcs_req_type_flat = 0,
mcs_req_type_factory = 1,
};
// factories can have at most one outstanding request at a time if you want to
// use response matching.
// if pipelining requests, pre-make N factories.
#define FACTORY_LENGTH KEY_MAX_LENGTH + REQ_MAX_LENGTH + 2
struct mcs_func_req {
enum mcs_req_type type;
struct timespec start;
uint64_t hash;
union {
struct {
int len;
int vlen;
} flat;
struct {
int64_t numeric;
char cmd;
int prefix_len;
int postfix_len;
// prefix/postfix are in data[]
} fac;
};
char data[];
};
// points into func's rbuf
struct mcs_func_resp {
int status;
int ntokens; // zero if not tokenized
struct timespec received; // time response was read from socket
char *buf; // start of response buffer
mcmc_resp_t resp;
uint16_t tokens[PARSER_MAX_TOKENS]; // offsets for start of each token
};
struct mcs_func {
lua_State *L; // lua coroutine local to this function
int self_ref; // avoid garbage collection
int self_ref_coro; // reference for the coroutine thread
int arg_ref; // reference for function argument
int func_ref; // reference to the function to call
STAILQ_ENTRY(mcs_func) next_run; // coroutine run stack.
STAILQ_ENTRY(mcs_func) next_func; // total live list.
struct mcs_thread *parent; // pointer back to owner thread
char *fname; // name of function to call
bool linked;
bool active;
enum mcs_func_state state;
struct mcs_f_rate rate; // rate limiter
struct mcs_f_reconn reconn; // tcp reconnector
struct mcs_event ev;
struct mcs_func_client c;
struct __kernel_timespec tosleep; // need a stable location for timespecs.
int limit; // stop running after N loops
int cqe_res; // result of most recent cqe
int lua_nargs; // number of args to pass back to lua
int reserr; // probably -ERRNO via uring.
int buf_readline; // skip parsing on next line response.
};
typedef STAILQ_HEAD(func_head_s, mcs_func) func_head_t;
struct mcs_thread {
struct mcs_ctx *ctx;
lua_State *L; // lua VM local to this thread
STAILQ_ENTRY(mcs_thread) next; // thread stack
func_head_t func_runlist; // queued runlist
func_head_t func_list; // coroutine stack
struct io_uring ring;
int active_funcs; // stop if no active functions
pthread_t tid;
bool stop;
};
enum mcs_memprofile_types {
mcs_memp_free = 0,
mcs_memp_string,
mcs_memp_table,
mcs_memp_func,
mcs_memp_userdata,
mcs_memp_thread,
mcs_memp_default,
mcs_memp_realloc,
};
struct mcs_memprofile {
struct timespec last_status; // for per-second prints on status
int id;
uint64_t allocs[8];
uint64_t alloc_bytes[8];
};
typedef STAILQ_HEAD(thread_head_s, mcs_thread) thread_head_t;
struct mcs_ctx {
lua_State *L;
thread_head_t threads; // stack of threads
pthread_cond_t wait_cond; // thread completion signal
pthread_mutex_t wait_lock;
#ifdef USE_TLS
void *tls_ctx; // global SSL CTX object
#endif
struct mcs_lock_buf out_buf; // out/listener stream buffer.
eventfd_t out_fd;
uint64_t out_readvar; // let io_uring put eventfd res somewhere.
bool memprofile; // runs threads with a memory profiler.
bool out_listener; // short circuit if there's no listener.
bool stop; // some thread told us to cut out of the shredder.
int active_threads; // return from shredder() if threads stopped
int arg_ref; // commandline argument table
int thread_counter; // to give ID's for the memory profiler.
const char *conffile;
struct mcs_conn conn; // connection details.
};
// adds ts2 to ts1
static void timespec_add(struct __kernel_timespec *ts1,
struct __kernel_timespec *ts2) {
ts1->tv_sec += ts2->tv_sec;
ts1->tv_nsec += ts2->tv_nsec;
if (ts1->tv_nsec >= NSEC_PER_SEC) {
ts1->tv_sec++;
ts1->tv_nsec -= NSEC_PER_SEC;
}
}
static void *profile_alloc(void *ud, void *ptr, size_t osize,
size_t nsize) {
struct mcs_memprofile *prof = ud;
struct timespec now;
clock_gettime(CLOCK_MONOTONIC, &now);
enum mcs_memprofile_types t = mcs_memp_free;
if (ptr == NULL) {
switch (osize) {
case LUA_TSTRING:
t = mcs_memp_string;
//fprintf(stderr, "alloc string: %ld\n", nsize);
break;
case LUA_TTABLE:
t = mcs_memp_table;
//fprintf(stderr, "alloc table: %ld\n", nsize);
break;
case LUA_TFUNCTION:
t = mcs_memp_func;
//fprintf(stderr, "alloc func: %ld\n", nsize);
break;
case LUA_TUSERDATA:
t = mcs_memp_userdata;
//fprintf(stderr, "alloc userdata: %ld\n", nsize);
break;
case LUA_TTHREAD:
t = mcs_memp_thread;
//fprintf(stderr, "alloc thread: %ld\n", nsize);
break;
default:
t = mcs_memp_default;
//fprintf(stderr, "alloc osize: %ld nsize: %ld\n", osize, nsize);
}
prof->allocs[t]++;
prof->alloc_bytes[t] += nsize;
} else {
if (nsize != 0) {
prof->allocs[mcs_memp_realloc]++;
prof->alloc_bytes[mcs_memp_realloc] += nsize;
} else {
prof->allocs[mcs_memp_free]++;
prof->alloc_bytes[mcs_memp_free] += osize;
}
//fprintf(stderr, "realloc: osize: %ld nsize: %ld\n", osize, nsize);
}
if (now.tv_sec != prof->last_status.tv_sec) {
prof->last_status.tv_sec = now.tv_sec;
fprintf(stderr, "MEMPROF[%d]:\tstring[%llu][%llu] table[%llu][%llu] func[%llu][%llu] udata[%llu][%llu] thr[%llu][%llu] def[%llu][%llu] realloc[%llu][%llu] free[%llu][%llu]\n",
prof->id,
(unsigned long long)prof->allocs[1],
(unsigned long long)prof->alloc_bytes[1],
(unsigned long long)prof->allocs[2],
(unsigned long long)prof->alloc_bytes[2],
(unsigned long long)prof->allocs[3],
(unsigned long long)prof->alloc_bytes[3],
(unsigned long long)prof->allocs[4],
(unsigned long long)prof->alloc_bytes[4],
(unsigned long long)prof->allocs[5],
(unsigned long long)prof->alloc_bytes[5],
(unsigned long long)prof->allocs[6],
(unsigned long long)prof->alloc_bytes[6],
(unsigned long long)prof->allocs[7],
(unsigned long long)prof->alloc_bytes[7],
(unsigned long long)prof->allocs[0],
(unsigned long long)prof->alloc_bytes[0]);
for (int x = 0; x < 8; x++) {
prof->allocs[x] = 0;
prof->alloc_bytes[x] = 0;
}
}
if (nsize == 0) {
free(ptr);
return NULL;
} else {
return realloc(ptr, nsize);
}
}
// Common lua debug command.
__attribute__((unused)) void dump_stack(lua_State *L) {
int top = lua_gettop(L);
int i = 1;
fprintf(stderr, "--TOP OF STACK [%d]\n", top);
for (; i < top + 1; i++) {
int type = lua_type(L, i);
// lets find the metatable of this userdata to identify it.
if (lua_getmetatable(L, i) != 0) {
lua_pushstring(L, "__name");
if (lua_rawget(L, -2) != LUA_TNIL) {
fprintf(stderr, "--|%d| [%s] (%s)\n", i, lua_typename(L, type), lua_tostring(L, -1));
lua_pop(L, 2);
continue;
}
lua_pop(L, 2);
}
if (type == LUA_TSTRING) {
fprintf(stderr, "--|%d| [%s] | %s\n", i, lua_typename(L, type), lua_tostring(L, i));
} else {
fprintf(stderr, "--|%d| [%s]\n", i, lua_typename(L, type));
}
}
fprintf(stderr, "-----------------\n");
}
// *** IO_URING ***
static void init_thread_uring(struct mcs_thread *t) {
struct io_uring_params p = {0};
p.flags = IORING_SETUP_CQSIZE;
p.cq_entries = PRING_QUEUE_CQ_ENTRIES;
int ret = io_uring_queue_init_params(PRING_QUEUE_SQ_ENTRIES, &t->ring, &p);
if (ret) {
perror("io_uring_queue_init_params");
exit(1);
}
if (!(p.features & IORING_FEAT_NODROP)) {
fprintf(stderr, "uring: kernel missing IORING_FEAT_NODROP\n");
exit(EXIT_FAILURE);
}
if (!(p.features & IORING_FEAT_SINGLE_MMAP)) {
fprintf(stderr, "uring: kernel missing IORING_FEAT_SINGLE_MMAP\n");
exit(EXIT_FAILURE);
}
if (!(p.features & IORING_FEAT_FAST_POLL)) {
fprintf(stderr, "uring: kernel missing IORING_FEAT_FAST_POLL\n");
exit(EXIT_FAILURE);
}
}
// NOTE: Don't believe we need handlers on timeouts, as the linked SQE will
// return with an abort failure.
// TODO: timeout override.
static void _evset_link_timeout(struct mcs_func *f) {
struct io_uring_sqe *sqe;
sqe = io_uring_get_sqe(&f->parent->ring);
io_uring_prep_link_timeout(sqe, &timeout_default, 0);
io_uring_sqe_set_data(sqe, NULL);
}
static void _evset_abs_timeout(struct mcs_func *f) {
struct io_uring_sqe *sqe;
sqe = io_uring_get_sqe(&f->parent->ring);
io_uring_prep_timeout(sqe, &f->rate.next, 0, IORING_TIMEOUT_ABS);
io_uring_sqe_set_data(sqe, &f->ev);
}
static void _evset_retry_timeout(struct mcs_func *f) {
struct io_uring_sqe *sqe;
sqe = io_uring_get_sqe(&f->parent->ring);
io_uring_prep_timeout(sqe, &timeout_retry, 0, 0);
io_uring_sqe_set_data(sqe, &f->ev);
}
static void _evset_sleep(struct mcs_func *f) {
struct io_uring_sqe *sqe;
sqe = io_uring_get_sqe(&f->parent->ring);
io_uring_prep_timeout(sqe, &f->tosleep, 0, 0);
io_uring_sqe_set_data(sqe, &f->ev);
}
static void _evset_wrpoll(struct mcs_func *f, struct mcs_func_client *c) {
struct io_uring_sqe *sqe;
sqe = io_uring_get_sqe(&f->parent->ring);
io_uring_prep_poll_add(sqe, mcmc_fd(c->mcmc), POLLOUT);
io_uring_sqe_set_data(sqe, &f->ev);
sqe->flags |= IOSQE_IO_LINK;
_evset_link_timeout(f);
}
static void _evset_nop(struct mcs_func *f) {
struct io_uring_sqe *sqe;
sqe = io_uring_get_sqe(&f->parent->ring);
io_uring_prep_nop(sqe);
io_uring_sqe_set_data(sqe, &f->ev);
}
static void _evset_wrflush(struct mcs_func *f, struct mcs_func_client *c) {
struct io_uring_sqe *sqe;
sqe = io_uring_get_sqe(&f->parent->ring);
io_uring_prep_write(sqe, mcmc_fd(c->mcmc), c->wb.data + c->wb.offset, c->wb.used - c->wb.offset, 0);
io_uring_sqe_set_data(sqe, &f->ev);
_evset_link_timeout(f);
}
void _evset_wrflush_data(struct mcs_func *f, struct mcs_func_client *c, char *data, long len) {
struct io_uring_sqe *sqe;
sqe = io_uring_get_sqe(&f->parent->ring);
io_uring_prep_write(sqe, mcmc_fd(c->mcmc), data, len, 0);
io_uring_sqe_set_data(sqe, &f->ev);
_evset_link_timeout(f);
}
void _evset_read_data(struct mcs_func *f, struct mcs_func_client *c, char *data, long len) {
struct io_uring_sqe *sqe = io_uring_get_sqe(&f->parent->ring);
io_uring_prep_recv(sqe, mcmc_fd(c->mcmc), data, len, 0);
io_uring_sqe_set_data(sqe, &f->ev);
_evset_link_timeout(f);
}
static void _evset_read(struct mcs_func *f, struct mcs_func_client *c) {
struct io_uring_sqe *sqe;
sqe = io_uring_get_sqe(&f->parent->ring);
io_uring_prep_recv(sqe, mcmc_fd(c->mcmc), c->rb.data + c->rb.used, c->rb.size - c->rb.used, 0);
io_uring_sqe_set_data(sqe, &f->ev);
_evset_link_timeout(f);
}
static void _evset_read_eventfd(struct mcs_func *f) {
struct io_uring_sqe *sqe;
struct mcs_ctx *ctx = f->parent->ctx;
sqe = io_uring_get_sqe(&f->parent->ring);
io_uring_prep_read(sqe, ctx->out_fd, &ctx->out_readvar, sizeof(uint64_t), 0);
io_uring_sqe_set_data(sqe, &f->ev);
// no timeout; block forever.
}
static void _evset_cancel(struct mcs_func *f) {
struct io_uring_sqe *sqe;
sqe = io_uring_get_sqe(&f->parent->ring);
io_uring_prep_cancel(sqe, &f->ev, 0);
io_uring_sqe_set_data(sqe, &f->ev);
}
// *** CORE ***
int mcs_func_cqe_res(struct mcs_func *f) {
return f->cqe_res;
}
void mcs_func_set_cqe_res(struct mcs_func *f, int res) {
f->cqe_res = res;
}
struct mcs_func_client *mcs_func_get_client(struct mcs_func *f) {
struct mcs_func_client *c = NULL;
if (f->c.mcmc) {
return c = &f->c;
} else {
// FIXME: gross. This requires the caller to assume that if it wants a
// client, one is currently sitting in the stack.
// Which should be generally true: however fixing the callback system
// so we can also override the callback data will remove the need for
// this function.
c = lua_touserdata(f->L, 1);
}
return c;
}
// TODO: ifdef a STATE_DEBUG with a print.
void mcs_func_set_state(struct mcs_func *f, enum mcs_func_state s) {
f->state = s;
}
static void mcs_client_init(struct mcs_func_client *c) {
c->s_read = mcs_fstate_read;
c->s_flush = mcs_fstate_flush;
}
static int mcs_lock_buf_used(struct mcs_lock_buf *b) {
int used = 0;
pthread_mutex_lock(&b->lock);
used = b->buf.used;
pthread_mutex_unlock(&b->lock);
return used;
}
void mcs_buf_init(struct mcs_buf *b, size_t size) {
memset(b, 0, sizeof(*b));
b->data = malloc(size);
b->size = size;
}
// For this codebase these buffers tend to settle into a certain size,
// and we don't shrink them. Increasing by chunks of the original size should
// help avoid memory bloat.
static void mcs_check_buf(struct mcs_buf *b, size_t len) {
if (b->used + len <= b->size) {
return;
}
while (b->used + len > b->size) {
// FIXME: remember and increase by a multiple of the initial size?
b->size += BUF_INITIAL_SIZE;
}
char *nb = realloc(b->data, b->size);
if (nb == NULL) {
fprintf(stderr, "Failed to realloc buffer buffer\n");
abort();
}
b->data = nb;
}
static void mcs_reset_buf(struct mcs_buf *b) {
char *data = b->data;
size_t size = b->size;
memset(b, 0, sizeof(struct mcs_buf));
b->size = size;
b->data = data;
}
static void mcs_consume_buf(struct mcs_buf *b) {
if (b->toconsume != 0) {
b->used -= b->toconsume;
if (b->used > 0) {
memmove(b->data, b->data+b->toconsume, b->used);
}
b->toconsume = 0;
}
}
// The connect routine isn't very "io_uring-y", as it calls
// socket()/connect() from here, but considering we're calling connect in
// nonblock mode I'm not sure if there's any real difference in pushing it
// over uring.
static int mcs_connect(struct mcs_func_client *c) {
int status = mcmc_connect(c->mcmc, c->conn.host, c->conn.port_num, MCMC_OPTION_NONBLOCK);
mcs_reset_buf(&c->wb);
mcs_reset_buf(&c->rb);
if (status == MCMC_CONNECTED) {
// NOTE: find when this is possible?
fprintf(stderr, "Client connected unexpectedly, please report this\n");
abort();
} else if (status == MCMC_CONNECTING) {
// need to wait for a writeable event.
return 0;
} else {
// FIXME: use real error flow once it exists
fprintf(stderr, "failed to connect: %s:%s\n", c->conn.host, c->conn.port_num);
return -1;
}
return 0;
}
void mcs_postflush(struct mcs_func *f, struct mcs_func_client *c) {
int res = f->cqe_res;
struct mcs_buf *b = &c->wb;
if (res > 0) {
b->offset += res;
if (b->offset < b->used) {
// need to continue flushing write buffer.
f->state = c->s_flush;
} else {
b->offset = 0;
b->used = 0;
f->state = mcs_fstate_run;
}
} else if (res < 0) {
if (res == -EAGAIN || res == -EWOULDBLOCK) {
// TODO: -> wrpoll -> flush
// is this even possible with uring?
fprintf(stderr, "Unexpectedly could not write to socket: please report this: %d\n", res);
abort();
} else {
f->reserr = res;
f->state = mcs_fstate_syserr;
}
} else if (res == 0) {
// disconnected, but probably gracefully
f->reserr = 0;
f->state = mcs_fstate_syserr;
}
}
// Note: this function throws away the response object if it needs to read
// more data from the socket, re-parsing after another read attempt.
// This should be an extremely rare case, and parsing is fast enough that I
// don't want to add more logic around this right now.
static int mcs_read_buf(struct mcs_func *f, struct mcs_func_client *c) {
int ret = 0; // RUN
struct mcs_buf *b = &c->rb;
char *rbuf_offset = b->data + b->toconsume;
int rbuf_remain = b->used - b->toconsume;
if (f->buf_readline == 0) {
struct mcs_func_resp *r = lua_touserdata(f->L, -1);
memset(r, 0, sizeof(*r));
r->status = mcmc_parse_buf(rbuf_offset, rbuf_remain, &r->resp);
if (r->status == MCMC_OK) {
if (r->resp.vlen != r->resp.vlen_read) {
if (b->toconsume != 0) {
// vlen didn't fit, but we are read partway into the
// buffer.
// memmove the buffer and read out.
mcs_consume_buf(&c->rb);
} else {
// ... else the read buffer simply wasn't large enough.
mcs_check_buf(&c->rb, RBUF_INITIAL_SIZE);
}
ret = 1; // WANT_READ
} else {
r->buf = rbuf_offset;
f->lua_nargs = 0;
b->toconsume += r->resp.reslen + r->resp.vlen_read;
clock_gettime(CLOCK_MONOTONIC, &r->received);
}
} else if (r->resp.code == MCMC_WANT_READ) {
mcs_check_buf(&c->rb, RBUF_INITIAL_SIZE);
ret = 1;
} else {
switch (r->resp.type) {
case MCMC_RESP_ERRMSG:
if (r->resp.code != MCMC_CODE_SERVER_ERROR) {
fprintf(stderr, "Protocol error, reconnecting: %.*s\n", rbuf_remain, rbuf_offset);
ret = -1;
} else {
// SERVER_ERROR can be handled upstream
r->buf = rbuf_offset;
f->lua_nargs = 0;
b->toconsume += r->resp.reslen;
clock_gettime(CLOCK_MONOTONIC, &r->received);
}
break;
case MCMC_RESP_FAIL:
fprintf(stderr, "Read failed, reconnecting: %.*s\n", rbuf_remain, rbuf_offset);
ret = -1;
break;
default:
fprintf(stderr, "Read found garbage, reconnecting: %.*s\n", rbuf_remain, rbuf_offset);
ret = -1;
}
}
} else {
// looking for a nonstandard or expanded protocol response line.
char *end = memchr(rbuf_offset, '\n', rbuf_remain);
if (end != NULL) {
f->buf_readline = 0;
// FIXME: making an assumption the minimum read buffer size is
// always big enough for one line. Could probably add the
// detection code anyway once I'm sure this works?
size_t len = end - rbuf_offset + 1;
b->toconsume += len;
if (len < 2) {
fprintf(stderr, "Protocol error, short response: %d\n", (int)len);
ret = -1;
} else {
if (*(end-1) == '\r') {
len -= 2;
} else {
len--;
}
lua_pushlstring(f->L, rbuf_offset, len);
f->lua_nargs = 1;
}
} else {
// in case we were reading off the end of the data buffer.
mcs_consume_buf(&c->rb);
ret = 1; // WANT_READ
}
}
return ret;
}
static bool mcs_postread(struct mcs_func *f, struct mcs_func_client *c) {
int res = f->cqe_res;
if (res > 0) {
c->rb.used += res;
int ret = mcs_read_buf(f, c);
if (ret == 0) {
f->state = mcs_fstate_run;
} else if (ret == 1) {
f->state = c->s_read;
} else if (ret < 0) {
f->reserr = ret;
f->state = mcs_fstate_syserr;
}
} else if (res < 0) {
if (res == -EAGAIN || res == -EWOULDBLOCK) {
// TODO: I think we should never get here, as uring is supposed to
// only wake us up with data filled.
fprintf(stderr, "Unexpectedly could not read from socket, please report this\n");
abort();
} else {
f->reserr = res;
f->state = mcs_fstate_syserr;
}
} else if (res == 0) {
// disconnected, but probably gracefully
f->reserr = 0;
f->state = mcs_fstate_syserr;
}
return true; // nonsense from the state machine.
}
static void mcs_reschedule(struct mcs_func *f) {
if (f->rate.rate != 0) {
_evset_abs_timeout(f);
// schedule the next wakeup time.
timespec_add(&f->rate.next, &f->rate.delta);
} else {
_evset_nop(f);
}
}
static void mcs_syserror(struct mcs_func *f) {
mcmc_disconnect(f->c.mcmc);
f->c.connected = false;
if (f->reserr == 0) {
fprintf(stderr, "%s: conn gracefully disconnected\n", f->fname);
} else {
// TODO: strerror
fprintf(stderr, "%s: system error, reconnecting: %d\n", f->fname, f->reserr);
}
// we need to reset the coroutine.
int res = lua_resetthread(f->L);
if (res != LUA_OK) {
// TODO: read lua code to find potential errors.
fprintf(stderr, "Lua thread failed to reset, aborting\n");
abort();
}
f->state = mcs_fstate_retry;
}
static void mcs_restart(struct mcs_func *f) {
f->state = mcs_fstate_run;
if (f->limit != 0) {
f->limit--;
if (f->limit == 0) {
mcmc_disconnect(f->c.mcmc);
f->state = mcs_fstate_stop;
return;
}
}
if (f->reconn.every != 0) {
f->reconn.after--;
if (f->reconn.after == 0) {
mcmc_disconnect(f->c.mcmc);
f->c.connected = false;
f->reconn.after = f->reconn.every;
f->state = mcs_fstate_disconn;
return;
}
}
if (f->parent->stop) {
mcmc_disconnect(f->c.mcmc);
f->c.connected = false;
f->state = mcs_fstate_stop;
return;
}
}
// run the function state machine.
// called _outside_ of the cqe reception loop
// must return -1 if we tried to allocate an SQE for some reason and couldn't.
static int mcs_func_run(void *udata) {
struct mcs_func *f = udata;
bool stop = false;
int err = 0;
while (!stop) {
switch (f->state) {
case mcs_fstate_disconn:
if (mcs_connect(&f->c) == 0) {
_evset_wrpoll(f, &f->c);
f->state = mcs_fstate_connecting;
stop = true;
} else {
mcmc_disconnect(f->c.mcmc);
f->c.connected = false;
f->state = mcs_fstate_retry;
}
break;
case mcs_fstate_connecting:
if (mcmc_check_nonblock_connect(f->c.mcmc, &err) != MCMC_OK) {
mcmc_disconnect(f->c.mcmc);
f->c.connected = false;
f->state = mcs_fstate_retry;
} else {
if (f->c.tls) {
stop = mcs_tls_postconnect(f, &f->c);
} else {
f->state = mcs_fstate_postconnect;
}
}
break;
case mcs_fstate_tls_hs_postread:
stop = mcs_tls_hs_postread(f);
break;
case mcs_fstate_tls_hs_postwrite:
stop = mcs_tls_hs_postwrite(f);
break;
case mcs_fstate_postconnect:
f->c.connected = true;
mcs_start_limiter(f);
f->state = mcs_fstate_rerun;
break;
case mcs_fstate_run:
if (mcs_func_lua(f)) {
f->state = mcs_fstate_rerun;
}
break;
case mcs_fstate_restart:
mcs_restart(f);
break;
case mcs_fstate_rerun:
mcs_reschedule(f);
f->state = mcs_fstate_restart;
stop = true;
break;
case mcs_fstate_flush:
_evset_wrflush(f, &f->c);
f->state = mcs_fstate_postflush;
stop = true;
break;
case mcs_fstate_postflush:
mcs_postflush(f, &f->c);
break;
case mcs_fstate_read:
_evset_read(f, &f->c);
mcs_func_set_state(f, mcs_fstate_postread);
stop = true;
break;
case mcs_fstate_postread:
mcs_postread(f, &f->c);
break;
case mcs_fstate_tls_read:
stop = mcs_tls_read(f, &f->c);
break;
case mcs_fstate_tls_postread:
stop = mcs_tls_postread(f, &f->c);
break;
case mcs_fstate_tls_flush:
stop = mcs_tls_flush(f, &f->c);
break;
case mcs_fstate_tls_postflush:
stop = mcs_tls_postflush(f, &f->c);
break;
case mcs_fstate_retry:
_evset_retry_timeout(f);
f->state = mcs_fstate_postretry;
stop = true;
break;
case mcs_fstate_postretry:
// FIXME: go directly to disconn from retry?
f->state = mcs_fstate_disconn;
break;
case mcs_fstate_syserr:
mcs_syserror(f);
break;
case mcs_fstate_sleep:
_evset_sleep(f);
f->state = mcs_fstate_run;
stop = true;
break;
case mcs_fstate_stop:
f->parent->active_funcs--;
f->active = false;
stop = true;
break;
default:
fprintf(stderr, "Unhandled function state, aborting\n");
abort();
}
}
return 0;
}
static int mcs_cfunc_run(void *udata) {
struct mcs_func *f = udata;
struct mcs_func_client *c = NULL;
bool stop = false;
int err = 0;
while (!stop) {
switch (f->state) {
case mcs_fstate_connecting:
c = lua_touserdata(f->L, 1);
if (mcmc_check_nonblock_connect(c->mcmc, &err) != MCMC_OK) {
mcmc_disconnect(c->mcmc);
c->connected = false;
lua_pushboolean(f->L, 0);
f->lua_nargs = 1;
} else {
if (c->tls) {
stop = mcs_tls_postconnect(f, c);
} else {
f->state = mcs_fstate_postconnect;
}
}
break;
case mcs_fstate_tls_hs_postread:
stop = mcs_tls_hs_postread(f);
break;
case mcs_fstate_tls_hs_postwrite:
stop = mcs_tls_hs_postwrite(f);
break;
case mcs_fstate_postconnect:
c = lua_touserdata(f->L, 1);
c->connected = true;
lua_pushboolean(f->L, 1);
f->lua_nargs = 1;
f->state = mcs_fstate_run;
break;
case mcs_fstate_read:
c = lua_touserdata(f->L, 1);
if (!c->connected) {
lua_pushnil(f->L);
// FIXME: get a real error in here.
lua_pushinteger(f->L, -1);
f->lua_nargs = 2;
f->state = mcs_fstate_run;
} else {
_evset_read(f, c);
f->state = mcs_fstate_postread;
stop = true;
}
break;
case mcs_fstate_postread:
c = lua_touserdata(f->L, 1);
mcs_postread(f, c);
break;
case mcs_fstate_flush:
c = lua_touserdata(f->L, 1);
if (!c->connected) {
lua_pushboolean(f->L, 0);
lua_pushinteger(f->L, 0);