-
Notifications
You must be signed in to change notification settings - Fork 209
/
sp.c
7398 lines (6767 loc) · 217 KB
/
sp.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
/*
Copyright 2015 Bloomberg Finance L.P.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <limits.h>
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stddef.h>
#include <ctype.h>
#include <arpa/inet.h>
#include <alloca.h>
#include <poll.h>
#include <unistd.h>
#include <math.h>
#include <sqlite3.h>
#include <sqliteInt.h>
#include <comdb2.h>
#include <reqlog.h>
#include <sqlglue.h>
#include <types.h>
#include <sql.h>
#include <sqlinterfaces.h>
#include <sqloffload.h>
#include <flibc.h>
#include <sqlresponse.pb-c.h>
#include <str0.h>
#include <bdb_api.h>
#include <bdb_queue.h>
#include <strbuf.h>
#include <cson.h>
#include <translistener.h>
#include <net_types.h>
#include <locks.h>
#include <trigger.h>
#include <thread_malloc.h>
#include <uuid/uuid.h>
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
#include <sp_int.h>
#include <luaglue.h>
#include <luautil.h>
#include <logmsg.h>
#include <tohex.h>
#include <ctrace.h>
#include <bb_oscompat.h>
#include <comdb2_atomic.h>
#include <sql_stmt_cache.h>
#include <debug_switches.h>
#include <string_ref.h>
#ifdef WITH_RDKAFKA
#include "librdkafka/rdkafka.h" /* for Kafka driver */
#endif
#include <event2/util.h> /* missing timeradd on aix */
#include <carray.h>
#include <trigger_main.h>
extern int gbl_dump_sql_dispatched; /* dump all sql strings dispatched */
extern int gbl_return_long_column_names;
extern int gbl_max_sqlcache;
extern int gbl_lua_new_trans_model;
extern int gbl_max_lua_instructions;
extern int gbl_lua_version;
extern int gbl_notimeouts;
extern int gbl_epoch_time;
extern int gbl_allow_lua_print;
extern int gbl_allow_lua_dynamic_libs;
extern int gbl_lua_prepare_max_retries;
extern int gbl_lua_prepare_retry_sleep;
pthread_t gbl_break_lua;
int gbl_break_all_lua = 0;
char *gbl_break_spname;
void *debug_clnt;
pthread_mutex_t lua_debug_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t lua_debug_cond = PTHREAD_COND_INITIALIZER;
struct tmptbl_info_t {
struct temptable tbl;
char *sql;
char name[MAXTABLELEN * 2]; // namespace.name
pthread_mutex_t *lk;
LIST_ENTRY(tmptbl_info_t) entries;
};
typedef struct {
DBTYPES_COMMON;
} db_t;
typedef struct {
DBTYPES_COMMON;
SP parent;
int is_temp_tbl;
char table_name[MAXTABLELEN * 2]; // namespace.name
} dbtable_t;
struct dbstmt_t {
DBTYPES_COMMON;
sqlite3_stmt *stmt;
int rows_changed;
uint16_t num_tbls;
uint8_t readonly;
uint8_t fetched;
uint8_t initial; // 1: stmt tables are locked
struct sql_state *rec; // only db:prepare will set
LIST_ENTRY(dbstmt_t) entries;
};
typedef enum {
THREAD_STATUS_DISPATCH_WAITING,
THREAD_STATUS_DISPATCH_FAILED,
THREAD_STATUS_RUNNING,
THREAD_STATUS_FINISHED,
THREAD_STATUS_JOINED
} thread_status;
struct dbthread_type {
pthread_mutex_t lua_thread_mutex;
pthread_cond_t lua_thread_cond;
thread_status status;
char error[128];
struct sqlclntstate clnt;
LIST_ENTRY(dbthread_type) entries;
};
typedef struct {
DBTYPES_COMMON;
dbthread_type *dbthd;
}dbthread_t;
struct dbconsumer_t {
DBTYPES_COMMON;
int osql_max_trans;
struct ireq iq;
struct bdb_queue_cursor last;
struct bdb_queue_cursor fnd;
genid_t genid;
int push_tid;
int push_seq;
int push_epoch;
int register_timeoutms;
int emit_timeoutms;
time_t registration_time;
const char *type;
/* signaling from libdb on qdb insert */
pthread_mutex_t *lock;
pthread_cond_t *cond;
const uint8_t *status;
struct __db_trigger_subscription *hndl;
trigger_reg_t info; // must be last in struct
};
struct qfound {
struct bdb_queue_found *item;
long long seq;
};
static int db_reset(Lua);
static SP create_sp(char **err);
static int push_trigger_args_int(Lua, dbconsumer_t *, struct qfound *, char **);
static void reset_sp(SP);
static void setup_clnt_for_sp(struct sqlclntstate *);
static const int dbq_delay_ms = 1000; // ms
static struct timespec setup_dbq_ts(int delay_ms)
{
struct timeval a, b, c;
if (delay_ms > dbq_delay_ms) {
delay_ms = dbq_delay_ms;
}
a.tv_sec = delay_ms / 1000;
a.tv_usec = (delay_ms % 1000) * 1000;
gettimeofday(&b, NULL);
evutil_timeradd(&a, &b, &c);
struct timespec t = {.tv_sec = c.tv_sec, .tv_nsec = c.tv_usec * 1000};
return t;
}
#define getdb(x) (x)->thd->sqldb
#define dbconsumer_sz(spname) \
(sizeof(dbconsumer_t) - sizeof(trigger_reg_t) + trigger_reg_sz(spname))
static int db_exec(Lua);
static int dbstmt_emit(Lua);
static void add_tran_funcs(Lua);
static void remove_thd_funcs(Lua);
/*
** n1: namespace - main, temp, fdb ...
** n2: unqualified table name
*/
static int two_part_tbl_name(const char *name, char *n1, char *n2)
{
char *dot;
if ((dot = strstr(name, ".")) != NULL) {
if (dot - name >= MAXTABLELEN) {
return -1;
}
strncpy0(n1, name, dot - name + 1);
++dot;
if (strlen(dot) >= MAXTABLELEN) {
return -1;
}
strcpy(n2, dot);
} else {
if (strlen(name) >= MAXTABLELEN) {
return -1;
}
strcpy(n1, "");
strcpy(n2, name);
}
return 0;
}
static void query_tbl_name(const char *name, char *n1, char *sep, char *n2)
{
two_part_tbl_name(name, n1, n2);
if (strcmp(n1, "") == 0)
strcpy(sep, "");
else
strcpy(sep, ".");
}
//////////////////////////////////
// Borrowed from sqlite/shell.c //
//////////////////////////////////
/*
** An object used to read a CSV file
*/
typedef struct CSVReader CSVReader;
struct CSVReader {
// const char *zFile; /* Name of the input file */
// FILE *in; /* Read the CSV text from this input stream */
Lua lua;
const char *in;
size_t pos;
char *z; /* Accumulated text for a field */
int n; /* Number of bytes in z */
int nAlloc; /* Space allocated for z[] */
int nLine; /* Current line number */
int cTerm; /* Character that terminated the most recent field */
int cSeparator; /* The separator character. (Usually ",") */
};
/* Append a single byte to z[] */
static void csv_append_char(CSVReader *p, int c)
{
if (p->n + 1 >= p->nAlloc) {
p->nAlloc += p->nAlloc + 100;
p->z = realloc(p->z, p->nAlloc);
if (p->z == 0) {
logmsg(LOGMSG_FATAL, "out of memory\n");
exit(1);
}
}
p->z[p->n++] = (char)c;
}
/* Read a single field of CSV text. Compatible with rfc4180 and extended
** with the option of having a separator other than ",".
**
** + Input comes from p->in.
** + Store results in p->z of length p->n. Space to hold p->z comes
** from sqlite3_malloc().
** + Use p->cSep as the separator. The default is ",".
** + Keep track of the line number in p->nLine.
** + Store the character that terminates the field in p->cTerm. Store
** EOF on end-of-file.
** + Report syntax errors on stderr
*/
static char *csv_read_one_field(CSVReader *p)
{
int c, pc, ppc;
int cSep = p->cSeparator;
p->n = 0;
// c = fgetc(p->in);
c = p->in[p->pos++];
if (c == 0 /* || seenInterrupt */) {
p->cTerm = 0;
return 0;
}
if (c == '"') {
int startLine = p->nLine;
int cQuote = c;
pc = ppc = 0;
while (1) {
// c = fgetc(p->in);
c = p->in[p->pos++];
if (c == '\n') p->nLine++;
if (c == cQuote) {
if (pc == cQuote) {
pc = 0;
continue;
}
}
if ((c == cSep && pc == cQuote) || (c == '\n' && pc == cQuote) ||
(c == '\n' && pc == '\r' && ppc == cQuote) ||
(c == 0 && pc == cQuote)) {
do {
p->n--;
} while (p->z[p->n] != cQuote);
p->cTerm = c;
break;
}
if (pc == cQuote && c != '\r') {
free(p->z);
luabb_error(p->lua, NULL,
"CSV line:%d: unescaped %c character\n", p->nLine,
cQuote);
}
if (c == 0) {
free(p->z);
luabb_error(p->lua, NULL,
"CSV line:%d: unterminated %c-quoted field\n",
p->nLine, startLine, cQuote);
p->cTerm = 0;
break;
}
csv_append_char(p, c);
ppc = pc;
pc = c;
}
} else {
while (c != 0 && c != cSep && c != '\n') {
csv_append_char(p, c);
// c = fgetc(p->in);
c = p->in[p->pos++];
}
if (c == '\n') {
p->nLine++;
if (p->n > 0 && p->z[p->n - 1] == '\r') p->n--;
}
p->cTerm = c;
}
if (p->z) p->z[p->n] = 0;
return p->z;
}
static int check_retry_conditions(Lua L, trigger_reg_t *reg, int skip_incoherent)
{
SP sp = getsp(L);
if (db_is_exiting()) {
luabb_error(L, sp, "database exiting");
return -1;
}
if (peer_dropped_connection(sp->clnt)) {
luabb_error(L, sp, "client disconnect");
return -2;
}
if (bdb_curtran_has_waiters(thedb->bdb_env, sp->clnt->dbtran.cursor_tran) || bdb_lock_desired(thedb->bdb_env)) {
int rc;
if ((rc = recover_deadlock(thedb->bdb_env, sp->clnt, NULL, 0)) != 0) {
luabb_error(L, sp, "recover deadlock failed");
return -3;
}
}
if (skip_incoherent) {
return 0;
}
if (!bdb_am_i_coherent(thedb->bdb_env)) {
luabb_error(L, sp, "incoherent server");
return -4;
}
return 0;
}
static pthread_mutex_t consumer_sqlthds_mutex = PTHREAD_MUTEX_INITIALIZER;
static int luabb_trigger_register(Lua L, trigger_reg_t *reg, int register_timeoutms)
{
int rc;
SP sp = getsp(L);
sp->num_instructions = 0;
int retry = round(register_timeoutms / 1000.0);
if (retry <= 0) {
retry = 1;
}
struct thdpool *pool = get_sql_pool(sp->clnt);
Pthread_mutex_lock(&consumer_sqlthds_mutex);
thdpool_add_waitthd(pool);
Pthread_mutex_unlock(&consumer_sqlthds_mutex);
while ((rc = trigger_register_req(reg)) != CDB2_TRIG_REQ_SUCCESS) {
/* trigger_register_req() can take up to 1 second. Tick up immediately
after this so that it's guaranteed that the appsock thread observes
a good query state for the next heartbeat. */
comdb2_sql_tick_no_recover_deadlock();
if (register_timeoutms) {
if (retry == 0) {
luabb_error(L, sp, "trigger:%s registration timeout %dms", reg->spname, register_timeoutms);
rc = -2;
goto out;
}
--retry;
}
if (check_retry_conditions(L, reg, 1) != 0) {
rc = luabb_error(L, sp, sp->error);
goto out;
}
if (rc != NET_SEND_FAIL_TIMEOUT) {
sleep(1);
comdb2_sql_tick_no_recover_deadlock();
}
}
out:
Pthread_mutex_lock(&consumer_sqlthds_mutex);
thdpool_remove_waitthd(pool);
Pthread_mutex_unlock(&consumer_sqlthds_mutex);
return rc;
}
static void luabb_trigger_unregister(Lua L, dbconsumer_t *q)
{
if (q->lock) {
Pthread_mutex_lock(q->lock);
if (*q->status != TRIGGER_SUBSCRIPTION_CLOSED) {
bdb_trigger_unsubscribe(q->iq.usedb->handle, q->hndl);
}
Pthread_mutex_unlock(q->lock);
}
int retry = 10;
do {
int rc = trigger_unregister_req(&q->info);
if (rc == CDB2_TRIG_REQ_SUCCESS || rc == CDB2_TRIG_ASSIGNED_OTHER) return;
if (L) check_retry_conditions(L, &q->info, 1);
} while (--retry);
}
static int stop_waiting(Lua L, dbconsumer_t *q)
{
if (check_retry_conditions(L, &q->info, 0) != 0)
return 1;
time_t now = time(NULL);
if (difftime(now, q->registration_time) <= 0) {
return 0;
}
SP sp = getsp(L);
if (sp->pingpong == 2) {
return 0;
}
if (luabb_trigger_register(L, &q->info, q->register_timeoutms) !=
CDB2_TRIG_REQ_SUCCESS)
return 1;
q->registration_time = time(NULL);
return 0;
}
static void ping(Lua L)
{
SP sp = getsp(L);
sp->pingpong = 1;
}
static void pong(Lua L, dbconsumer_t *q)
{
SP sp = getsp(L);
struct sqlclntstate *clnt = sp->clnt;
int timeout = q->emit_timeoutms / 1000;
if (q->emit_timeoutms && timeout == 0) {
timeout = 1;
}
while (1) {
switch (read_response(clnt, RESPONSE_PING_PONG, NULL, 0)) {
case 0: sp->pingpong = 0; return;
case -1: if (stop_waiting(L, q)) luaL_error(L, sp->error); break;
case -2: luaL_error(L, "client disconnect");
case -3: luaL_error(L, "client protocol error");
default: luaL_error(L, "failed reading event ack from client");
}
if (q->emit_timeoutms) {
if (timeout) {
--timeout;
} else if (sp->pingpong == 1) {
logmsg(LOGMSG_USER,
"%s:%s suspending heartbeat timeout:%dms\n",
q->type, q->info.spname, q->emit_timeoutms);
sp->pingpong = 2;
}
}
}
}
static int dbtype_to_client_type(lua_dbtypes_t *t)
{
switch (t->dbtype) {
case DBTYPES_INTEGER: return SQLITE_INTEGER;
case DBTYPES_DECIMAL:
case DBTYPES_CSTRING: return SQLITE_TEXT;
case DBTYPES_REAL: return SQLITE_FLOAT;
case DBTYPES_DATETIME: {
lua_datetime_t *ldt = (lua_datetime_t *)t;
return (ldt->val.prec == DTTZ_PREC_MSEC) ? SQLITE_DATETIME
: SQLITE_DATETIMEUS;
}
case DBTYPES_BLOB: return SQLITE_BLOB;
case DBTYPES_INTERVALYM: return SQLITE_INTERVAL_YM;
case DBTYPES_INTERVALDS: {
lua_intervalds_t *lds = (lua_intervalds_t *)t;
return (lds->val.u.ds.prec == DTTZ_PREC_MSEC) ? SQLITE_INTERVAL_DS
: SQLITE_INTERVAL_DSUS;
}
default: return -1;
}
}
static int lua_to_client_type(Lua lua, int idx)
{
if (lua_isnumber(lua, idx)) {
return SQLITE_FLOAT;
} else if (lua_isstring(lua, idx)) {
return SQLITE_TEXT;
} else if (lua_type(lua, idx) == LUA_TUSERDATA) {
lua_dbtypes_t *t = lua_touserdata(lua, idx);
return dbtype_to_client_type(t);
} else {
return -1;
}
}
#define col_to_idx(narg, col) lua_gettop(L) - narg + col + 1
int sp_column_type(struct response_data *arg, int col, size_t typed_stmt, int type)
{
SP parent = arg->sp->parent;
if (typed_stmt) {
parent->clnttype[col] = type;
return type;
}
if (parent->clnttype[col] > 0) {
return parent->clnttype[col];
}
if (type > 0) {
parent->clnttype[col] = type;
return type;
}
Lua L = arg->sp->lua;
int idx = col_to_idx(arg->ncols, col);
type = lua_to_client_type(L, idx);
if (type == -1) {
type = SQLITE_TEXT;
}
parent->clnttype[col] = type;
return type;
}
int sp_column_nil(struct response_data *arg, int col)
{
SP sp = arg->sp;
Lua L = sp->lua;
int idx = col_to_idx(arg->ncols, col);
return lua_isnil(L, idx) || luabb_isnull(L, idx);
}
int sp_column_val(struct response_data *arg, int col, int type, void *out)
{
SP sp = arg->sp;
Lua L = sp->lua;
int idx = col_to_idx(arg->ncols, col);
int rc = -1;
switch (type) {
case SQLITE_INTEGER: rc = luabb_tointeger_noerr(L, idx, out); break;
case SQLITE_FLOAT: rc = luabb_toreal_noerr(L, idx, out); break;
case SQLITE_DATETIME: /* fall through */
case SQLITE_DATETIMEUS: rc = luabb_todatetime_noerr(L, idx, out); break;
case SQLITE_INTERVAL_YM: rc = luabb_tointervalym_noerr(L, idx, out); break;
case SQLITE_INTERVAL_DS: /* fall through */
case SQLITE_INTERVAL_DSUS: rc = luabb_tointervalds_noerr(L, idx, out); break;
}
return rc;
}
void *sp_column_ptr(struct response_data *arg, int col, int type, size_t *len)
{
SP sp = arg->sp;
Lua L = sp->lua;
int idx = col_to_idx(arg->ncols, col);
char *c;
blob_t b;
lua_cstring_t *cs;
switch (type) {
case SQLITE_TEXT:
switch (luabb_type(L, idx)) {
case DBTYPES_LNUMBER:
case DBTYPES_LSTRING:
c = (char *)lua_tolstring(L, idx, len);
break;
case DBTYPES_CSTRING:
cs = lua_touserdata(L, idx);
c = cs->val;
*len = strlen(c);
break;
default:
c = (char *)luabb_tostring_noerr(L, idx);
if (!c) break;
c = strdup(c);
*len = strlen(c);
luabb_pushcstring_dl(L, c);
lua_replace(L, idx);
}
return c;
case SQLITE_BLOB:
if (luabb_toblob_noerr(L, idx, &b))
break;
if (luabb_type(L, idx) != DBTYPES_BLOB) {
luabb_pushblob_dl(L, &b);
lua_replace(L, idx);
}
*len = b.length;
return b.data;
}
return NULL;
}
char *sp_column_name(struct response_data *arg, int col)
{
SP parent = arg->sp->parent;
if (parent->clntname[col] == NULL) {
sqlite3_stmt *stmt = arg->stmt;
if (stmt) {
parent->clntname[col] = strdup(sqlite3_column_name(stmt, col));
} else {
size_t n = snprintf(NULL, 0, "$%d", col);
char *name = malloc(n + 1);
snprintf(name, n + 1, "$%d", col);
parent->clntname[col] = name;
}
}
return parent->clntname[col];
}
// Call with q->lock held.
// Unlocks q->lock on return.
// Returns -2:stopped -1:error 0:IX_NOTFND 1:IX_FND
// If IX_FND will push Lua table on stack.
static int dbq_poll_int(Lua L, dbconsumer_t *q)
{
SP sp = getsp(L);
struct sqlclntstate *clnt = sp->clnt;
struct qfound f = {0};
int rc = dbq_get(&q->iq, 0, &q->last, &f.item, NULL, NULL, &q->fnd, &f.seq,
bdb_get_lid_from_cursortran(clnt->dbtran.cursor_tran));
Pthread_mutex_unlock(q->lock);
if (debug_switch_test_trigger_deadlock()) {
logmsg(LOGMSG_WARN, "%s %p released q->lock\n",__func__, (void *)(intptr_t)pthread_self());
}
comdb2_sql_tick_no_recover_deadlock();
sp->num_instructions = 0;
if (rc == 0) {
char *err;
rc = push_trigger_args_int(L, q, &f, &err);
free(f.item);
if (rc != 1) {
SP sp = getsp(L);
luabb_error(L, sp, err);
free(err);
}
return rc;
}
if (rc == IX_NOTFND) {
return 0;
}
return -1;
}
static int dbq_poll(Lua L, dbconsumer_t *q, int delay_ms)
{
SP sp = getsp(L);
while (1) {
if (stop_waiting(L, q)) {
return -1;
}
int rc;
uint8_t status;
struct timespec ts;
if (debug_switch_test_trigger_deadlock()) {
logmsg(LOGMSG_WARN, "%s %p acquiring q->lock\n",__func__, (void *)(intptr_t)pthread_self());
}
Pthread_mutex_lock(q->lock);
if (debug_switch_test_trigger_deadlock()) {
logmsg(LOGMSG_WARN, "%s %p acquired q->lock\n",__func__, (void *)(intptr_t)pthread_self());
}
again: status = *q->status;
if (status == TRIGGER_SUBSCRIPTION_OPEN) {
rc = dbq_poll_int(L, q); // call will release q->lock
} else if (status == TRIGGER_SUBSCRIPTION_PAUSED) {
if (stop_waiting(L, q)) {
Pthread_mutex_unlock(q->lock);
return -1;
}
ts = setup_dbq_ts(delay_ms);
pthread_cond_timedwait(q->cond, q->lock, &ts); /* RC IGNORED */
goto again;
} else {
assert(status == TRIGGER_SUBSCRIPTION_CLOSED);
Pthread_mutex_unlock(q->lock);
rc = -2;
}
if (rc == 1) {
return rc;
}
if (rc < 0) {
luabb_error(L, sp, "failed to read from:%s rc:%d", q->info.spname, rc);
return rc;
}
if (delay_ms <= 0) {
return 0;
}
ts = setup_dbq_ts(delay_ms);
Pthread_mutex_lock(q->lock);
if (pthread_cond_timedwait(q->cond, q->lock, &ts) == 0) {
// was woken up -- try getting from queue
goto again;
}
Pthread_mutex_unlock(q->lock);
delay_ms -= dbq_delay_ms;
if (delay_ms <= 0) {
return 0;
}
}
}
// this call will block until queue item available
static int dbconsumer_get_int(Lua L, dbconsumer_t *q)
{
int rc;
while ((rc = dbq_poll(L, q, dbq_delay_ms)) == 0)
;
return rc;
}
static void dbconsumer_getargs(Lua L, dbconsumer_t *consumer)
{
luaL_checktype(L, -1, LUA_TTABLE);
lua_pushnil(L);
while (lua_next(L, -2)) {
const char *key;
int type = luabb_type(L, -2);
if (type == DBTYPES_LSTRING || type == DBTYPES_CSTRING) {
key = luabb_tostring(L, -2);
if (strcasecmp(key, "with_tid") == 0) {
if (luabb_type(L, -1) == DBTYPES_LBOOLEAN) {
consumer->push_tid = lua_toboolean(L, -1);
} else {
luaL_error(L, "bad argument for 'with_tid'");
return;
}
} else if (strcasecmp(key, "with_sequence") == 0) {
if (luabb_type(L, -1) == DBTYPES_LBOOLEAN) {
consumer->push_seq = lua_toboolean(L, -1);
} else {
luaL_error(L, "bad argument for 'with_sequence'");
return;
}
} else if (strcasecmp(key, "with_epoch") == 0) {
if (luabb_type(L, -1) == DBTYPES_LBOOLEAN) {
consumer->push_epoch = lua_toboolean(L, -1);
} else {
luaL_error(L, "bad argument for 'with_epoch'");
return;
}
} else if (strcasecmp(key, "register_timeout") == 0) {
long long timeoutms = 0;
luabb_tointeger(L, -1, &timeoutms);
if (timeoutms > 0) {
consumer->register_timeoutms = timeoutms;
}
}
}
lua_pop(L, 1);
}
lua_pop(L, 1);
}
static int dbconsumer_get(Lua L)
{
dbconsumer_t *q = luaL_checkudata(L, 1, dbtypes.dbconsumer);
int rc;
if ((rc = dbconsumer_get_int(L, q)) > 0) return rc;
return luaL_error(L, getsp(L)->error);
}
static int dbconsumer_poll(Lua L)
{
dbconsumer_t *q = luaL_checkudata(L, 1, dbtypes.dbconsumer);
lua_Number arg = luaL_checknumber(L, 2);
lua_Integer delay_ms; // ms
lua_number2integer(delay_ms, arg);
if (delay_ms < 0) {
delay_ms = 0;
}
int rc = dbq_poll(L, q, delay_ms);
if (rc >= 0) {
return rc;
}
return luaL_error(L, getsp(L)->error);
}
static inline int push_and_return(Lua L, int rc)
{
lua_pushinteger(L, rc);
return 1;
}
static const char *begin_parent(Lua);
static const char *commit_parent(Lua);
static int in_parent_trans(SP sp)
{
return (sp->in_parent_trans || !sp->make_parent_trans);
}
// _int variants don't modify lua stack, just return success/error code
static const char * db_begin_int(Lua, int *);
static const char * db_commit_int(Lua, int *);
static const char * db_rollback_int(Lua, int *);
static void reset_consumer_cursor(SP sp)
{
struct dbconsumer_t *q = sp->consumer;
if (!q) return;
sp->clnt->osql_max_trans = q->osql_max_trans;
q->genid = 0;
memset(&q->fnd, 0, sizeof(q->fnd));
memset(&q->last, 0, sizeof(q->last));
}
/*
** (1) No explicit db:begin()
** (2) Have explicit db:begin(), but no writes yet.
** Start a new transaction in either case.
** Commit transaction only for (1)
*/
static int dbconsumer_consume(Lua L)
{
dbconsumer_t *q = luaL_checkudata(L, 1, dbtypes.dbconsumer);
if (q->genid == 0) {
return push_and_return(L, -1);
}
int rc = 0;
const char *err = NULL;
SP sp = getsp(L);
struct sqlclntstate *clnt = sp->clnt;
int implicit_txn = in_parent_trans(sp);
if (implicit_txn) {
err = db_begin_int(L, &rc);
if (err || rc || clnt->intrans) {
luaL_error(L, "%s: begin intrans:%d err:%s rc:%d\n", __func__, clnt->intrans, err, rc);
}
}
if (!clnt->intrans) {
if ((rc = start_new_transaction(clnt, clnt->thd->sqlthd)) != 0) {
luaL_error(L, "%s: start_new_transaction intrans:%d err:%s rc:%d\n",
__func__, clnt->intrans, err, rc);
}
if ((rc = osql_sock_start(clnt, OSQL_SOCK_REQ, 0)) != 0) {
luaL_error(L, "%s: osql_sock_start intrans:%d err:%s rc:%d\n",
__func__, clnt->intrans, err, rc);
}
}
if ((rc = osql_dbq_consume_logic(clnt, q->info.spname, q->genid)) != 0) {
if (implicit_txn) {
err = db_rollback_int(L, &rc);
if (err || rc || clnt->intrans) {
luaL_error(L, "%s: rollback - unexpected intrans:%d err:%s rc:%d\n",
__func__, clnt->intrans, err, rc);
}
}
luaL_error(L, "%s osql_dbq_consume_logic rc:%d\n", __func__, rc);
}
if (implicit_txn) {
err = db_commit_int(L, &rc);
if (err || rc || clnt->intrans) {
luaL_error(L, "%s: commit failed intrans:%d err:%s rc:%d\n",
__func__, clnt->intrans, err, rc);
}
}
reset_consumer_cursor(sp);
return push_and_return(L, rc);
}
static int dbconsumer_next(Lua L)
{
dbconsumer_t *q = luaL_checkudata(L, 1, dbtypes.dbconsumer);
if (q->genid == 0) {
return 0;
}
SP sp = getsp(L);
if (in_parent_trans(sp)) {
/* We require explicit transaction */
return luaL_error(L, "missing transaction for next");
}
int rc;
struct sqlclntstate *clnt = sp->clnt;
if (!clnt->intrans) {
/* First write done by this txn */
rc = osql_sock_start_no_reorder(clnt, OSQL_SOCK_REQ, 0);
if (rc) {
luaL_error(L, "%s osql_sock_start rc:%d", __func__, rc);
}
clnt->intrans = 1;
}
Q4SP(qname, q->info.spname);
++clnt->osql_max_trans;
rc = osql_delrec_qdb(clnt, qname, q->genid);
if (rc) {
if (errstat_get_rc(&clnt->osql.xerr)) {
return luaL_error(L, "%s osql_delrec_qdb rc:%d err:%s", __func__, rc, errstat_get_str(&clnt->osql.xerr));
} else {
return luaL_error(L, "%s osql_delrec_qdb rc:%d", __func__, rc);
}
}
q->last = q->fnd;
return push_and_return(L, 0);
}
static int db_emit_int(Lua);
static int dbconsumer_emit(Lua L)
{
dbconsumer_t *q = luaL_checkudata(L, 1, dbtypes.dbconsumer);
lua_remove(L, 1);
ping(L);
int rc = db_emit_int(L);
pong(L, q);
return rc;
}
static int dbconsumer_emit_timeout(Lua L)
{
dbconsumer_t *q = luaL_checkudata(L, 1, dbtypes.dbconsumer);
int rc = -1;
int timeoutms = luaL_checknumber(L, 2);
if (timeoutms >= 0) {
q->emit_timeoutms = timeoutms;
rc = 0;
}
return push_and_return(L, rc);
}
static int dbconsumer_free(Lua L)
{
dbconsumer_t *q = luaL_checkudata(L, 1, dbtypes.dbconsumer);
ctrace("%s:%s %016" PRIx64 " unregister req\n", q->type, q->info.spname, q->info.trigger_cookie);
luabb_trigger_unregister(L, q);
ctrace("%s:%s %016" PRIx64 " unregister done\n", q->type, q->info.spname, q->info.trigger_cookie);
SP sp = getsp(L);
sp->clnt->osql_max_trans = q->osql_max_trans;
return 0;
}
static int l_global_undef(lua_State *lua)
{
const char *name = lua_tostring(lua, -1);
lua_pushnumber(lua, -1);
return luaL_error(lua, "Global variables not allowed (%s).", name);
}
int to_positive_index(Lua L, int idx)
{
if (idx < 0) {
idx = lua_gettop(L) + idx + 1;