-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathSQLite3_Server.cpp
2063 lines (1849 loc) · 66.6 KB
/
SQLite3_Server.cpp
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
#include <iostream> // std::cout
#include <algorithm> // std::sort
#include <vector> // std::vector
#include "re2/re2.h"
#include "re2/regexp.h"
#include "proxysql.h"
#include "cpp.h"
#include "MySQL_Logger.hpp"
#include "MySQL_Data_Stream.h"
#include "proxysql_utils.h"
#include "MySQL_Query_Processor.h"
#include "SQLite3_Server.h"
#include <search.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/time.h>
#include <time.h>
#include <string.h>
#include <assert.h>
#include <unistd.h>
#include <sys/socket.h>
#include <resolv.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <pthread.h>
#ifndef SPOOKYV2
#include "SpookyV2.h"
#define SPOOKYV2
#endif
#include <fcntl.h>
#include <sys/utsname.h>
using std::string;
#define SELECT_VERSION_COMMENT "select @@version_comment limit 1"
#define SELECT_VERSION_COMMENT_LEN 32
#define SELECT_DB_USER "select DATABASE(), USER() limit 1"
#define SELECT_DB_USER_LEN 33
#define SELECT_CHARSET_VARIOUS "select @@character_set_client, @@character_set_connection, @@character_set_server, @@character_set_database limit 1"
#define SELECT_CHARSET_VARIOUS_LEN 115
#define READ_ONLY_OFF "\x01\x00\x00\x01\x02\x23\x00\x00\x02\x03\x64\x65\x66\x00\x00\x00\x0d\x56\x61\x72\x69\x61\x62\x6c\x65\x5f\x6e\x61\x6d\x65\x00\x0c\x21\x00\x0f\x00\x00\x00\xfd\x01\x00\x1f\x00\x00\x1b\x00\x00\x03\x03\x64\x65\x66\x00\x00\x00\x05\x56\x61\x6c\x75\x65\x00\x0c\x21\x00\x0f\x00\x00\x00\xfd\x01\x00\x1f\x00\x00\x05\x00\x00\x04\xfe\x00\x00\x02\x00\x0e\x00\x00\x05\x09\x72\x65\x61\x64\x5f\x6f\x6e\x6c\x79\x03\x4f\x46\x46\x05\x00\x00\x06\xfe\x00\x00\x02\x00"
#define READ_ONLY_ON "\x01\x00\x00\x01\x02\x23\x00\x00\x02\x03\x64\x65\x66\x00\x00\x00\x0d\x56\x61\x72\x69\x61\x62\x6c\x65\x5f\x6e\x61\x6d\x65\x00\x0c\x21\x00\x0f\x00\x00\x00\xfd\x01\x00\x1f\x00\x00\x1b\x00\x00\x03\x03\x64\x65\x66\x00\x00\x00\x05\x56\x61\x6c\x75\x65\x00\x0c\x21\x00\x0f\x00\x00\x00\xfd\x01\x00\x1f\x00\x00\x05\x00\x00\x04\xfe\x00\x00\x02\x00\x0d\x00\x00\x05\x09\x72\x65\x61\x64\x5f\x6f\x6e\x6c\x79\x02\x4f\x4e\x05\x00\x00\x06\xfe\x00\x00\x02\x00"
#ifdef __APPLE__
#ifndef MSG_NOSIGNAL
#define MSG_NOSIGNAL 0
#endif // MSG_NOSIGNAL
#endif // __APPLE__
#define SAFE_SQLITE3_STEP(_stmt) do {\
do {\
rc=sqlite3_step(_stmt);\
if (rc!=SQLITE_DONE) {\
assert(rc==SQLITE_LOCKED);\
usleep(100);\
}\
} while (rc!=SQLITE_DONE);\
} while (0)
#define SAFE_SQLITE3_STEP2(_stmt) do {\
do {\
rc=sqlite3_step(_stmt);\
if (rc==SQLITE_LOCKED || rc==SQLITE_BUSY) {\
usleep(100);\
}\
} while (rc==SQLITE_LOCKED || rc==SQLITE_BUSY);\
} while (0)
/*
struct cpu_timer
{
cpu_timer() {
begin = monotonic_time();
}
~cpu_timer()
{
unsigned long long end = monotonic_time();
#ifdef DEBUG
std::cerr << double( end - begin ) / 1000000 << " secs.\n" ;
#endif
begin=end-begin; // make the compiler happy
};
unsigned long long begin;
};
*/
static char *s_strdup(char *s) {
char *ret=NULL;
if (s) {
ret=strdup(s);
}
return ret;
}
static int __SQLite3_Server_refresh_interval=1000;
extern MySQL_Query_Cache *GloMyQC;
extern MySQL_Authentication *GloMyAuth;
extern ProxySQL_Admin *GloAdmin;
extern MySQL_Query_Processor* GloMyQPro;
extern MySQL_Threads_Handler *GloMTH;
extern MySQL_Logger *GloMyLogger;
extern MySQL_Monitor *GloMyMon;
extern SQLite3_Server *GloSQLite3Server;
#define PANIC(msg) { perror(msg); exit(EXIT_FAILURE); }
static pthread_mutex_t sock_mutex = PTHREAD_MUTEX_INITIALIZER;
static char * SQLite3_Server_variables_names[] = {
(char *)"mysql_ifaces",
(char *)"read_only",
NULL
};
static void * (*child_func[1]) (void *arg);
typedef struct _main_args {
int nfds;
struct pollfd *fds;
int *callback_func;
volatile int *shutdown;
} main_args;
typedef struct _ifaces_desc_t {
char **mysql_ifaces;
} ifaces_desc_t;
#define MAX_IFACES 128
#define MAX_SQLITE3SERVER_LISTENERS 128
class ifaces_desc {
public:
PtrArray *ifaces;
ifaces_desc() {
ifaces=new PtrArray();
}
bool add(const char *iface) {
for (unsigned int i=0; i<ifaces->len; i++) {
if (strcmp((const char *)ifaces->index(i),iface)==0) {
return false;
}
}
ifaces->add(strdup(iface));
return true;
}
~ifaces_desc() {
while(ifaces->len) {
char *d=(char *)ifaces->remove_index_fast(0);
free(d);
}
delete ifaces;
}
};
class sqlite3server_main_loop_listeners {
private:
int version;
pthread_rwlock_t rwlock;
char ** reset_ifaces(char **ifaces) {
int i;
if (ifaces) {
for (i=0; i<MAX_IFACES; i++) {
if (ifaces[i]) free(ifaces[i]);
}
} else {
ifaces=(char **)malloc(sizeof(char *)*MAX_IFACES);
}
for (i=0; i<MAX_IFACES; i++) {
ifaces[i]=NULL;
}
return ifaces;
}
public:
int nfds;
struct pollfd *fds;
int *callback_func;
int get_version() { return version; }
void wrlock() {
pthread_rwlock_wrlock(&rwlock);
}
void wrunlock() {
pthread_rwlock_unlock(&rwlock);
}
ifaces_desc *ifaces_mysql;
ifaces_desc_t descriptor_new;
sqlite3server_main_loop_listeners() {
pthread_rwlock_init(&rwlock, NULL);
ifaces_mysql=new ifaces_desc();
version=0;
descriptor_new.mysql_ifaces=NULL;
}
void update_ifaces(char *list, ifaces_desc **ifd) {
wrlock();
delete *ifd;
*ifd=new ifaces_desc();
int i=0;
tokenizer_t tok;
tokenizer( &tok, list, ";", TOKENIZER_NO_EMPTIES );
const char* token;
for ( token = tokenize( &tok ) ; token && i < MAX_IFACES ; token = tokenize( &tok ) ) {
(*ifd)->add(token);
i++;
}
free_tokenizer( &tok );
version++;
wrunlock();
}
bool update_ifaces(char *list, char ***_ifaces) {
wrlock();
int i;
char **ifaces=*_ifaces;
tokenizer_t tok;
tokenizer( &tok, list, ";", TOKENIZER_NO_EMPTIES );
const char* token;
ifaces=reset_ifaces(ifaces);
i=0;
for ( token = tokenize( &tok ) ; token && i < MAX_IFACES ; token = tokenize( &tok ) ) {
ifaces[i]=(char *)malloc(strlen(token)+1);
strcpy(ifaces[i],token);
i++;
}
free_tokenizer( &tok );
version++;
wrunlock();
return true;
}
};
static sqlite3server_main_loop_listeners S_amll;
#ifdef TEST_GROUPREP
/**
* @brief Helper function that checks if the supplied string
* is a number.
* @param s The string to check.
* @return True if the supplied string is just composed of
* digits, false otherwise.
*/
bool is_number(const std::string& s) {
if (s.empty()) { return false; }
for (const auto& d : s) {
if (std::isdigit(d) == false) {
return false;
}
}
return true;
}
/**
* @brief Checks if the query matches an specified 'monitor_query' of the
* following format:
*
* "$MONITOR_QUERY" + " hostname:port"
*
* If the query matches, 'true' is returned, false otherwise.
*
* @param monitor_query Query that should be matched against the current
* supplied 'query'.
* @param query Current query, to be matched against the supplied
* 'monitor_query'.
* @return 'true' if the query matches, false otherwise.
*/
bool match_monitor_query(const std::string& monitor_query, const std::string& query) {
if (query.rfind(monitor_query, 0) != 0) {
return false;
}
std::string srv_address {
query.substr(monitor_query.size())
};
// Check that what is beyond this point, is just the servers address,
// written as an identifier 'n.n.n.n:n'.
std::size_t cur_mark_pos = 0;
for (int i = 0; i < 3; i++) {
std::size_t next_mark_pos = srv_address.find('.', cur_mark_pos);
if (next_mark_pos == std::string::npos) {
return false;
} else {
std::string number {
srv_address.substr(cur_mark_pos, next_mark_pos - cur_mark_pos)
};
if (is_number(number)) {
cur_mark_pos = next_mark_pos + 1;
} else {
return false;
}
}
}
// Check last part is also a valid number
cur_mark_pos = srv_address.find(':', cur_mark_pos);
if (cur_mark_pos == std::string::npos) {
return false;
} else {
std::string number {
srv_address.substr(cur_mark_pos + 1)
};
return is_number(number);
}
}
#endif // TEST_GROUPREP
#ifdef TEST_AURORA
using std::vector;
using aurora_hg_info_t = std::tuple<uint32_t,uint32_t,string>;
enum AURORA_HG_INFO {
WRITER_HG,
READER_HG,
DOMAIN_NAME
};
vector<aurora_hg_info_t> get_hgs_info(SQLite3DB* db) {
vector<aurora_hg_info_t> whgs {};
char* error = NULL;
int cols = 0;
int affected_rows = 0;
SQLite3_result* resultset = NULL;
GloAdmin->admindb->execute_statement(
"SELECT writer_hostgroup,reader_hostgroup,domain_name FROM mysql_aws_aurora_hostgroups",
&error, &cols, &affected_rows, &resultset
);
for (const SQLite3_row* r : resultset->rows) {
uint32_t writer_hg = atoi(r->fields[0]);
uint32_t reader_hg = atoi(r->fields[1]);
string domain_name { r->fields[2] };
whgs.push_back({writer_hg, reader_hg, domain_name});
}
return whgs;
}
#endif
void SQLite3_Server_session_handler(MySQL_Session* sess, void *_pa, PtrSize_t *pkt) {
char *error=NULL;
int cols;
int affected_rows;
bool run_query=true;
SQLite3_result *resultset=NULL;
char *strA=NULL;
char *strB=NULL;
size_t strAl, strBl;
char *query=NULL;
unsigned int query_length=pkt->size-sizeof(mysql_hdr);
query=(char *)l_alloc(query_length);
memcpy(query,(char *)pkt->ptr+sizeof(mysql_hdr)+1,query_length-1);
query[query_length-1]=0;
#if defined(TEST_AURORA) || defined(TEST_GALERA) || defined(TEST_GROUPREP) || defined(TEST_READONLY) || defined(TEST_REPLICATIONLAG)
if (sess->client_myds->proxy_addr.addr == NULL) {
struct sockaddr addr;
socklen_t addr_len=sizeof(struct sockaddr);
memset(&addr,0,addr_len);
int rc;
rc=getsockname(sess->client_myds->fd, &addr, &addr_len);
if (rc==0) {
char buf[512];
switch (addr.sa_family) {
case AF_INET: {
struct sockaddr_in *ipv4 = (struct sockaddr_in *)&addr;
inet_ntop(addr.sa_family, &ipv4->sin_addr, buf, INET_ADDRSTRLEN);
sess->client_myds->proxy_addr.addr = strdup(buf);
}
break;
case AF_INET6: {
struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)&addr;
inet_ntop(addr.sa_family, &ipv6->sin6_addr, buf, INET6_ADDRSTRLEN);
sess->client_myds->proxy_addr.addr = strdup(buf);
}
break;
default:
sess->client_myds->proxy_addr.addr = strdup("unknown");
break;
}
} else {
sess->client_myds->proxy_addr.addr = strdup("unknown");
}
}
#endif // TEST_AURORA || TEST_GALERA || TEST_GROUPREP || TEST_READONLY || TEST_REPLICATIONLAG
char *query_no_space=(char *)l_alloc(query_length);
memcpy(query_no_space,query,query_length);
unsigned int query_no_space_length=remove_spaces(query_no_space);
// fix bug #925
while (query_no_space[query_no_space_length-1]==';' || query_no_space[query_no_space_length-1]==' ') {
query_no_space_length--;
query_no_space[query_no_space_length]=0;
}
proxy_debug(PROXY_DEBUG_SQLITE, 4, "Received query on Session %p , thread_session_id %u : %s\n", sess, sess->thread_session_id, query_no_space);
{
SQLite3_Session *sqlite_sess = (SQLite3_Session *)sess->thread->gen_args;
sqlite3 *db = sqlite_sess->sessdb->get_db();
char c=((char *)pkt->ptr)[5];
bool ret=false;
if (c=='c' || c=='C') {
if (strncasecmp((char *)"commit",(char *)pkt->ptr+5,6)==0) {
if ((*proxy_sqlite3_get_autocommit)(db)==1) {
ret=true;
}
}
} else {
if (c=='r' || c=='R') {
if ( strncasecmp((char *)"rollback",(char *)pkt->ptr+5,8)==0 ) {
if ((*proxy_sqlite3_get_autocommit)(db)==1) {
ret=true;
}
}
}
}
// if there is no transactions we filter both commit and rollback
if (ret == true) {
uint16_t status=0;
if (sess->autocommit) status |= SERVER_STATUS_AUTOCOMMIT;
if ((*proxy_sqlite3_get_autocommit)(db)==0) {
status |= SERVER_STATUS_IN_TRANS;
}
GloSQLite3Server->send_MySQL_OK(&sess->client_myds->myprot, NULL, 0, status);
run_query=false;
goto __run_query;
}
}
{
SQLite3_Session *sqlite_sess = (SQLite3_Session *)sess->thread->gen_args;
sqlite3 *db = sqlite_sess->sessdb->get_db();
bool prev_autocommit = sess->autocommit;
bool autocommit_to_skip = sess->handler_SetAutocommit(pkt);
if (prev_autocommit == sess->autocommit) {
if (autocommit_to_skip==true) {
uint16_t status=0;
if (sess->autocommit) status |= SERVER_STATUS_AUTOCOMMIT;
if ((*proxy_sqlite3_get_autocommit)(db)==0) {
status |= SERVER_STATUS_IN_TRANS;
}
GloSQLite3Server->send_MySQL_OK(&sess->client_myds->myprot, NULL, 0, status);
run_query=false;
goto __run_query;
}
} else {
// autocommit changed
if (sess->autocommit == false) {
// we simply reply ok. We will create a transaction at the next query
// we defer the creation of the transaction to simulate how MySQL works
uint16_t status=0;
if (sess->autocommit) status |= SERVER_STATUS_AUTOCOMMIT;
if ((*proxy_sqlite3_get_autocommit)(db)==0) {
status |= SERVER_STATUS_IN_TRANS;
}
GloSQLite3Server->send_MySQL_OK(&sess->client_myds->myprot, NULL, 0, status);
run_query=false;
goto __run_query;
/*
l_free(query_length,query);
query = l_strdup((char *)"BEGIN IMMEDIATE");
query_length=strlen(query)+1;
goto __run_query;
*/
} else {
// setting autocommit=1
if ((*proxy_sqlite3_get_autocommit)(db)==1) {
// there is no transaction
uint16_t status=0;
if (sess->autocommit) status |= SERVER_STATUS_AUTOCOMMIT;
if ((*proxy_sqlite3_get_autocommit)(db)==0) {
status |= SERVER_STATUS_IN_TRANS;
}
GloSQLite3Server->send_MySQL_OK(&sess->client_myds->myprot, NULL, 0, status);
run_query=false;
goto __run_query;
} else {
// there is a transaction, we run COMMIT
l_free(query_length,query);
query = l_strdup((char *)"COMMIT");
query_length=strlen(query)+1;
goto __run_query;
}
}
}
}
// fix bug #1047
if (
/*
(!strncasecmp("BEGIN", query_no_space, strlen("BEGIN")))
||
(!strncasecmp("START TRANSACTION", query_no_space, strlen("START TRANSACTION")))
||
(!strncasecmp("COMMIT", query_no_space, strlen("COMMIT")))
||
(!strncasecmp("ROLLBACK", query_no_space, strlen("ROLLBACK")))
||
*/
(!strncasecmp("SET character_set_results", query_no_space, strlen("SET character_set_results")))
||
(!strncasecmp("SET SQL_AUTO_IS_NULL", query_no_space, strlen("SET SQL_AUTO_IS_NULL")))
||
(!strncasecmp("SET NAMES", query_no_space, strlen("SET NAMES")))
||
//(!strncasecmp("SET AUTOCOMMIT", query_no_space, strlen("SET AUTOCOMMIT")))
//||
(!strncasecmp("/*!40100 SET @@SQL_MODE='' */", query_no_space, strlen("/*!40100 SET @@SQL_MODE='' */")))
||
(!strncasecmp("/*!40103 SET TIME_ZONE=", query_no_space, strlen("/*!40103 SET TIME_ZONE=")))
||
(!strncasecmp("/*!80000 SET SESSION", query_no_space, strlen("/*!80000 SET SESSION")))
||
(!strncasecmp("SET SESSION", query_no_space, strlen("SET SESSION")))
||
(!strncasecmp("SET wait_timeout", query_no_space, strlen("SET wait_timeout")))
) {
SQLite3_Session *sqlite_sess = (SQLite3_Session *)sess->thread->gen_args;
sqlite3 *db = sqlite_sess->sessdb->get_db();
uint16_t status=0;
if (sess->autocommit) status |= SERVER_STATUS_AUTOCOMMIT;
if ((*proxy_sqlite3_get_autocommit)(db)==0) {
status |= SERVER_STATUS_IN_TRANS;
}
GloSQLite3Server->send_MySQL_OK(&sess->client_myds->myprot, NULL, 0, status);
run_query=false;
goto __run_query;
}
if (query_no_space_length==17) {
if (!strncasecmp((char *)"START TRANSACTION", query_no_space, query_no_space_length)) {
l_free(query_length,query);
query = l_strdup((char *)"BEGIN IMMEDIATE");
query_length=strlen(query)+1;
goto __run_query;
}
}
if (query_no_space_length==5) {
if (!strncasecmp((char *)"BEGIN", query_no_space, query_no_space_length)) {
l_free(query_length,query);
query = l_strdup((char *)"BEGIN IMMEDIATE");
query_length=strlen(query)+1;
goto __run_query;
}
}
if (query_no_space_length==SELECT_VERSION_COMMENT_LEN) {
if (!strncasecmp(SELECT_VERSION_COMMENT, query_no_space, query_no_space_length)) {
l_free(query_length,query);
#if defined(TEST_AURORA) || defined(TEST_GALERA) || defined(TEST_GROUPREP) || defined(TEST_READONLY) || defined(TEST_REPLICATIONLAG)
char *a = (char *)"SELECT '(ProxySQL Automated Test Server) - %s'";
query = (char *)malloc(strlen(a)+strlen(sess->client_myds->proxy_addr.addr));
sprintf(query,a,sess->client_myds->proxy_addr.addr);
#else
query=l_strdup("SELECT '(ProxySQL SQLite3 Server)'");
#endif // TEST_AURORA || TEST_GALERA || TEST_GROUPREP || TEST_READONLY || TEST_REPLICATIONLAG
query_length=strlen(query)+1;
goto __run_query;
}
}
if (query_no_space_length==SELECT_DB_USER_LEN) {
if (!strncasecmp(SELECT_DB_USER, query_no_space, query_no_space_length)) {
l_free(query_length,query);
char *query1=(char *)"SELECT \"admin\" AS 'DATABASE()', \"%s\" AS 'USER()'";
char *query2=(char *)malloc(strlen(query1)+strlen(sess->client_myds->myconn->userinfo->username)+10);
sprintf(query2,query1,sess->client_myds->myconn->userinfo->username);
query=l_strdup(query2);
query_length=strlen(query2)+1;
free(query2);
goto __run_query;
}
}
if (query_no_space_length==SELECT_CHARSET_VARIOUS_LEN) {
if (!strncasecmp(SELECT_CHARSET_VARIOUS, query_no_space, query_no_space_length)) {
l_free(query_length,query);
char *query1=(char *)"select 'utf8' as '@@character_set_client', 'utf8' as '@@character_set_connection', 'utf8' as '@@character_set_server', 'utf8' as '@@character_set_database' limit 1";
query=l_strdup(query1);
query_length=strlen(query1)+1;
goto __run_query;
}
}
if (!strncasecmp("SELECT @@version", query_no_space, strlen("SELECT @@version"))) {
l_free(query_length,query);
char *q=(char *)"SELECT '%s' AS '@@version'";
query_length=strlen(q)+strlen(PROXYSQL_VERSION)+20;
query=(char *)l_alloc(query_length);
sprintf(query,q,PROXYSQL_VERSION);
goto __run_query;
}
if (!strncasecmp("SELECT version()", query_no_space, strlen("SELECT version()"))) {
l_free(query_length,query);
char *q=(char *)"SELECT '%s' AS 'version()'";
query_length=strlen(q)+strlen(PROXYSQL_VERSION)+20;
query=(char *)l_alloc(query_length);
sprintf(query,q,PROXYSQL_VERSION);
goto __run_query;
}
if (strncasecmp("SHOW ", query_no_space, 5)) {
goto __end_show_commands; // in the next block there are only SHOW commands
}
if (query_no_space_length==strlen("SHOW TABLES") && !strncasecmp("SHOW TABLES",query_no_space, query_no_space_length)) {
l_free(query_length,query);
query=l_strdup("SELECT name AS tables FROM sqlite_master WHERE type='table' AND name NOT IN ('sqlite_sequence') ORDER BY name");
query_length=strlen(query)+1;
goto __run_query;
}
if ((query_no_space_length>17) && (!strncasecmp("SHOW TABLES FROM ", query_no_space, 17))) {
strA=query_no_space+17;
strAl=strlen(strA);
strB=(char *)"SELECT name AS tables FROM %s.sqlite_master WHERE type='table' AND name NOT IN ('sqlite_sequence') ORDER BY name";
strBl=strlen(strB);
int l=strBl+strAl-2;
char *b=(char *)l_alloc(l+1);
snprintf(b,l+1,strB,strA);
b[l]=0;
l_free(query_length,query);
query=b;
query_length=l+1;
goto __run_query;
}
if ((query_no_space_length>17) && (!strncasecmp("SHOW TABLES LIKE ", query_no_space, 17))) {
strA=query_no_space+17;
strAl=strlen(strA);
strB=(char *)"SELECT name AS tables FROM sqlite_master WHERE type='table' AND name LIKE '%s'";
strBl=strlen(strB);
char *tn=NULL; // tablename
tn=(char *)malloc(strAl+1);
unsigned int i=0, j=0;
while (i<strAl) {
if (strA[i]!='\\' && strA[i]!='`' && strA[i]!='\'') {
tn[j]=strA[i];
j++;
}
i++;
}
tn[j]=0;
int l=strBl+strlen(tn)-2;
char *b=(char *)l_alloc(l+1);
snprintf(b,l+1,strB,tn);
b[l]=0;
free(tn);
l_free(query_length,query);
query=b;
query_length=l+1;
goto __run_query;
}
strA=(char *)"SHOW CREATE TABLE ";
strB=(char *)"SELECT name AS 'table' , REPLACE(REPLACE(sql,' , ', X'2C0A20202020'),'CREATE TABLE %s (','CREATE TABLE %s ('||X'0A20202020') AS 'Create Table' FROM %s.sqlite_master WHERE type='table' AND name='%s'";
strAl=strlen(strA);
if (strncasecmp("SHOW CREATE TABLE ", query_no_space, strAl)==0) {
strBl=strlen(strB);
char *dbh=NULL;
char *tbh=NULL;
c_split_2(query_no_space+strAl,".",&dbh,&tbh);
if (strlen(tbh)==0) {
free(tbh);
tbh=dbh;
dbh=strdup("main");
}
if (strlen(tbh)>=3 && tbh[0]=='`' && tbh[strlen(tbh)-1]=='`') { // tablename is quoted
char *tbh_tmp=(char *)malloc(strlen(tbh)-1);
strncpy(tbh_tmp,tbh+1,strlen(tbh)-2);
tbh_tmp[strlen(tbh)-2]=0;
free(tbh);
tbh=tbh_tmp;
}
int l=strBl+strlen(tbh)*3+strlen(dbh)-8;
char *buff=(char *)l_alloc(l+1);
snprintf(buff,l+1,strB,tbh,tbh,dbh,tbh);
buff[l]=0;
free(tbh);
free(dbh);
l_free(query_length,query);
query=buff;
query_length=l+1;
goto __run_query;
}
if (
(query_no_space_length==strlen("SHOW DATABASES") && !strncasecmp("SHOW DATABASES",query_no_space, query_no_space_length))
||
(query_no_space_length==strlen("SHOW SCHEMAS") && !strncasecmp("SHOW SCHEMAS",query_no_space, query_no_space_length))
) {
l_free(query_length,query);
query=l_strdup("PRAGMA DATABASE_LIST");
query_length=strlen(query)+1;
goto __run_query;
}
__end_show_commands:
if (query_no_space_length==strlen("SELECT DATABASE()") && !strncasecmp("SELECT DATABASE()",query_no_space, query_no_space_length)) {
l_free(query_length,query);
query=l_strdup("SELECT \"main\" AS 'DATABASE()'");
query_length=strlen(query)+1;
goto __run_query;
}
// see issue #1022
if (query_no_space_length==strlen("SELECT DATABASE() AS name") && !strncasecmp("SELECT DATABASE() AS name",query_no_space, query_no_space_length)) {
l_free(query_length,query);
query=l_strdup("SELECT \"main\" AS 'DATABASE()'");
query_length=strlen(query)+1;
goto __run_query;
}
if (query_length>20 && strncasecmp(query,"SELECT",6)==0) {
if (strncasecmp(query+query_length-12," FOR UPDATE",11)==0) {
char * query_new = strndup(query,query_length-12);
l_free(query_length,query);
query_length-=11;
query = query_new;
} else if (strncasecmp(query+query_length-20," LOCK IN SHARE MODE",19)==0) {
char * query_new = strndup(query,query_length-20);
l_free(query_length,query);
query_length-=11;
query = query_new;
}
}
if (sess->session_type == PROXYSQL_SESSION_SQLITE) { // no admin
if (
(strncasecmp("PRAGMA",query_no_space,6)==0)
||
(strncasecmp("ATTACH",query_no_space,6)==0)
) {
proxy_error("[WARNING]: Commands executed from stats interface in Admin Module: \"%s\"\n", query_no_space);
GloSQLite3Server->send_MySQL_ERR(&sess->client_myds->myprot, (char *)"Command not allowed");
run_query=false;
}
}
__run_query:
if (run_query) {
#if defined(TEST_AURORA) || defined(TEST_GALERA) || defined(TEST_GROUPREP) || defined(TEST_READONLY) || defined(TEST_REPLICATIONLAG)
if (strncasecmp("SELECT",query_no_space,6)==0) {
#ifdef TEST_AURORA
if (strstr(query_no_space,(char *)"REPLICA_HOST_STATUS")) {
pthread_mutex_lock(&GloSQLite3Server->aurora_mutex);
if (strcasestr(query_no_space, TEST_AURORA_MONITOR_BASE_QUERY)) {
string s_whg { query_no_space + strlen(TEST_AURORA_MONITOR_BASE_QUERY) };
uint32_t whg = atoi(s_whg.c_str());
GloSQLite3Server->populate_aws_aurora_table(sess, whg);
vector<aurora_hg_info_t> hgs_info { get_hgs_info(GloAdmin->admindb) };
const auto match_writer = [&whg](const aurora_hg_info_t& hg_info) {
return std::get<AURORA_HG_INFO::WRITER_HG>(hg_info) == whg;
};
const auto hg_info_it = std::find_if(hgs_info.begin(), hgs_info.end(), match_writer);
string select_query {
"SELECT SERVER_ID,SESSION_ID,LAST_UPDATE_TIMESTAMP,REPLICA_LAG_IN_MILLISECONDS,CPU"
" FROM REPLICA_HOST_STATUS "
};
if (hg_info_it == hgs_info.end()) {
select_query += " LIMIT 0";
} else {
const string& domain_name { std::get<AURORA_HG_INFO::DOMAIN_NAME>(*hg_info_it) };
select_query += " WHERE DOMAIN_NAME='" + domain_name + "' ORDER BY SERVER_ID";
}
free(query);
query = static_cast<char*>(malloc(select_query.length() + 1));
strcpy(query, select_query.c_str());
}
}
#endif // TEST_AURORA
#ifdef TEST_GALERA
if (strstr(query_no_space,(char *)"HOST_STATUS_GALERA")) {
pthread_mutex_lock(&GloSQLite3Server->galera_mutex);
GloSQLite3Server->populate_galera_table(sess);
}
#endif // TEST_GALERA
#ifdef TEST_GROUPREP
if (strstr(query_no_space,(char *)"GR_MEMBER_ROUTING_CANDIDATE_STATUS")) {
pthread_mutex_lock(&GloSQLite3Server->grouprep_mutex);
GloSQLite3Server->populate_grouprep_table(sess, 0);
// NOTE: This query should be in one place that can be reused by
// 'ProxySQL_Monitor' module.
const std::string grouprep_monitor_test_query_start {
"SELECT viable_candidate,read_only,transactions_behind,members "
"FROM GR_MEMBER_ROUTING_CANDIDATE_STATUS "
};
// If the query matches 'grouprep_monitor_test_query_start', it
// means that the query has been issued by `ProxySQL_Monitor` and
// we need to fetch for the proper values and replace the query
// with one holding the values from `grouprep_map`.
if (match_monitor_query(grouprep_monitor_test_query_start, query_no_space)) {
std::string srv_addr {
query_no_space + grouprep_monitor_test_query_start.size()
};
const group_rep_status& gr_srv_status =
GloSQLite3Server->grouprep_test_value(srv_addr);
free(query);
std::string t_select_as_query {
"SELECT '%s' AS viable_candidate, '%s' AS read_only, %d AS transactions_behind, '%s' AS members"
};
std::string select_as_query {};
string_format(
t_select_as_query, select_as_query,
std::get<0>(gr_srv_status) ? "YES" : "NO",
std::get<1>(gr_srv_status) ? "YES" : "NO",
std::get<2>(gr_srv_status),
std::get<3>(gr_srv_status).c_str()
);
query = static_cast<char*>(malloc(select_as_query.length() + 1));
strcpy(query, select_as_query.c_str());
}
}
#endif // TEST_GROUPREP
#ifdef TEST_READONLY
if (strncasecmp("SELECT @@global.read_only read_only ",query_no_space, strlen("SELECT @@global.read_only read_only "))==0) {
if (strlen(query_no_space) > strlen("SELECT @@global.read_only read_only ")+5) {
pthread_mutex_lock(&GloSQLite3Server->test_readonly_mutex);
// the current test doesn't try to simulate failures, therefore it will return immediately
if (GloSQLite3Server->readonly_map_size() == 0) {
// probably never initialized
GloSQLite3Server->load_readonly_table(sess);
}
int rc = GloSQLite3Server->readonly_test_value(query_no_space+strlen("SELECT @@global.read_only read_only "));
free(query);
char *a = (char *)"SELECT %d as read_only";
query = (char *)malloc(strlen(a)+2);
sprintf(query,a,rc);
pthread_mutex_unlock(&GloSQLite3Server->test_readonly_mutex);
}
}
#endif // TEST_READONLY
#ifdef TEST_REPLICATIONLAG
if (
strncasecmp("SELECT SLAVE STATUS ", query_no_space, strlen("SELECT SLAVE STATUS ")) == 0
|| strncasecmp("SELECT REPLICA STATUS ", query_no_space, strlen("SELECT REPLICA STATUS ")) == 0
) {
uint64_t addr_offset {
strstr(query_no_space, "REPLICA") ? strlen("SELECT REPLICA STATUS ") : strlen("SELECT SLAVE STATUS ")
};
if (strlen(query_no_space) > strlen("SELECT SLAVE STATUS ") + 5) {
pthread_mutex_lock(&GloSQLite3Server->test_replicationlag_mutex);
// the current test doesn't try to simulate failures, therefore it will return immediately
if (GloSQLite3Server->replicationlag_map_size() == 0) {
// probably never initialized
GloSQLite3Server->load_replicationlag_table(sess);
}
const int* rc = GloSQLite3Server->replicationlag_test_value(query_no_space + addr_offset);
free(query);
string SELECT { "SELECT " + (rc ? std::to_string(*rc) : string { "null" }) + " AS " };
SELECT += strstr(query_no_space, "REPLICA") ? "Seconds_Behind_Source" : "Seconds_Behind_Master";
query = static_cast<char*>(malloc(SELECT.size() + 1));
sprintf(query, SELECT.c_str());
pthread_mutex_unlock(&GloSQLite3Server->test_replicationlag_mutex);
}
}
#endif // TEST_REPLICATIONLAG
if (strstr(query_no_space,(char *)"Seconds_Behind_Master")) {
free(query);
char *a = (char *)"SELECT %d as Seconds_Behind_Master";
query = (char *)malloc(strlen(a)+4);
sprintf(query,a,rand()%30+10);
}
}
#endif // TEST_AURORA || TEST_GALERA || TEST_GROUPREP || TEST_READONLY || TEST_REPLICATIONLAG
SQLite3_Session *sqlite_sess = (SQLite3_Session *)sess->thread->gen_args;
if (sess->autocommit==false) {
sqlite3 *db = sqlite_sess->sessdb->get_db();
if ((*proxy_sqlite3_get_autocommit)(db)==1) {
// we defer the creation of the transaction to simulate how MySQL works
sqlite_sess->sessdb->execute("BEGIN IMMEDIATE");
}
}
sqlite_sess->sessdb->execute_statement(query, &error , &cols , &affected_rows , &resultset);
#if defined(TEST_AURORA) || defined(TEST_GALERA) || defined(TEST_GROUPREP)
if (strncasecmp("SELECT",query_no_space,6)==0) {
#ifdef TEST_AURORA
if (strstr(query_no_space,(char *)"REPLICA_HOST_STATUS")) {
pthread_mutex_unlock(&GloSQLite3Server->aurora_mutex);
#ifdef TEST_AURORA_RANDOM
if (rand() % 100 == 0) {
// randomly add some latency on 1% of the traffic
sleep(2);
}
#endif
}
#endif // TEST_AURORA
#ifdef TEST_GALERA
if (strstr(query_no_space,(char *)"HOST_STATUS_GALERA")) {
pthread_mutex_unlock(&GloSQLite3Server->galera_mutex);
if (resultset->rows_count == 0) {
PROXY_TRACE();
}
#ifdef TEST_GALERA_RANDOM
if (rand() % 20 == 0) {
// randomly add some latency on 5% of the traffic
sleep(2);
}
#endif
}
#endif // TEST_GALERA
#ifdef TEST_GROUPREP
if (strstr(query_no_space,(char *)"GR_MEMBER_ROUTING_CANDIDATE_STATUS")) {
pthread_mutex_unlock(&GloSQLite3Server->grouprep_mutex);
// NOTE: Enable this just in case of manual testing
// if (rand() % 100 == 0) {
// // randomly add some latency on 1% of the traffic
// sleep(2);
// }
}
#endif // TEST_GROUPREP
if (strstr(query_no_space,(char *)"Seconds_Behind_Master")) {
if (rand() % 10 == 0) {
// randomly add some latency on 10% of the traffic
sleep(2);
}
}
}
#endif // TEST_AURORA || TEST_GALERA || TEST_GROUPREP
sqlite3 *db = sqlite_sess->sessdb->get_db();
bool in_trans = false;
if ((*proxy_sqlite3_get_autocommit)(db)==0) {
in_trans = true;
}
bool deprecate_eof = sess->client_myds->myconn->options.client_flag & CLIENT_DEPRECATE_EOF;
sess->SQLite3_to_MySQL(resultset, error, affected_rows, &sess->client_myds->myprot, in_trans, deprecate_eof);
delete resultset;
#ifdef TEST_READONLY
if (strncasecmp("SELECT",query_no_space,6)) {
if (strstr(query_no_space,(char *)"READONLY_STATUS")) {
// the table is writable
pthread_mutex_lock(&GloSQLite3Server->test_readonly_mutex);
GloSQLite3Server->load_readonly_table(sess);
pthread_mutex_unlock(&GloSQLite3Server->test_readonly_mutex);
}
}
#endif // TEST_READONLY
#ifdef TEST_REPLICATIONLAG
if (strncasecmp("SELECT", query_no_space, 6)) {
if (strstr(query_no_space, (char*)"REPLICATIONLAG_HOST_STATUS")) {
// the table is writable
pthread_mutex_lock(&GloSQLite3Server->test_replicationlag_mutex);
GloSQLite3Server->load_replicationlag_table(sess);
pthread_mutex_unlock(&GloSQLite3Server->test_replicationlag_mutex);
}
}
#endif // TEST_REPLICATIONLAG
}
l_free(pkt->size-sizeof(mysql_hdr),query_no_space); // it is always freed here
l_free(query_length,query);
}
#ifdef TEST_GROUPREP
group_rep_status SQLite3_Server::grouprep_test_value(const std::string& srv_addr) {
group_rep_status cur_srv_st { "YES", "YES", 0, "" };