forked from haproxy/haproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhlua_fcn.c
2727 lines (2283 loc) · 64.4 KB
/
hlua_fcn.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
/*
* Lua safe functions
*
* Copyright 2015-2016 Thierry Fournier <tfournier@arpalert.org>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
*
* All the functions in this file runs with a Lua stack, and can
* return with a longjmp. All of these function must be launched
* in an environment able to catch a longjmp, otherwise a
* critical error can be raised.
*/
#define _GNU_SOURCE
#include <lauxlib.h>
#include <lua.h>
#include <lualib.h>
#include <import/ebmbtree.h>
#include <haproxy/cli-t.h>
#include <haproxy/errors.h>
#include <haproxy/hlua.h>
#include <haproxy/hlua_fcn.h>
#include <haproxy/http.h>
#include <haproxy/net_helper.h>
#include <haproxy/pattern-t.h>
#include <haproxy/proxy.h>
#include <haproxy/regex.h>
#include <haproxy/server.h>
#include <haproxy/stats.h>
#include <haproxy/stick_table.h>
#include <haproxy/event_hdl.h>
#include <haproxy/stream-t.h>
#include <haproxy/time.h>
#include <haproxy/tools.h>
#include <haproxy/mailers.h>
/* Contains the class reference of the concat object. */
static int class_concat_ref;
static int class_queue_ref;
static int class_proxy_ref;
static int class_server_ref;
static int class_listener_ref;
static int class_event_sub_ref;
static int class_regex_ref;
static int class_stktable_ref;
static int class_proxy_list_ref;
static int class_server_list_ref;
#define STATS_LEN (MAX((int)ST_I_PX_MAX, (int)ST_I_INF_MAX))
static THREAD_LOCAL struct field stats[STATS_LEN];
int hlua_checkboolean(lua_State *L, int index)
{
if (!lua_isboolean(L, index))
luaL_argerror(L, index, "boolean expected");
return lua_toboolean(L, index);
}
/* Helper to push unsigned integers to Lua stack, respecting Lua limitations */
static int hlua_fcn_pushunsigned(lua_State *L, unsigned int val)
{
#if (LUA_MAXINTEGER == LLONG_MAX || ((LUA_MAXINTEGER == LONG_MAX) && (__WORDSIZE == 64)))
lua_pushinteger(L, val);
#else
if (val > INT_MAX)
lua_pushnumber(L, (lua_Number)val);
else
lua_pushinteger(L, (int)val);
#endif
return 1;
}
/* Helper to push unsigned long long to Lua stack, respecting Lua limitations */
static int hlua_fcn_pushunsigned_ll(lua_State *L, unsigned long long val) {
#if (LUA_MAXINTEGER == LLONG_MAX || ((LUA_MAXINTEGER == LONG_MAX) && (__WORDSIZE == 64)))
/* 64 bits case, U64 is supported until LLONG_MAX */
if (val > LLONG_MAX)
lua_pushnumber(L, (lua_Number)val);
else
lua_pushinteger(L, val);
#else
/* 32 bits case, U64 is supported until INT_MAX */
if (val > INT_MAX)
lua_pushnumber(L, (lua_Number)val);
else
lua_pushinteger(L, (int)val);
#endif
return 1;
}
/* This function gets a struct field and converts it in Lua
* variable. The variable is pushed at the top of the stack.
*/
int hlua_fcn_pushfield(lua_State *L, struct field *field)
{
/* The lua_Integer is always signed. Its length depends on
* compilation options, so the following code is conditioned
* by some macros. Windows maros are not supported.
* If the number cannot be represented as integer, we try to
* convert to float.
*/
switch (field_format(field, 0)) {
case FF_EMPTY:
lua_pushnil(L);
return 1;
case FF_S32:
/* S32 is always supported. */
lua_pushinteger(L, field->u.s32);
return 1;
case FF_U32:
#if (LUA_MAXINTEGER == LLONG_MAX || ((LUA_MAXINTEGER == LONG_MAX) && (__WORDSIZE == 64)))
/* 64 bits case, U32 is always supported */
lua_pushinteger(L, field->u.u32);
#else
/* 32 bits case, U32 is supported until INT_MAX. */
if (field->u.u32 > INT_MAX)
lua_pushnumber(L, (lua_Number)field->u.u32);
else
lua_pushinteger(L, field->u.u32);
#endif
return 1;
case FF_S64:
#if (LUA_MAXINTEGER == LLONG_MAX || ((LUA_MAXINTEGER == LONG_MAX) && (__WORDSIZE == 64)))
/* 64 bits case, S64 is always supported */
lua_pushinteger(L, field->u.s64);
#else
/* 64 bits case, S64 is supported between INT_MIN and INT_MAX */
if (field->u.s64 < INT_MIN || field->u.s64 > INT_MAX)
lua_pushnumber(L, (lua_Number)field->u.s64);
else
lua_pushinteger(L, (int)field->u.s64);
#endif
return 1;
case FF_U64:
#if (LUA_MAXINTEGER == LLONG_MAX || ((LUA_MAXINTEGER == LONG_MAX) && (__WORDSIZE == 64)))
/* 64 bits case, U64 is supported until LLONG_MAX */
if (field->u.u64 > LLONG_MAX)
lua_pushnumber(L, (lua_Number)field->u.u64);
else
lua_pushinteger(L, field->u.u64);
#else
/* 64 bits case, U64 is supported until INT_MAX */
if (field->u.u64 > INT_MAX)
lua_pushnumber(L, (lua_Number)field->u.u64);
else
lua_pushinteger(L, (int)field->u.u64);
#endif
return 1;
case FF_STR:
lua_pushstring(L, field->u.str);
return 1;
default:
break;
}
/* Default case, never reached. */
lua_pushnil(L);
return 1;
}
/* Some string are started or terminated by blank chars,
* this function removes the spaces, tabs, \r and
* \n at the begin and at the end of the string "str", and
* push the result in the lua stack.
* Returns a pointer to the Lua internal copy of the string.
*/
const char *hlua_pushstrippedstring(lua_State *L, const char *str)
{
const char *p;
int l;
for (p = str; HTTP_IS_LWS(*p); p++);
for (l = strlen(p); l && HTTP_IS_LWS(p[l-1]); l--);
return lua_pushlstring(L, p, l);
}
/* The three following functions are useful for adding entries
* in a table. These functions takes a string and respectively an
* integer, a string or a function and add it to the table in the
* top of the stack.
*
* These functions throws an error if no more stack size is
* available.
*/
void hlua_class_const_int(lua_State *L, const char *name, int value)
{
lua_pushstring(L, name);
lua_pushinteger(L, value);
lua_rawset(L, -3);
}
void hlua_class_const_str(lua_State *L, const char *name, const char *value)
{
lua_pushstring(L, name);
lua_pushstring(L, value);
lua_rawset(L, -3);
}
void hlua_class_function(lua_State *L, const char *name, int (*function)(lua_State *L))
{
lua_pushstring(L, name);
lua_pushcclosure(L, function, 0);
lua_rawset(L, -3);
}
/* This function returns a string containing the HAProxy object name. */
int hlua_dump_object(struct lua_State *L)
{
const char *name = (const char *)lua_tostring(L, lua_upvalueindex(1));
lua_pushfstring(L, "HAProxy class %s", name);
return 1;
}
/* This function register a table as metatable and. It names
* the metatable, and returns the associated reference.
* The original table is popped from the top of the stack.
* "name" is the referenced class name.
*/
int hlua_register_metatable(struct lua_State *L, char *name)
{
/* Check the type of the top element. it must be
* a table.
*/
if (lua_type(L, -1) != LUA_TTABLE)
luaL_error(L, "hlua_register_metatable() requires a type Table "
"in the top of the stack");
/* Add the __tostring function which identify the
* created object.
*/
lua_pushstring(L, "__tostring");
lua_pushstring(L, name);
lua_pushcclosure(L, hlua_dump_object, 1);
lua_rawset(L, -3);
/* Register a named entry for the table. The table
* reference is copied first because the function
* lua_setfield() pop the entry.
*/
lua_pushvalue(L, -1);
lua_setfield(L, LUA_REGISTRYINDEX, name);
/* Creates the reference of the object. The
* function luaL_ref pop the top of the stack.
*/
return luaL_ref(L, LUA_REGISTRYINDEX);
}
/* Return an object of the expected type, or throws an error. */
void *hlua_checkudata(lua_State *L, int ud, int class_ref)
{
void *p;
int ret;
/* Check if the stack entry is an array. */
if (!lua_istable(L, ud))
luaL_argerror(L, ud, NULL);
/* pop the metatable of the referencecd object. */
if (!lua_getmetatable(L, ud))
luaL_argerror(L, ud, NULL);
/* pop the expected metatable. */
lua_rawgeti(L, LUA_REGISTRYINDEX, class_ref);
/* Check if the metadata have the expected type. */
ret = lua_rawequal(L, -1, -2);
lua_pop(L, 2);
if (!ret)
luaL_argerror(L, ud, NULL);
/* Push on the stack at the entry [0] of the table. */
lua_rawgeti(L, ud, 0);
/* Check if this entry is userdata. */
p = lua_touserdata(L, -1);
if (!p)
luaL_argerror(L, ud, NULL);
/* Remove the entry returned by lua_rawgeti(). */
lua_pop(L, 1);
/* Return the associated struct. */
return p;
}
/* This function return the current date at epoch format in milliseconds. */
int hlua_now(lua_State *L)
{
/* WT: the doc says "returns the current time" and later says that it's
* monotonic. So the best fit is to use start_date+(now-start_time).
*/
struct timeval tv;
tv = NS_TO_TV(now_ns - start_time_ns);
tv_add(&tv, &tv, &start_date);
lua_newtable(L);
lua_pushstring(L, "sec");
lua_pushinteger(L, tv.tv_sec);
lua_rawset(L, -3);
lua_pushstring(L, "usec");
lua_pushinteger(L, tv.tv_usec);
lua_rawset(L, -3);
return 1;
}
/* This functions expects a Lua string as HTTP date, parse it and
* returns an integer containing the epoch format of the date, or
* nil if the parsing fails.
*/
static int hlua_parse_date(lua_State *L, int (*fcn)(const char *, int, struct tm*))
{
const char *str;
size_t len;
struct tm tm;
time_t time;
str = luaL_checklstring(L, 1, &len);
if (!fcn(str, len, &tm)) {
lua_pushnil(L);
return 1;
}
/* This function considers the content of the broken-down time
* is exprimed in the UTC timezone. timegm don't care about
* the gnu variable tm_gmtoff. If gmtoff is set, or if you know
* the timezone from the broken-down time, it must be fixed
* after the conversion.
*/
time = my_timegm(&tm);
if (time == -1) {
lua_pushnil(L);
return 1;
}
lua_pushinteger(L, (int)time);
return 1;
}
static int hlua_http_date(lua_State *L)
{
return hlua_parse_date(L, parse_http_date);
}
static int hlua_imf_date(lua_State *L)
{
return hlua_parse_date(L, parse_imf_date);
}
static int hlua_rfc850_date(lua_State *L)
{
return hlua_parse_date(L, parse_rfc850_date);
}
static int hlua_asctime_date(lua_State *L)
{
return hlua_parse_date(L, parse_asctime_date);
}
static int hlua_get_info(lua_State *L)
{
int i;
stats_fill_info(stats, STATS_LEN, 0);
lua_newtable(L);
for (i=0; i<ST_I_INF_MAX; i++) {
lua_pushstring(L, stat_cols_info[i].name);
hlua_fcn_pushfield(L, &stats[i]);
lua_settable(L, -3);
}
return 1;
}
static struct hlua_concat *hlua_check_concat(lua_State *L, int ud)
{
return (hlua_checkudata(L, ud, class_concat_ref));
}
static int hlua_concat_add(lua_State *L)
{
struct hlua_concat *b;
char *buffer;
char *new;
const char *str;
size_t l;
/* First arg must be a concat object. */
b = hlua_check_concat(L, 1);
/* Second arg must be a string. */
str = luaL_checklstring(L, 2, &l);
/* Get the buffer. */
lua_rawgeti(L, 1, 1);
buffer = lua_touserdata(L, -1);
lua_pop(L, 1);
/* Update the buffer size if it s required. The old buffer
* is crushed by the new in the object array, so it will
* be deleted by the GC.
* Note that in the first loop, the "new" variable is only
* used as a flag.
*/
new = NULL;
while (b->size - b->len < l) {
b->size += HLUA_CONCAT_BLOCSZ;
new = buffer;
}
if (new) {
new = lua_newuserdata(L, b->size);
memcpy(new, buffer, b->len);
lua_rawseti(L, 1, 1);
buffer = new;
}
/* Copy string, and update metadata. */
memcpy(buffer + b->len, str, l);
b->len += l;
return 0;
}
static int hlua_concat_dump(lua_State *L)
{
struct hlua_concat *b;
char *buffer;
/* First arg must be a concat object. */
b = hlua_check_concat(L, 1);
/* Get the buffer. */
lua_rawgeti(L, 1, 1);
buffer = lua_touserdata(L, -1);
lua_pop(L, 1);
/* Push the soncatenated string in the stack. */
lua_pushlstring(L, buffer, b->len);
return 1;
}
int hlua_concat_new(lua_State *L)
{
struct hlua_concat *b;
lua_newtable(L);
b = lua_newuserdata(L, sizeof(*b));
b->size = HLUA_CONCAT_BLOCSZ;
b->len = 0;
lua_rawseti(L, -2, 0);
lua_newuserdata(L, HLUA_CONCAT_BLOCSZ);
lua_rawseti(L, -2, 1);
lua_rawgeti(L, LUA_REGISTRYINDEX, class_concat_ref);
lua_setmetatable(L, -2);
return 1;
}
static int concat_tostring(lua_State *L)
{
const void *ptr = lua_topointer(L, 1);
lua_pushfstring(L, "Concat object: %p", ptr);
return 1;
}
static void hlua_concat_init(lua_State *L)
{
/* Creates the buffered concat object. */
lua_newtable(L);
lua_pushstring(L, "__tostring");
lua_pushcclosure(L, concat_tostring, 0);
lua_settable(L, -3);
lua_pushstring(L, "__index"); /* Creates the index entry. */
lua_newtable(L); /* The "__index" content. */
lua_pushstring(L, "add");
lua_pushcclosure(L, hlua_concat_add, 0);
lua_settable(L, -3);
lua_pushstring(L, "dump");
lua_pushcclosure(L, hlua_concat_dump, 0);
lua_settable(L, -3);
lua_settable(L, -3); /* Sets the __index entry. */
class_concat_ref = luaL_ref(L, LUA_REGISTRYINDEX);
}
/* C backing storage for lua Queue class */
struct hlua_queue {
uint32_t size;
struct mt_list list;
struct mt_list wait_tasks;
};
/* used to store lua objects in queue->list */
struct hlua_queue_item {
int ref; /* lua object reference id */
struct mt_list list;
};
/* used to store wait entries in queue->wait_tasks */
struct hlua_queue_wait
{
struct task *task;
struct mt_list entry;
};
/* This is the memory pool containing struct hlua_queue_item (queue items)
*/
DECLARE_STATIC_POOL(pool_head_hlua_queue, "hlua_queue", sizeof(struct hlua_queue_item));
/* This is the memory pool containing struct hlua_queue_wait
* (queue waiting tasks)
*/
DECLARE_STATIC_POOL(pool_head_hlua_queuew, "hlua_queuew", sizeof(struct hlua_queue_wait));
static struct hlua_queue *hlua_check_queue(lua_State *L, int ud)
{
return hlua_checkudata(L, ud, class_queue_ref);
}
/* queue:size(): returns an integer containing the current number of queued
* items.
*/
static int hlua_queue_size(lua_State *L)
{
struct hlua_queue *queue = hlua_check_queue(L, 1);
BUG_ON(!queue);
lua_pushinteger(L, HA_ATOMIC_LOAD(&queue->size));
return 1;
}
/* queue:push(): push an item (any type, except nil) at the end of the queue
*
* Returns boolean:true for success and boolean:false on error
*/
static int hlua_queue_push(lua_State *L)
{
struct hlua_queue *queue = hlua_check_queue(L, 1);
struct hlua_queue_item *item;
struct mt_list *elt1, elt2;
struct hlua_queue_wait *waiter;
if (lua_gettop(L) != 2 || lua_isnoneornil(L, 2)) {
luaL_error(L, "unexpected argument");
/* not reached */
return 0;
}
BUG_ON(!queue);
item = pool_alloc(pool_head_hlua_queue);
if (!item) {
/* memory error */
lua_pushboolean(L, 0);
return 1;
}
/* get a reference from lua object at the top of the stack */
item->ref = hlua_ref(L);
/* push new entry to the queue */
MT_LIST_INIT(&item->list);
HA_ATOMIC_INC(&queue->size);
MT_LIST_APPEND(&queue->list, &item->list);
/* notify tasks waiting on queue:pop_wait() (if any) */
mt_list_for_each_entry_safe(waiter, &queue->wait_tasks, entry, elt1, elt2) {
task_wakeup(waiter->task, TASK_WOKEN_MSG);
}
lua_pushboolean(L, 1);
return 1;
}
/* internal queue pop helper, returns 1 if it successfully popped an item
* from the queue and pushed it on lua stack.
*
* Else it returns 0 (nothing is pushed on the stack)
*/
static int _hlua_queue_pop(lua_State *L, struct hlua_queue *queue)
{
struct hlua_queue_item *item;
item = MT_LIST_POP(&queue->list, typeof(item), list);
if (!item)
return 0; /* nothing in queue */
HA_ATOMIC_DEC(&queue->size);
/* push lua obj on the stack */
hlua_pushref(L, item->ref);
/* obj ref should be released right away since it was pushed
* on the stack and will not be used anymore
*/
hlua_unref(L, item->ref);
/* free the queue item */
pool_free(pool_head_hlua_queue, item);
return 1;
}
/* queue:pop(): returns the first item at the top of que queue or nil if
* the queue is empty.
*/
static int hlua_queue_pop(lua_State *L)
{
struct hlua_queue *queue = hlua_check_queue(L, 1);
BUG_ON(!queue);
if (!_hlua_queue_pop(L, queue)) {
/* nothing in queue, push nil */
lua_pushnil(L);
}
return 1; /* either item or nil is at the top of the stack */
}
/* queue:pop_wait(): same as queue:pop() but doesn't return on empty queue.
*
* Aborts if used incorrectly and returns nil in case of memory error.
*/
static int _hlua_queue_pop_wait(lua_State *L, int status, lua_KContext ctx)
{
struct hlua_queue *queue = hlua_check_queue(L, 1);
struct hlua_queue_wait *wait = lua_touserdata(L, 2);
/* new pop attempt */
if (!_hlua_queue_pop(L, queue)) {
hlua_yieldk(L, 0, 0, _hlua_queue_pop_wait, TICK_ETERNITY, 0); // wait retry
return 0; // never reached, yieldk won't return
}
/* remove task from waiting list */
MT_LIST_DELETE(&wait->entry);
pool_free(pool_head_hlua_queuew, wait);
return 1; // success
}
static int hlua_queue_pop_wait(lua_State *L)
{
struct hlua_queue *queue = hlua_check_queue(L, 1);
struct hlua_queue_wait *wait;
struct hlua *hlua;
BUG_ON(!queue);
/* Get hlua struct, or NULL if we execute from main lua state */
hlua = hlua_gethlua(L);
if (!hlua || HLUA_CANT_YIELD(hlua)) {
luaL_error(L, "pop_wait() may only be used within task context "
"(requires yielding)");
return 0; /* not reached */
}
/* try opportunistic pop (there could already be pending items) */
if (_hlua_queue_pop(L, queue))
return 1; // success
/* no pending items, waiting required */
wait = pool_alloc(pool_head_hlua_queuew);
if (!wait) {
lua_pushnil(L);
return 1; /* memory error, return nil */
}
wait->task = hlua->task;
MT_LIST_INIT(&wait->entry);
/* add task to queue's wait list */
MT_LIST_TRY_APPEND(&queue->wait_tasks, &wait->entry);
/* push wait entry at index 2 on the stack (queue is already there) */
lua_pushlightuserdata(L, wait);
/* Go to waiting loop which immediately performs a new attempt to make
* sure we didn't miss a push during the wait entry initialization.
*
* _hlua_queue_pop_wait() won't return to us if it has to yield, which
* is the most likely scenario. What happens in this case is that yieldk
* call never returns, and instead Lua will call the continuation
* function after a successful resume, so the calling function will
* no longer be us, but Lua instead. And when the continuation function
* eventually returns (because it successfully popped an item), Lua will
* directly give the hand back to the Lua function that called us.
*
* More info here: https://www.lua.org/manual/5.4/manual.html#4.7
*/
return _hlua_queue_pop_wait(L, LUA_OK, 0);
}
static int hlua_queue_new(lua_State *L)
{
struct hlua_queue *q;
lua_newtable(L);
/* set class metatable */
lua_rawgeti(L, LUA_REGISTRYINDEX, class_queue_ref);
lua_setmetatable(L, -2);
/* index:0 is queue userdata (c data) */
q = lua_newuserdata(L, sizeof(*q));
MT_LIST_INIT(&q->list);
MT_LIST_INIT(&q->wait_tasks);
q->size = 0;
lua_rawseti(L, -2, 0);
/* class methods */
hlua_class_function(L, "size", hlua_queue_size);
hlua_class_function(L, "pop", hlua_queue_pop);
hlua_class_function(L, "pop_wait", hlua_queue_pop_wait);
hlua_class_function(L, "push", hlua_queue_push);
return 1;
}
static int hlua_queue_gc(struct lua_State *L)
{
struct hlua_queue *queue = hlua_check_queue(L, 1);
struct hlua_queue_wait *wait;
struct hlua_queue_item *item;
/* Purge waiting tasks (if any)
*
* It is normally not expected to have waiting tasks, except if such
* task has been aborted while in the middle of a queue:pop_wait()
* function call.
*/
while ((wait = MT_LIST_POP(&queue->wait_tasks, typeof(wait), entry))) {
/* free the wait entry */
pool_free(pool_head_hlua_queuew, wait);
}
/* purge remaining (unconsumed) items in the queue */
while ((item = MT_LIST_POP(&queue->list, typeof(item), list))) {
/* free the queue item */
pool_free(pool_head_hlua_queue, item);
}
/* queue (userdata) will automatically be freed by lua gc */
return 0;
}
static void hlua_queue_init(lua_State *L)
{
/* Creates the queue object. */
lua_newtable(L);
hlua_class_function(L, "__gc", hlua_queue_gc);
class_queue_ref = luaL_ref(L, LUA_REGISTRYINDEX);
}
int hlua_fcn_new_stktable(lua_State *L, struct stktable *tbl)
{
lua_newtable(L);
/* Pop a class stktbl metatable and affect it to the userdata. */
lua_rawgeti(L, LUA_REGISTRYINDEX, class_stktable_ref);
lua_setmetatable(L, -2);
lua_pushlightuserdata(L, tbl);
lua_rawseti(L, -2, 0);
return 1;
}
static struct stktable *hlua_check_stktable(lua_State *L, int ud)
{
return hlua_checkudata(L, ud, class_stktable_ref);
}
/* Extract stick table attributes into Lua table */
int hlua_stktable_info(lua_State *L)
{
struct stktable *tbl;
int dt;
tbl = hlua_check_stktable(L, 1);
if (!tbl->id) {
lua_pushnil(L);
return 1;
}
lua_newtable(L);
lua_pushstring(L, "type");
lua_pushstring(L, stktable_types[tbl->type].kw);
lua_settable(L, -3);
lua_pushstring(L, "length");
lua_pushinteger(L, tbl->key_size);
lua_settable(L, -3);
lua_pushstring(L, "size");
hlua_fcn_pushunsigned(L, tbl->size);
lua_settable(L, -3);
lua_pushstring(L, "used");
hlua_fcn_pushunsigned(L, tbl->current);
lua_settable(L, -3);
lua_pushstring(L, "nopurge");
lua_pushboolean(L, tbl->nopurge > 0);
lua_settable(L, -3);
lua_pushstring(L, "expire");
lua_pushinteger(L, tbl->expire);
lua_settable(L, -3);
/* Save data types periods (if applicable) in 'data' table */
lua_pushstring(L, "data");
lua_newtable(L);
for (dt = 0; dt < STKTABLE_DATA_TYPES; dt++) {
if (tbl->data_ofs[dt] == 0)
continue;
lua_pushstring(L, stktable_data_types[dt].name);
if (stktable_data_types[dt].arg_type == ARG_T_DELAY)
lua_pushinteger(L, tbl->data_arg[dt].u);
else
lua_pushinteger(L, -1);
lua_settable(L, -3);
}
lua_settable(L, -3);
return 1;
}
/* Helper to get extract stick table entry into Lua table */
static void hlua_stktable_entry(lua_State *L, struct stktable *t, struct stksess *ts)
{
int dt;
void *ptr;
for (dt = 0; dt < STKTABLE_DATA_TYPES; dt++) {
ptr = stktable_data_ptr(t, ts, dt);
if (!ptr)
continue;
lua_pushstring(L, stktable_data_types[dt].name);
switch (stktable_data_types[dt].std_type) {
case STD_T_SINT:
lua_pushinteger(L, stktable_data_cast(ptr, std_t_sint));
break;
case STD_T_UINT:
hlua_fcn_pushunsigned(L, stktable_data_cast(ptr, std_t_uint));
break;
case STD_T_ULL:
hlua_fcn_pushunsigned_ll(L, stktable_data_cast(ptr, std_t_ull));
break;
case STD_T_FRQP:
lua_pushinteger(L, read_freq_ctr_period(&stktable_data_cast(ptr, std_t_frqp),
t->data_arg[dt].u));
break;
case STD_T_DICT: {
struct dict_entry *de;
de = stktable_data_cast(ptr, std_t_dict);
lua_pushstring(L, de ? (char *)de->value.key : "-");
break;
}
}
lua_settable(L, -3);
}
}
/* Looks in table <t> for a sticky session matching key <key>
* Returns table with session data or nil
*
* The returned table always contains 'use' and 'expire' (integer) fields.
* For frequency/rate counters, each data entry is returned as table with
* 'value' and 'period' fields.
*/
int hlua_stktable_lookup(lua_State *L)
{
struct stktable *t;
struct sample smp;
struct stktable_key *skey;
struct stksess *ts;
t = hlua_check_stktable(L, 1);
smp.data.type = SMP_T_STR;
smp.flags = SMP_F_CONST;
smp.data.u.str.area = (char *)lua_tolstring(L, 2, &smp.data.u.str.data);
skey = smp_to_stkey(&smp, t);
if (!skey) {
lua_pushnil(L);
return 1;
}
ts = stktable_lookup_key(t, skey);
if (!ts) {
lua_pushnil(L);
return 1;
}
lua_newtable(L);
lua_pushstring(L, "use");
lua_pushinteger(L, HA_ATOMIC_LOAD(&ts->ref_cnt) - 1);
lua_settable(L, -3);
lua_pushstring(L, "expire");
lua_pushinteger(L, tick_remain(now_ms, ts->expire));
lua_settable(L, -3);
hlua_stktable_entry(L, t, ts);
HA_ATOMIC_DEC(&ts->ref_cnt);
return 1;
}
struct stk_filter {
long long val;
int type;
int op;
};
/* Helper for returning errors to callers using Lua convention (nil, err) */
static int hlua_error(lua_State *L, const char *fmt, ...) {
char buf[256];
int len;
va_list args;
va_start(args, fmt);
len = vsnprintf(buf, sizeof(buf), fmt, args);
va_end(args);
if (len < 0) {
ha_alert("hlua_error(): Could not write error message.\n");
lua_pushnil(L);
return 1;
} else if (len >= sizeof(buf))
ha_alert("hlua_error(): Error message was truncated.\n");
lua_pushnil(L);
lua_pushstring(L, buf);
return 2;
}
/* Dump the contents of stick table <t>*/
int hlua_stktable_dump(lua_State *L)
{
struct stktable *t;
struct ebmb_node *eb;
struct ebmb_node *n;
struct stksess *ts;
int type;
int op;
int dt;
long long val;
struct stk_filter filter[STKTABLE_FILTER_LEN];
int filter_count = 0;
int i;
int skip_entry;
void *ptr;
int shard = 0; // FIXME: this should be stored in the context and iterate to scan the table
t = hlua_check_stktable(L, 1);
type = lua_type(L, 2);
switch (type) {
case LUA_TNONE:
case LUA_TNIL:
break;
case LUA_TTABLE:
lua_pushnil(L);
while (lua_next(L, 2) != 0) {
int entry_idx = 0;
if (filter_count >= STKTABLE_FILTER_LEN)
return hlua_error(L, "Filter table too large (len > %d)", STKTABLE_FILTER_LEN);