forked from memcached/mcshredder
/
mcshredder.c
2634 lines (2307 loc) · 75.5 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 <dormando@rydia.net>
*/
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <ctype.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 <lua.h>
#include <lualib.h>
#include <lauxlib.h>
#include <liburing.h>
#include <poll.h> // POLLOUT for liburing.
#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
// avoiding some hacks for finding member size.
#define SOCK_MAX 100
#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 void mcs_start_limiter(struct mcs_func *f);
typedef void (*event_cb)(void *udata, struct io_uring_cqe *cqe);
// return -1 if failure to get sqe
typedef int (*queue_cb)(void *udata);
struct mcs_event {
void *udata;
event_cb cb;
queue_cb qcb;
};
struct mcs_conn {
// host info
char host[NI_MAXHOST];
char port_num[NI_MAXSERV];
// event detail
int fd;
};
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
};
// TODO: func or macro for state changes so can be printed.
enum mcs_func_state {
mcs_fstate_disconn = 0,
mcs_fstate_connecting,
mcs_fstate_postconnect,
mcs_fstate_retry,
mcs_fstate_postretry,
mcs_fstate_run,
mcs_fstate_flush,
mcs_fstate_postflush,
mcs_fstate_read,
mcs_fstate_postread,
mcs_fstate_rerun,
mcs_fstate_restart,
mcs_fstate_syserr,
mcs_fstate_sleep,
mcs_fstate_stop,
};
enum mcs_lua_yield {
mcs_luayield_write = 0,
mcs_luayield_flush,
mcs_luayield_read,
mcs_luayield_sleep,
mcs_luayield_c_conn,
mcs_luayield_c_read,
mcs_luayield_c_readline,
mcs_luayield_c_write,
mcs_luayield_c_flush,
};
struct mcs_func_req {
struct timespec start;
int len;
int vlen;
uint64_t hash; // hash of the key, used to match the value.
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
};
// client object for custom funcs
struct mcs_func_client {
struct mcs_conn conn;
void *mcmc; // mcmc client object
char *wbuf;
size_t wbuf_size; // total size of buffer
int wbuf_used;
int wbuf_sent;
char *rbuf;
size_t rbuf_size;
int rbuf_used;
int rbuf_toconsume; // how far to skip rbuf on next read.
bool connected;
};
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
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
int active_funcs; // stop if no active functions
struct io_uring ring;
pthread_t tid;
bool stop;
};
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;
int active_threads; // return from shredder() if threads stopped
int arg_ref; // commandline argument table
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;
}
}
// 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 int _evset_link_timeout(struct mcs_func *f) {
struct io_uring_sqe *sqe;
sqe = io_uring_get_sqe(&f->parent->ring);
if (sqe == NULL) {
return -1;
}
io_uring_prep_link_timeout(sqe, &timeout_default, 0);
io_uring_sqe_set_data(sqe, NULL);
return 0;
}
static int _evset_abs_timeout(struct mcs_func *f) {
struct io_uring_sqe *sqe;
sqe = io_uring_get_sqe(&f->parent->ring);
if (sqe == NULL) {
return -1;
}
io_uring_prep_timeout(sqe, &f->rate.next, 0, IORING_TIMEOUT_ABS);
io_uring_sqe_set_data(sqe, &f->ev);
return 0;
}
static int _evset_retry_timeout(struct mcs_func *f) {
struct io_uring_sqe *sqe;
sqe = io_uring_get_sqe(&f->parent->ring);
if (sqe == NULL) {
return -1;
}
io_uring_prep_timeout(sqe, &timeout_retry, 0, 0);
io_uring_sqe_set_data(sqe, &f->ev);
return 0;
}
static int _evset_sleep(struct mcs_func *f) {
struct io_uring_sqe *sqe;
sqe = io_uring_get_sqe(&f->parent->ring);
if (sqe == NULL) {
return -1;
}
io_uring_prep_timeout(sqe, &f->tosleep, 0, 0);
io_uring_sqe_set_data(sqe, &f->ev);
return 0;
}
static int _evset_wrpoll(struct mcs_func *f, struct mcs_func_client *c) {
struct io_uring_sqe *sqe;
sqe = io_uring_get_sqe(&f->parent->ring);
if (sqe == NULL) {
return -1;
}
io_uring_prep_poll_add(sqe, mcmc_fd(c->mcmc), POLLOUT);
io_uring_sqe_set_data(sqe, &f->ev);
sqe->flags |= IOSQE_IO_LINK;
// couldn't link our timeout, need to give up on this sqe.
// should be an extremely rare event.
if (_evset_link_timeout(f) != 0) {
io_uring_prep_nop(sqe);
io_uring_sqe_set_data(sqe, NULL);
sqe->flags = 0;
return -1;
}
return 0;
}
static int _evset_nop(struct mcs_func *f) {
struct io_uring_sqe *sqe;
sqe = io_uring_get_sqe(&f->parent->ring);
if (sqe == NULL) {
return -1;
}
io_uring_prep_nop(sqe);
io_uring_sqe_set_data(sqe, &f->ev);
return 0;
}
static int _evset_wrflush(struct mcs_func *f, struct mcs_func_client *c) {
struct io_uring_sqe *sqe;
sqe = io_uring_get_sqe(&f->parent->ring);
if (sqe == NULL) {
return -1;
}
io_uring_prep_write(sqe, mcmc_fd(c->mcmc), c->wbuf + c->wbuf_sent, c->wbuf_used - c->wbuf_sent, 0);
io_uring_sqe_set_data(sqe, &f->ev);
if (_evset_link_timeout(f) != 0) {
io_uring_prep_nop(sqe);
io_uring_sqe_set_data(sqe, NULL);
sqe->flags = 0;
return -1;
}
return 0;
}
static int _evset_read(struct mcs_func *f, struct mcs_func_client *c) {
struct io_uring_sqe *sqe;
sqe = io_uring_get_sqe(&f->parent->ring);
if (sqe == NULL) {
return -1;
}
io_uring_prep_recv(sqe, mcmc_fd(c->mcmc), c->rbuf + c->rbuf_used, c->rbuf_size - c->rbuf_used, 0);
io_uring_sqe_set_data(sqe, &f->ev);
if (_evset_link_timeout(f) != 0) {
io_uring_prep_nop(sqe);
io_uring_sqe_set_data(sqe, NULL);
sqe->flags = 0;
return -1;
}
return 0;
}
static int _evset_cancel(struct mcs_func *f) {
struct io_uring_sqe *sqe;
sqe = io_uring_get_sqe(&f->parent->ring);
if (sqe == NULL) {
return -1;
}
io_uring_prep_cancel(sqe, &f->ev, 0);
io_uring_sqe_set_data(sqe, &f->ev);
return 0;
}
// *** CORE ***
static void mcs_expand_rbuf(struct mcs_func_client *c) {
if (c->rbuf_used == c->rbuf_size) {
c->rbuf_size *= 2;
char *nrb = realloc(c->rbuf, c->rbuf_size);
if (nrb == NULL) {
fprintf(stderr, "Failed to realloc read buffer\n");
abort();
}
c->rbuf = nrb;
}
}
// yes this should be a "buf" abstraction
static void mcs_expand_wbuf(struct mcs_func_client *c, size_t len) {
while (c->wbuf_used + len > c->wbuf_size) {
c->wbuf_size *= 2;
}
char *nwb = realloc(c->wbuf, c->wbuf_size);
if (nwb == NULL) {
fprintf(stderr, "Failed to realloc write buffer\n");
abort();
}
c->wbuf = nwb;
}
// 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);
c->rbuf_used = 0;
c->rbuf_toconsume = 0;
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;
if (res > 0) {
c->wbuf_sent += res;
if (c->wbuf_sent < c->wbuf_used) {
// need to continue flushing write buffer.
f->state = mcs_fstate_flush;
} else {
c->wbuf_sent = 0;
c->wbuf_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;
}
}
static void _mcs_consume_buf(struct mcs_func_client *c) {
if (c->rbuf_toconsume != 0) {
c->rbuf_used -= c->rbuf_toconsume;
if (c->rbuf_used > 0) {
memmove(c->rbuf, c->rbuf+c->rbuf_toconsume, c->rbuf_used);
}
c->rbuf_toconsume = 0;
}
}
// 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
char *rbuf_offset = c->rbuf + c->rbuf_toconsume;
int rbuf_remain = c->rbuf_used - c->rbuf_toconsume;
if (f->buf_readline == 0) {
// optimistically allocate a response to minimize data copying.
struct mcs_func_resp *r = lua_newuserdatauv(f->L, sizeof(struct mcs_func_resp), 0);
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) {
lua_pop(f->L, 1); // throw away the resp object, try re-parsing later
if (c->rbuf_toconsume != 0) {
// vlen didn't fit, but we are read partway into the
// buffer.
// memmove the buffer and read out.
_mcs_consume_buf(c);
} else {
// ... else the read buffer simply wasn't large enough.
mcs_expand_rbuf(c);
}
ret = 1; // WANT_READ
} else {
r->buf = rbuf_offset;
f->lua_nargs = 1;
c->rbuf_toconsume += r->resp.reslen + r->resp.vlen_read;
clock_gettime(CLOCK_MONOTONIC, &r->received);
}
} else if (r->resp.code == MCMC_WANT_READ) {
lua_pop(f->L, 1);
mcs_expand_rbuf(c);
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 = 1;
c->rbuf_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;
c->rbuf_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);
ret = 1; // WANT_READ
}
}
return ret;
}
static void mcs_postread(struct mcs_func *f, struct mcs_func_client *c) {
int res = f->cqe_res;
if (res > 0) {
c->rbuf_used += res;
int ret = mcs_read_buf(f, c);
if (ret == 0) {
f->state = mcs_fstate_run;
} else if (ret == 1) {
f->state = mcs_fstate_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;
}
}
static int mcs_reschedule(struct mcs_func *f) {
if (f->rate.rate != 0) {
if (_evset_abs_timeout(f) == 0) {
// schedule the next wakeup time.
timespec_add(&f->rate.next, &f->rate.delta);
} else {
return -1;
}
} else {
return _evset_nop(f);
}
return 0;
}
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) {
f->state = mcs_fstate_connecting;
} else {
mcmc_disconnect(f->c.mcmc);
f->c.connected = false;
f->state = mcs_fstate_retry;
}
break;
case mcs_fstate_connecting:
if (_evset_wrpoll(f, &f->c) != 0) {
return -1;
}
f->state = mcs_fstate_postconnect;
stop = true;
break;
case mcs_fstate_postconnect:
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 {
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:
if (mcs_reschedule(f) == 0) {
f->state = mcs_fstate_restart;
stop = true;
} else {
return -1;
}
break;
case mcs_fstate_flush:
if (_evset_wrflush(f, &f->c) == 0) {
f->state = mcs_fstate_postflush;
stop = true;
} else {
return -1;
}
break;
case mcs_fstate_postflush:
mcs_postflush(f, &f->c);
break;
case mcs_fstate_read:
if (_evset_read(f, &f->c) == 0) {
f->state = mcs_fstate_postread;
stop = true;
} else {
return -1;
}
break;
case mcs_fstate_postread:
mcs_postread(f, &f->c);
break;
case mcs_fstate_retry:
if (_evset_retry_timeout(f) == 0) {
f->state = mcs_fstate_postretry;
stop = true;
} else {
return -1;
}
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:
if (_evset_sleep(f) == 0) {
f->state = mcs_fstate_run;
stop = true;
} else {
return -1;
}
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 (_evset_wrpoll(f, c) != 0) {
return -1;
}
f->state = mcs_fstate_postconnect;
stop = true;
break;
case mcs_fstate_postconnect:
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 {
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 if (_evset_read(f, c) == 0) {
f->state = mcs_fstate_postread;
stop = true;
} else {
return -1;
}
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);
f->lua_nargs = 2;
f->state = mcs_fstate_run;
} else if (_evset_wrflush(f, c) == 0) {
f->state = mcs_fstate_postflush;
stop = true;
} else {
return -1;
}
break;
case mcs_fstate_postflush:
c = lua_touserdata(f->L, 1);
mcs_postflush(f, c);
break;
case mcs_fstate_syserr:
c = lua_touserdata(f->L, 1);
mcmc_disconnect(c->mcmc);
c->connected = false;
// FIXME: need better way to communicate client has errored.
lua_pushnil(f->L);
lua_pushinteger(f->L, f->reserr);
f->lua_nargs = 2;
f->state = mcs_fstate_run;
break;
case mcs_fstate_run:
if (mcs_func_lua(f)) {
f->state = mcs_fstate_stop;
}
break;
case mcs_fstate_sleep:
if (_evset_sleep(f) == 0) {
f->state = mcs_fstate_run;
stop = true;
} else {
return -1;
}
break;
case mcs_fstate_stop:
f->parent->active_funcs--;
f->active = false;
stop = true;
break;
default:
fprintf(stderr, "Unhandled custom function state, aborting\n");
abort();
}
}
return 0;
}
// Turn the 8 byte hash into a pattern-fill for the value. Just filling with
// the same value can miss a few classes of bugs.
static void _mcs_write_value(struct mcs_func_req *r, struct mcs_func_client *c) {
uint64_t hash = r->hash;
for (int x = 0; x < r->vlen / sizeof(hash); x++) {
memcpy(c->wbuf + c->wbuf_used, &hash, sizeof(hash));
hash++;
c->wbuf_used += sizeof(hash);
}
int remain = r->vlen % sizeof(hash);
for (int x = 0; x < remain; x++) {
c->wbuf[c->wbuf_used] = '#';
c->wbuf_used++;
}
memcpy(c->wbuf + c->wbuf_used, "\r\n", 2);
c->wbuf_used += 2;
}
// should be doing cast-comparisons since that should be a bit faster, but not
// sure what the compiler's going to do with this to be honest.
static int _mcs_check_value(struct mcs_func_req *req, struct mcs_func_resp *res) {
uint64_t hash = req->hash;
// remove \r\n from value for comparison.
for (int x = 0; x < (res->resp.vlen-2) / sizeof(hash); x++) {
if (memcmp(res->resp.value + x * sizeof(hash), &hash, sizeof(hash)) != 0) {
return -1;
}
hash++;
}
// TODO: bother checking the remain? it should be fine since we can't get
// here without the \r\n being valid _and_ all of the key specific stuff
// checked.
//int remain = res->resp.vlen % sizeof(hash);
return 0;
}
// writes the passed argument to the client buffer
static int mcslib_write_c(struct mcs_func *f, struct mcs_func_client *c) {
int type = lua_type(f->L, -1);
size_t len = 0;
int vlen = 0;
const char *rline = NULL;
struct mcs_func_req *req = NULL;
if (type == LUA_TUSERDATA) {
req = lua_touserdata(f->L, -1);
len = req->len;
rline = req->data;
vlen = req->vlen;
clock_gettime(CLOCK_MONOTONIC, &req->start);
} else if (type == LUA_TSTRING) {
rline = luaL_tolstring(f->L, -1, &len);
}
mcs_expand_wbuf(c, len + vlen + 2);
memcpy(c->wbuf + c->wbuf_used, rline, len);
c->wbuf_used += len;
lua_pop(f->L, 1);
if (vlen != 0) {
_mcs_write_value(req, c);
}
return 0;
}
// TODO: the read routine can offset via rbuf_toconsume until we hit
// "MCMC_WANT_READ" to avoid memmove's in most/many cases.