forked from memcached/memcached
-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxy_lua.c
1602 lines (1362 loc) · 51.5 KB
/
proxy_lua.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 -*- */
#include "proxy.h"
// sad, I had to look this up...
#define NANOSECONDS(x) ((x) * 1E9 + 0.5)
#define MICROSECONDS(x) ((x) * 1E6 + 0.5)
// func prototype example:
// static int fname (lua_State *L)
// normal library open:
// int luaopen_mcp(lua_State *L) { }
static lua_Integer _mcplib_backend_get_waittime(lua_Number secondsf) {
lua_Integer secondsi = (lua_Integer) secondsf;
lua_Number subseconds = secondsf - secondsi;
if (subseconds >= 0.5) {
// Yes, I know this rounding is probably wrong. it's close enough.
// Rounding functions have tricky portability and whole-integer
// rounding is at least simpler to reason about.
secondsi++;
}
if (secondsi < 1) {
secondsi = 1;
}
return secondsi;
}
static int mcplib_time_real_millis(lua_State *L) {
struct timespec now;
clock_gettime(CLOCK_REALTIME, &now);
lua_Integer t = now.tv_nsec / 1000000 + now.tv_sec * 1000;
lua_pushinteger(L, t);
return 1;
}
static int mcplib_time_mono_millis(lua_State *L) {
struct timespec now;
clock_gettime(CLOCK_MONOTONIC, &now);
lua_Integer t = now.tv_nsec / 1000000 + now.tv_sec * 1000;
lua_pushinteger(L, t);
return 1;
}
// end util funcs.
static int mcplib_response_elapsed(lua_State *L) {
mcp_resp_t *r = luaL_checkudata(L, -1, "mcp.response");
lua_pushinteger(L, r->elapsed);
return 1;
}
// resp:ok()
static int mcplib_response_ok(lua_State *L) {
mcp_resp_t *r = luaL_checkudata(L, -1, "mcp.response");
if (r->status == MCMC_OK) {
lua_pushboolean(L, 1);
} else {
lua_pushboolean(L, 0);
}
return 1;
}
static int mcplib_response_hit(lua_State *L) {
mcp_resp_t *r = luaL_checkudata(L, -1, "mcp.response");
if (r->status == MCMC_OK && r->resp.code != MCMC_CODE_END) {
lua_pushboolean(L, 1);
} else {
lua_pushboolean(L, 0);
}
return 1;
}
// Caller needs to discern if a vlen is 0 because of a failed response or an
// OK response that was actually zero. So we always return an integer value
// here.
static int mcplib_response_vlen(lua_State *L) {
mcp_resp_t *r = luaL_checkudata(L, -1, "mcp.response");
// We do remove the "\r\n" from the value length, so if you're actually
// processing the value nothing breaks.
if (r->resp.vlen >= 2) {
lua_pushinteger(L, r->resp.vlen-2);
} else {
lua_pushinteger(L, 0);
}
return 1;
}
// Refer to MCMC_CODE_* defines.
static int mcplib_response_code(lua_State *L) {
mcp_resp_t *r = luaL_checkudata(L, -1, "mcp.response");
lua_pushinteger(L, r->resp.code);
return 1;
}
// Get the unparsed response line for handling in lua.
static int mcplib_response_line(lua_State *L) {
mcp_resp_t *r = luaL_checkudata(L, -1, "mcp.response");
if (r->resp.rline != NULL) {
lua_pushlstring(L, r->resp.rline, r->resp.rlen);
} else {
lua_pushnil(L);
}
return 1;
}
void mcp_response_cleanup(LIBEVENT_THREAD *t, mcp_resp_t *r) {
// On error/similar we might be holding the read buffer.
// If the buf is handed off to mc_resp for return, this pointer is NULL
if (r->buf != NULL) {
pthread_mutex_lock(&t->proxy_limit_lock);
t->proxy_buffer_memory_used -= r->blen + r->extra;
pthread_mutex_unlock(&t->proxy_limit_lock);
free(r->buf);
r->buf = NULL;
}
// release our temporary mc_resp sub-object.
if (r->cresp != NULL) {
mc_resp *cresp = r->cresp;
assert(r->thread != NULL);
resp_free(r->thread, cresp);
r->cresp = NULL;
}
}
static int mcplib_response_gc(lua_State *L) {
LIBEVENT_THREAD *t = PROXY_GET_THR(L);
mcp_resp_t *r = luaL_checkudata(L, -1, "mcp.response");
mcp_response_cleanup(t, r);
return 0;
}
// NOTE: backends are global objects owned by pool objects.
// Each pool has a "proxy pool object" distributed to each worker VM.
// proxy pool objects are held at the same time as any request exists on a
// backend, in the coroutine stack during yield()
// To free a backend: All proxies for a pool are collected, then the central
// pool is collected, which releases backend references, which allows backend
// to be collected.
static int mcplib_backend_wrap_gc(lua_State *L) {
mcp_backend_wrap_t *bew = luaL_checkudata(L, -1, "mcp.backendwrap");
proxy_ctx_t *ctx = PROXY_GET_CTX(L);
if (bew->be != NULL) {
mcp_backend_t *be = bew->be;
// TODO (v3): technically a race where a backend could be created,
// queued, but not picked up before being gc'ed again. In practice
// this is impossible but at some point we should close the loop here.
// Since we're running in the config thread it could just busy poll
// until the connection was picked up.
assert(be->transferred);
// There has to be at least one connection, and the event_thread will
// always be the same.
proxy_event_thread_t *e = be->be[0].event_thread;
pthread_mutex_lock(&e->mutex);
STAILQ_INSERT_TAIL(&e->beconn_head_in, be, beconn_next);
pthread_mutex_unlock(&e->mutex);
// Signal to check queue.
#ifdef USE_EVENTFD
uint64_t u = 1;
// TODO (v2): check result? is it ever possible to get a short write/failure
// for an eventfd?
if (write(e->be_event_fd, &u, sizeof(uint64_t)) != sizeof(uint64_t)) {
assert(1 == 0);
}
#else
if (write(e->be_notify_send_fd, "w", 1) <= 0) {
assert(1 == 0);
}
#endif
}
STAT_DECR(ctx, backend_total, 1);
return 0;
}
static int mcplib_backend_gc(lua_State *L) {
return 0; // no-op.
}
// backend label object; given to pools which then find or create backend
// objects as necessary.
// allow optionally passing a table of arguments for extended options:
// { label = "etc", "host" = "127.0.0.1", port = "11211",
// readtimeout = 0.5, connecttimeout = 1, retrytime = 3,
// failurelimit = 3, tcpkeepalive = false }
static int mcplib_backend(lua_State *L) {
size_t llen = 0;
size_t nlen = 0;
size_t plen = 0;
proxy_ctx_t *ctx = PROXY_GET_CTX(L);
mcp_backend_label_t *be = lua_newuserdatauv(L, sizeof(mcp_backend_label_t), 0);
memset(be, 0, sizeof(*be));
const char *label;
const char *name;
const char *port;
// copy global defaults for tunables.
memcpy(&be->tunables, &ctx->tunables, sizeof(be->tunables));
be->conncount = 1; // one connection per backend as default.
if (lua_istable(L, 1)) {
// We don't pop the label/host/port strings so lua won't change them
// until after the function call.
if (lua_getfield(L, 1, "label") != LUA_TNIL) {
label = luaL_checklstring(L, -1, &llen);
} else {
proxy_lua_error(L, "backend must have a label argument");
return 0;
}
if (lua_getfield(L, 1, "host") != LUA_TNIL) {
name = luaL_checklstring(L, -1, &nlen);
} else {
proxy_lua_error(L, "backend must have a host argument");
return 0;
}
// TODO: allow a default port.
if (lua_getfield(L, 1, "port") != LUA_TNIL) {
port = luaL_checklstring(L, -1, &plen);
} else {
proxy_lua_error(L, "backend must have a port argument");
return 0;
}
if (lua_getfield(L, 1, "tcpkeepalive") != LUA_TNIL) {
be->tunables.tcp_keepalive = lua_toboolean(L, -1);
}
lua_pop(L, 1);
if (lua_getfield(L, 1, "failurelimit") != LUA_TNIL) {
int limit = luaL_checkinteger(L, -1);
if (limit < 0) {
proxy_lua_error(L, "failure_limit must be >= 0");
return 0;
}
be->tunables.backend_failure_limit = limit;
}
lua_pop(L, 1);
if (lua_getfield(L, 1, "connecttimeout") != LUA_TNIL) {
lua_Number secondsf = luaL_checknumber(L, -1);
lua_Integer secondsi = (lua_Integer) secondsf;
lua_Number subseconds = secondsf - secondsi;
be->tunables.connect.tv_sec = secondsi;
be->tunables.connect.tv_usec = MICROSECONDS(subseconds);
}
lua_pop(L, 1);
// TODO (v2): print deprecation warning.
if (lua_getfield(L, 1, "retrytimeout") != LUA_TNIL) {
be->tunables.retry.tv_sec =
_mcplib_backend_get_waittime(luaL_checknumber(L, -1));
}
lua_pop(L, 1);
if (lua_getfield(L, 1, "retrywaittime") != LUA_TNIL) {
be->tunables.retry.tv_sec =
_mcplib_backend_get_waittime(luaL_checknumber(L, -1));
}
lua_pop(L, 1);
if (lua_getfield(L, 1, "retrytimeout") != LUA_TNIL) {
lua_Number secondsf = luaL_checknumber(L, -1);
lua_Integer secondsi = (lua_Integer) secondsf;
lua_Number subseconds = secondsf - secondsi;
be->tunables.retry.tv_sec = secondsi;
be->tunables.retry.tv_usec = MICROSECONDS(subseconds);
}
lua_pop(L, 1);
if (lua_getfield(L, 1, "readtimeout") != LUA_TNIL) {
lua_Number secondsf = luaL_checknumber(L, -1);
lua_Integer secondsi = (lua_Integer) secondsf;
lua_Number subseconds = secondsf - secondsi;
be->tunables.read.tv_sec = secondsi;
be->tunables.read.tv_usec = MICROSECONDS(subseconds);
}
lua_pop(L, 1);
if (lua_getfield(L, 1, "down") != LUA_TNIL) {
int down = lua_toboolean(L, -1);
be->tunables.down = down;
}
lua_pop(L, 1);
if (lua_getfield(L, 1, "flaptime") != LUA_TNIL) {
lua_Number secondsf = luaL_checknumber(L, -1);
lua_Integer secondsi = (lua_Integer) secondsf;
lua_Number subseconds = secondsf - secondsi;
be->tunables.flap.tv_sec = secondsi;
be->tunables.flap.tv_usec = MICROSECONDS(subseconds);
}
lua_pop(L, 1);
if (lua_getfield(L, 1, "flapbackofframp") != LUA_TNIL) {
float ramp = luaL_checknumber(L, -1);
if (ramp <= 1.1) {
ramp = 1.1;
}
be->tunables.flap_backoff_ramp = ramp;
}
lua_pop(L, 1);
if (lua_getfield(L, 1, "flapbackoffmax") != LUA_TNIL) {
luaL_checknumber(L, -1);
uint32_t max = lua_tointeger(L, -1);
be->tunables.flap_backoff_max = max;
}
lua_pop(L, 1);
if (lua_getfield(L, 1, "connections") != LUA_TNIL) {
int c = luaL_checkinteger(L, -1);
if (c <= 0) {
proxy_lua_error(L, "backend connections argument must be >= 0");
return 0;
} else if (c > 8) {
proxy_lua_error(L, "backend connections argument must be <= 8");
return 0;
}
be->conncount = c;
}
lua_pop(L, 1);
} else {
label = luaL_checklstring(L, 1, &llen);
name = luaL_checklstring(L, 2, &nlen);
port = luaL_checklstring(L, 3, &plen);
}
if (llen > MAX_LABELLEN-1) {
proxy_lua_error(L, "backend label too long");
return 0;
}
if (nlen > MAX_NAMELEN-1) {
proxy_lua_error(L, "backend name too long");
return 0;
}
if (plen > MAX_PORTLEN-1) {
proxy_lua_error(L, "backend port too long");
return 0;
}
memcpy(be->label, label, llen);
be->label[llen] = '\0';
memcpy(be->name, name, nlen);
be->name[nlen] = '\0';
memcpy(be->port, port, plen);
be->port[plen] = '\0';
be->llen = llen;
if (lua_istable(L, 1)) {
lua_pop(L, 3); // drop label, name, port.
}
luaL_getmetatable(L, "mcp.backend");
lua_setmetatable(L, -2); // set metatable to userdata.
return 1; // return be object.
}
// Called with the cache label at top of the stack.
static mcp_backend_wrap_t *_mcplib_backend_checkcache(lua_State *L, mcp_backend_label_t *bel) {
// first check our reference table to compare.
// Note: The upvalue won't be found unless we're running from a function with it
// set as an upvalue.
int ret = lua_gettable(L, lua_upvalueindex(MCP_BACKEND_UPVALUE));
if (ret != LUA_TNIL) {
mcp_backend_wrap_t *be_orig = luaL_checkudata(L, -1, "mcp.backendwrap");
if (strncmp(be_orig->be->name, bel->name, MAX_NAMELEN) == 0
&& strncmp(be_orig->be->port, bel->port, MAX_PORTLEN) == 0
&& be_orig->be->conncount == bel->conncount
&& memcmp(&be_orig->be->tunables, &bel->tunables, sizeof(bel->tunables)) == 0) {
// backend is the same, return it.
return be_orig;
} else {
// backend not the same, pop from stack and make new one.
lua_pop(L, 1);
}
} else {
lua_pop(L, 1); // pop the nil.
}
return NULL;
}
static mcp_backend_wrap_t *_mcplib_make_backendconn(lua_State *L, mcp_backend_label_t *bel,
proxy_event_thread_t *e) {
proxy_ctx_t *ctx = PROXY_GET_CTX(L);
mcp_backend_wrap_t *bew = lua_newuserdatauv(L, sizeof(mcp_backend_wrap_t), 0);
luaL_getmetatable(L, "mcp.backendwrap");
lua_setmetatable(L, -2); // set metatable to userdata.
mcp_backend_t *be = calloc(1, sizeof(mcp_backend_t) + sizeof(struct mcp_backendconn_s) * bel->conncount);
if (be == NULL) {
proxy_lua_error(L, "out of memory allocating backend connection");
return NULL;
}
bew->be = be;
strncpy(be->name, bel->name, MAX_NAMELEN+1);
strncpy(be->port, bel->port, MAX_PORTLEN+1);
strncpy(be->label, bel->label, MAX_LABELLEN+1);
memcpy(&be->tunables, &bel->tunables, sizeof(bel->tunables));
be->conncount = bel->conncount;
STAILQ_INIT(&be->io_head);
for (int x = 0; x < bel->conncount; x++) {
struct mcp_backendconn_s *bec = &be->be[x];
bec->be_parent = be;
memcpy(&bec->tunables, &bel->tunables, sizeof(bel->tunables));
STAILQ_INIT(&bec->io_head);
bec->state = mcp_backend_read;
// this leaves a permanent buffer on the backend, which is fine
// unless you have billions of backends.
// we can later optimize for pulling buffers from idle backends.
bec->rbuf = malloc(READ_BUFFER_SIZE);
if (bec->rbuf == NULL) {
proxy_lua_error(L, "out of memory allocating backend");
return NULL;
}
// initialize the client
bec->client = malloc(mcmc_size(MCMC_OPTION_BLANK));
if (bec->client == NULL) {
proxy_lua_error(L, "out of memory allocating backend");
return NULL;
}
// TODO (v2): no way to change the TCP_KEEPALIVE state post-construction.
// This is a trivial fix if we ensure a backend's owning event thread is
// set before it can be used in the proxy, as it would have access to the
// tunables structure. _reset_bad_backend() may not have its event thread
// set 100% of the time and I don't want to introduce a crash right now,
// so I'm writing this overly long comment. :)
int flags = MCMC_OPTION_NONBLOCK;
STAT_L(ctx);
if (ctx->tunables.tcp_keepalive) {
flags |= MCMC_OPTION_TCP_KEEPALIVE;
}
STAT_UL(ctx);
bec->connect_flags = flags;
bec->event_thread = e;
}
pthread_mutex_lock(&e->mutex);
STAILQ_INSERT_TAIL(&e->beconn_head_in, be, beconn_next);
pthread_mutex_unlock(&e->mutex);
// Signal to check queue.
#ifdef USE_EVENTFD
uint64_t u = 1;
// TODO (v2): check result? is it ever possible to get a short write/failure
// for an eventfd?
if (write(e->be_event_fd, &u, sizeof(uint64_t)) != sizeof(uint64_t)) {
assert(1 == 0);
}
#else
if (write(e->be_notify_send_fd, "w", 1) <= 0) {
assert(1 == 0);
}
#endif
lua_pushvalue(L, -2); // push the label string back to the top.
// Add this new backend connection to the object cache.
lua_pushvalue(L, -2); // copy the backend reference to the top.
// set our new backend wrapper object into the reference table.
lua_settable(L, lua_upvalueindex(MCP_BACKEND_UPVALUE));
// stack is back to having backend on the top.
STAT_INCR(ctx, backend_total, 1);
return bew;
}
static int mcplib_pool_gc(lua_State *L) {
mcp_pool_t *p = luaL_checkudata(L, -1, "mcp.pool");
assert(p->refcount == 0);
pthread_mutex_destroy(&p->lock);
for (int x = 0; x < p->pool_be_total; x++) {
if (p->pool[x].ref) {
luaL_unref(L, LUA_REGISTRYINDEX, p->pool[x].ref);
}
}
return 0;
}
// Looks for a short string in a key to separate which part gets hashed vs
// sent to the backend node.
// ie: "foo:bar|#|restofkey" - only "foo:bar" gets hashed.
static const char *mcp_key_hash_filter_stop(const char *conf, const char *key, size_t klen, size_t *newlen) {
char temp[KEY_MAX_LENGTH+1];
*newlen = klen;
if (klen > KEY_MAX_LENGTH) {
// Hedging against potential bugs.
return key;
}
memcpy(temp, key, klen);
temp[klen+1] = '\0';
// TODO (v2): memmem would avoid the temp key and memcpy here, but it's
// not technically portable. An easy improvement would be to detect
// memmem() in `configure` and only use strstr/copy as a fallback.
// Since keys are short it's unlikely this would be a major performance
// win.
char *found = strstr(temp, conf);
if (found) {
*newlen = found - temp;
}
// hash stop can't change where keys start.
return key;
}
// Takes a two character "tag", ie; "{}", or "$$", searches string for the
// first then second character. Only hashes the portion within these tags.
// *conf _must_ be two characters.
static const char *mcp_key_hash_filter_tag(const char *conf, const char *key, size_t klen, size_t *newlen) {
*newlen = klen;
const char *t1 = memchr(key, conf[0], klen);
if (t1) {
size_t remain = klen - (t1 - key);
// must be at least one character inbetween the tags to hash.
if (remain > 1) {
const char *t2 = memchr(t1, conf[1], remain);
if (t2) {
*newlen = t2 - t1 - 1;
return t1+1;
}
}
}
return key;
}
static void _mcplib_pool_dist(lua_State *L, mcp_pool_t *p) {
luaL_checktype(L, -1, LUA_TTABLE);
if (lua_getfield(L, -1, "new") != LUA_TFUNCTION) {
proxy_lua_error(L, "key distribution object missing 'new' function");
return;
}
// - now create the copy pool table
lua_createtable(L, p->pool_size, 0); // give the new pool table a sizing hint.
for (int x = 1; x <= p->pool_size; x++) {
mcp_backend_t *be = p->pool[x-1].be;
lua_createtable(L, 0, 4);
// stack = [p, h, f, optN, newpool, backend]
// the key should be fine for id? maybe don't need to duplicate
// this?
lua_pushinteger(L, x);
lua_setfield(L, -2, "id");
// we don't use the hostname for ketama hashing
// so passing ip for hostname is fine
lua_pushstring(L, be->name);
lua_setfield(L, -2, "addr");
lua_pushstring(L, be->port);
lua_setfield(L, -2, "port");
// set the backend table into the new pool table.
lua_rawseti(L, -2, x);
}
// we can either use lua_insert() or possibly _rotate to shift
// things into the right place, but simplest is to just copy the
// option arg to the end of the stack.
lua_pushvalue(L, 2);
// - stack should be: pool, opts, func, pooltable, opts
// call the dist new function.
int res = lua_pcall(L, 2, 2, 0);
if (res != LUA_OK) {
lua_error(L); // error should be on the stack already.
return;
}
// -1 is lightuserdata ptr to the struct (which must be owned by the
// userdata), which is later used for internal calls.
struct proxy_hash_caller *phc;
luaL_checktype(L, -1, LUA_TLIGHTUSERDATA);
luaL_checktype(L, -2, LUA_TUSERDATA);
phc = lua_touserdata(L, -1);
memcpy(&p->phc, phc, sizeof(*phc));
lua_pop(L, 1);
// -2 was userdata we need to hold a reference to
p->phc_ref = luaL_ref(L, LUA_REGISTRYINDEX);
// UD now popped from stack.
}
// in the proxy object, we can alias a ptr to the pool to where it needs to be
// based on worker number or io_thread right?
static void _mcplib_pool_make_be_loop(lua_State *L, mcp_pool_t *p, int offset, proxy_event_thread_t *t) {
// remember lua arrays are 1 indexed.
for (int x = 1; x <= p->pool_size; x++) {
mcp_pool_be_t *s = &p->pool[x-1 + (offset * p->pool_size)];
lua_geti(L, 1, x); // get next server into the stack.
// If we bail here, the pool _gc() should handle releasing any backend
// references we made so far.
mcp_backend_label_t *bel = luaL_checkudata(L, -1, "mcp.backend");
// check label for pre-existing backend conn/wrapper
// TODO (v2): there're native ways of "from C make lua strings"
int toconcat = 1;
if (p->beprefix[0] != '\0') {
lua_pushstring(L, p->beprefix);
toconcat++;
}
if (p->use_iothread) {
lua_pushstring(L, ":io:");
toconcat++;
} else {
lua_pushstring(L, ":w");
lua_pushinteger(L, offset);
lua_pushstring(L, ":");
toconcat += 3;
}
lua_pushlstring(L, bel->label, bel->llen);
lua_concat(L, toconcat);
lua_pushvalue(L, -1); // copy the label string for the create method.
mcp_backend_wrap_t *bew = _mcplib_backend_checkcache(L, bel);
if (bew == NULL) {
bew = _mcplib_make_backendconn(L, bel, t);
}
s->be = bew->be; // unwrap the backend connection for direct ref.
bew->be->use_io_thread = p->use_iothread;
// If found from cache or made above, the backend wrapper is on the
// top of the stack, so we can now take its reference.
// The wrapper abstraction allows the be memory to be owned by its
// destination thread (IO thread/etc).
s->ref = luaL_ref(L, LUA_REGISTRYINDEX); // references and pops object.
lua_pop(L, 1); // pop the mcp.backend label object.
lua_pop(L, 1); // drop extra label copy.
}
}
// call with table of backends in 1
static void _mcplib_pool_make_be(lua_State *L, mcp_pool_t *p) {
if (p->use_iothread) {
proxy_ctx_t *ctx = PROXY_GET_CTX(L);
_mcplib_pool_make_be_loop(L, p, 0, ctx->proxy_io_thread);
} else {
// TODO (v3) globals.
for (int n = 0; n < settings.num_threads; n++) {
LIBEVENT_THREAD *t = get_worker_thread(n);
_mcplib_pool_make_be_loop(L, p, t->thread_baseid, t->proxy_event_thread);
}
}
}
// p = mcp.pool(backends, { dist = f, hashfilter = f, seed = "a", hash = f })
static int mcplib_pool(lua_State *L) {
proxy_ctx_t *ctx = PROXY_GET_CTX(L);
int argc = lua_gettop(L);
luaL_checktype(L, 1, LUA_TTABLE);
int n = luaL_len(L, 1); // get length of array table
int workers = settings.num_threads; // TODO (v3): globals usage.
size_t plen = sizeof(mcp_pool_t) + (sizeof(mcp_pool_be_t) * n * workers);
mcp_pool_t *p = lua_newuserdatauv(L, plen, 0);
// Zero the memory before use, so we can realibly use __gc to clean up
memset(p, 0, plen);
p->pool_size = n;
p->pool_be_total = n * workers;
p->use_iothread = ctx->tunables.use_iothread;
// TODO (v2): Nicer if this is fetched from mcp.default_key_hash
p->key_hasher = XXH3_64bits_withSeed;
pthread_mutex_init(&p->lock, NULL);
p->ctx = PROXY_GET_CTX(L);
luaL_setmetatable(L, "mcp.pool");
lua_pushvalue(L, -1); // dupe self for reference.
p->self_ref = luaL_ref(L, LUA_REGISTRYINDEX);
// Allow passing an ignored nil as a second argument. Makes the lua easier
int type = lua_type(L, 2);
if (argc == 1 || type == LUA_TNIL) {
_mcplib_pool_make_be(L, p);
lua_getglobal(L, "mcp");
// TODO (v2): decide on a mcp.default_dist and use that instead
if (lua_getfield(L, -1, "dist_jump_hash") != LUA_TNIL) {
_mcplib_pool_dist(L, p);
lua_pop(L, 1); // pop "dist_jump_hash" value.
} else {
lua_pop(L, 1);
}
lua_pop(L, 1); // pop "mcp"
return 1;
}
// Supplied with an options table. We inspect this table to decorate the
// pool, then pass it along to the a constructor if necessary.
luaL_checktype(L, 2, LUA_TTABLE);
if (lua_getfield(L, 2, "iothread") != LUA_TNIL) {
luaL_checktype(L, -1, LUA_TBOOLEAN);
int use_iothread = lua_toboolean(L, -1);
if (use_iothread) {
p->use_iothread = true;
} else {
p->use_iothread = false;
}
lua_pop(L, 1); // remove value.
} else {
lua_pop(L, 1); // pop the nil.
}
if (lua_getfield(L, 2, "beprefix") != LUA_TNIL) {
luaL_checktype(L, -1, LUA_TSTRING);
size_t len = 0;
const char *bepfx = lua_tolstring(L, -1, &len);
memcpy(p->beprefix, bepfx, len);
p->beprefix[len+1] = '\0';
lua_pop(L, 1); // pop beprefix string.
} else {
lua_pop(L, 1); // pop the nil.
}
_mcplib_pool_make_be(L, p);
// stack: backends, options, mcp.pool
if (lua_getfield(L, 2, "dist") != LUA_TNIL) {
// overriding the distribution function.
_mcplib_pool_dist(L, p);
lua_pop(L, 1); // remove the dist table from stack.
} else {
lua_pop(L, 1); // pop the nil.
// use the default dist if not specified with an override table.
lua_getglobal(L, "mcp");
// TODO (v2): decide on a mcp.default_dist and use that instead
if (lua_getfield(L, -1, "dist_jump_hash") != LUA_TNIL) {
_mcplib_pool_dist(L, p);
lua_pop(L, 1); // pop "dist_jump_hash" value.
} else {
lua_pop(L, 1);
}
lua_pop(L, 1); // pop "mcp"
}
if (lua_getfield(L, 2, "filter") != LUA_TNIL) {
luaL_checktype(L, -1, LUA_TSTRING);
const char *f_type = lua_tostring(L, -1);
if (strcmp(f_type, "stop") == 0) {
p->key_filter = mcp_key_hash_filter_stop;
} else if (strcmp(f_type, "tags") == 0) {
p->key_filter = mcp_key_hash_filter_tag;
} else {
proxy_lua_ferror(L, "unknown hash filter specified: %s\n", f_type);
}
lua_pop(L, 1); // pops "filter" value.
if (lua_getfield(L, 2, "filter_conf") == LUA_TSTRING) {
size_t len = 0;
const char *conf = lua_tolstring(L, -1, &len);
if (len < 2 || len > KEY_HASH_FILTER_MAX) {
proxy_lua_ferror(L, "hash filter conf must be between 2 and %d characters", KEY_HASH_FILTER_MAX);
}
memcpy(p->key_filter_conf, conf, len);
p->key_filter_conf[len+1] = '\0';
} else {
proxy_lua_error(L, "hash filter requires 'filter_conf' string");
}
lua_pop(L, 1); // pops "filter_conf" value.
} else {
lua_pop(L, 1); // pop the nil.
}
if (lua_getfield(L, 2, "hash") != LUA_TNIL) {
luaL_checktype(L, -1, LUA_TLIGHTUSERDATA);
struct proxy_hash_func *phf = lua_touserdata(L, -1);
p->key_hasher = phf->func;
lua_pop(L, 1);
} else {
lua_pop(L, 1); // pop the nil.
}
if (lua_getfield(L, 2, "seed") != LUA_TNIL) {
luaL_checktype(L, -1, LUA_TSTRING);
size_t seedlen;
const char *seedstr = lua_tolstring(L, -1, &seedlen);
// Note: the custom hasher for a dist may be "weird" in some cases, so
// we use a standard hash method for the seed here.
// I'm open to changing this (ie; mcp.pool_seed_hasher = etc)
p->hash_seed = XXH3_64bits(seedstr, seedlen);
lua_pop(L, 1);
} else {
lua_pop(L, 1); // pop the nil.
}
if (p->phc.selector_func == NULL) {
proxy_lua_error(L, "cannot create pool missing 'dist' argument");
}
return 1;
}
static int mcplib_pool_proxy_gc(lua_State *L) {
mcp_pool_proxy_t *pp = luaL_checkudata(L, -1, "mcp.pool_proxy");
mcp_pool_t *p = pp->main;
pthread_mutex_lock(&p->lock);
p->refcount--;
if (p->refcount == 0) {
proxy_ctx_t *ctx = p->ctx;
pthread_mutex_lock(&ctx->manager_lock);
STAILQ_INSERT_TAIL(&ctx->manager_head, p, next);
pthread_cond_signal(&ctx->manager_cond);
pthread_mutex_unlock(&ctx->manager_lock);
}
pthread_mutex_unlock(&p->lock);
return 0;
}
mcp_backend_t *mcplib_pool_proxy_call_helper(mcp_pool_proxy_t *pp, const char *key, size_t len) {
mcp_pool_t *p = pp->main;
if (p->key_filter) {
key = p->key_filter(p->key_filter_conf, key, len, &len);
P_DEBUG("%s: filtered key for hashing (%.*s)\n", __func__, (int)len, key);
}
uint64_t hash = p->key_hasher(key, len, p->hash_seed);
uint32_t lookup = p->phc.selector_func(hash, p->phc.ctx);
assert(p->phc.ctx != NULL);
if (lookup >= p->pool_size) {
return NULL;
}
return pp->pool[lookup].be;
}
// pool(request) -> yields the pool/request for further processing
static int mcplib_pool_proxy_call(lua_State *L) {
mcp_pool_proxy_t *pp = luaL_checkudata(L, -2, "mcp.pool_proxy");
mcp_request_t *rq = luaL_checkudata(L, -1, "mcp.request");
// we have a fast path to the key/length.
if (!rq->pr.keytoken) {
proxy_lua_error(L, "cannot route commands without key");
return 0;
}
const char *key = MCP_PARSER_KEY(rq->pr);
size_t len = rq->pr.klen;
mcp_backend_t *be = mcplib_pool_proxy_call_helper(pp, key, len);
if (be == NULL) {
proxy_lua_error(L, "key dist hasher tried to use out of bounds index");
return 0;
}
lua_pushlightuserdata(L, be);
// now yield request, pool, backend, mode up.
lua_pushinteger(L, MCP_YIELD_POOL);
return lua_yield(L, 4);
}
static int mcplib_backend_use_iothread(lua_State *L) {
luaL_checktype(L, -1, LUA_TBOOLEAN);
int state = lua_toboolean(L, -1);
proxy_ctx_t *ctx = PROXY_GET_CTX(L);
STAT_L(ctx);
ctx->tunables.use_iothread = state;
STAT_UL(ctx);
return 0;
}
static int mcplib_tcp_keepalive(lua_State *L) {
luaL_checktype(L, -1, LUA_TBOOLEAN);
int state = lua_toboolean(L, -1);
proxy_ctx_t *ctx = PROXY_GET_CTX(L);
STAT_L(ctx);
ctx->tunables.tcp_keepalive = state;
STAT_UL(ctx);
return 0;
}
static int mcplib_backend_failure_limit(lua_State *L) {
int limit = luaL_checkinteger(L, -1);
proxy_ctx_t *ctx = PROXY_GET_CTX(L);
if (limit < 0) {
proxy_lua_error(L, "backend_failure_limit must be >= 0");
return 0;
}
STAT_L(ctx);
ctx->tunables.backend_failure_limit = limit;
STAT_UL(ctx);
return 0;
}
static int mcplib_backend_connect_timeout(lua_State *L) {
lua_Number secondsf = luaL_checknumber(L, -1);
lua_Integer secondsi = (lua_Integer) secondsf;
lua_Number subseconds = secondsf - secondsi;
proxy_ctx_t *ctx = PROXY_GET_CTX(L);
STAT_L(ctx);
ctx->tunables.connect.tv_sec = secondsi;
ctx->tunables.connect.tv_usec = MICROSECONDS(subseconds);
STAT_UL(ctx);
return 0;
}
static int mcplib_backend_retry_waittime(lua_State *L) {
lua_Number secondsf = luaL_checknumber(L, -1);
proxy_ctx_t *ctx = PROXY_GET_CTX(L);
lua_Integer secondsi = _mcplib_backend_get_waittime(secondsf);
STAT_L(ctx);
ctx->tunables.retry.tv_sec = secondsi;
ctx->tunables.retry.tv_usec = 0;
STAT_UL(ctx);
return 0;
}
// TODO (v2): deprecation notice print when using this function.
static int mcplib_backend_retry_timeout(lua_State *L) {
return mcplib_backend_retry_waittime(L);
}
static int mcplib_backend_read_timeout(lua_State *L) {
lua_Number secondsf = luaL_checknumber(L, -1);
lua_Integer secondsi = (lua_Integer) secondsf;
lua_Number subseconds = secondsf - secondsi;
proxy_ctx_t *ctx = PROXY_GET_CTX(L);
STAT_L(ctx);
ctx->tunables.read.tv_sec = secondsi;
ctx->tunables.read.tv_usec = MICROSECONDS(subseconds);
STAT_UL(ctx);
return 0;
}
static int mcplib_backend_flap_time(lua_State *L) {
lua_Number secondsf = luaL_checknumber(L, -1);
lua_Integer secondsi = (lua_Integer) secondsf;
lua_Number subseconds = secondsf - secondsi;
proxy_ctx_t *ctx = PROXY_GET_CTX(L);
STAT_L(ctx);
ctx->tunables.flap.tv_sec = secondsi;
ctx->tunables.flap.tv_usec = MICROSECONDS(subseconds);
STAT_UL(ctx);
return 0;
}
static int mcplib_backend_flap_backoff_ramp(lua_State *L) {
float factor = luaL_checknumber(L, -1);
proxy_ctx_t *ctx = PROXY_GET_CTX(L);
if (factor <= 1.1) {
factor = 1.1;
}
STAT_L(ctx);