-
Notifications
You must be signed in to change notification settings - Fork 977
/
MySQL_Session.cpp
7952 lines (7593 loc) · 301 KB
/
MySQL_Session.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 "MySQL_HostGroups_Manager.h"
#include "MySQL_Thread.h"
#include "proxysql.h"
#include "cpp.h"
#include "proxysql_utils.h"
#include "re2/re2.h"
#include "re2/regexp.h"
#include "mysqld_error.h"
#include "set_parser.h"
#include "MySQL_Data_Stream.h"
#include "query_processor.h"
#include "MySQL_PreparedStatement.h"
#include "MySQL_Logger.hpp"
#include "StatCounters.h"
#include "MySQL_Authentication.hpp"
#include "MySQL_LDAP_Authentication.hpp"
#include "MySQL_Protocol.h"
#include "SQLite3_Server.h"
#include "MySQL_Variables.h"
#include "ProxySQL_Cluster.hpp"
#include "libinjection.h"
#include "libinjection_sqli.h"
#define SELECT_VERSION_COMMENT "select @@version_comment limit 1"
#define SELECT_VERSION_COMMENT_LEN 32
#define PROXYSQL_VERSION_COMMENT "\x01\x00\x00\x01\x01\x27\x00\x00\x02\x03\x64\x65\x66\x00\x00\x00\x11\x40\x40\x76\x65\x72\x73\x69\x6f\x6e\x5f\x63\x6f\x6d\x6d\x65\x6e\x74\x00\x0c\x21\x00\x18\x00\x00\x00\xfd\x00\x00\x1f\x00\x00\x05\x00\x00\x03\xfe\x00\x00\x02\x00\x0b\x00\x00\x04\x0a(ProxySQL)\x05\x00\x00\x05\xfe\x00\x00\x02\x00"
#define PROXYSQL_VERSION_COMMENT_LEN 81
// PROXYSQL_VERSION_COMMENT_WITH_OK is sent instead of PROXYSQL_VERSION_COMMENT
// if Client supports CLIENT_DEPRECATE_EOF
#define PROXYSQL_VERSION_COMMENT_WITH_OK "\x01\x00\x00\x01\x01" \
"\x27\x00\x00\x02\x03\x64\x65\x66\x00\x00\x00\x11\x40\x40\x76\x65\x72\x73\x69\x6f\x6e\x5f\x63\x6f\x6d\x6d\x65\x6e\x74\x00\x0c\x21\x00\x18\x00\x00\x00\xfd\x00\x00\x1f\x00\x00" \
"\x0b\x00\x00\x03\x0a(ProxySQL)" \
"\x07\x00\x00\x04\xfe\x00\x00\x02\x00\x00\x00"
#define PROXYSQL_VERSION_COMMENT_WITH_OK_LEN 74
#define SELECT_CONNECTION_ID "SELECT CONNECTION_ID()"
#define SELECT_CONNECTION_ID_LEN 22
#define SELECT_LAST_INSERT_ID "SELECT LAST_INSERT_ID()"
#define SELECT_LAST_INSERT_ID_LEN 23
#define SELECT_LAST_INSERT_ID_LIMIT1 "SELECT LAST_INSERT_ID() LIMIT 1"
#define SELECT_LAST_INSERT_ID_LIMIT1_LEN 31
#define SELECT_VARIABLE_IDENTITY "SELECT @@IDENTITY"
#define SELECT_VARIABLE_IDENTITY_LEN 17
#define SELECT_VARIABLE_IDENTITY_LIMIT1 "SELECT @@IDENTITY LIMIT 1"
#define SELECT_VARIABLE_IDENTITY_LIMIT1_LEN 25
#define EXPMARIA
using std::function;
using std::vector;
static inline char is_digit(char c) {
if(c >= '0' && c <= '9')
return 1;
return 0;
}
static inline char is_normal_char(char c) {
if(c >= 'a' && c <= 'z')
return 1;
if(c >= 'A' && c <= 'Z')
return 1;
if(c >= '0' && c <= '9')
return 1;
if(c == '$' || c == '_')
return 1;
return 0;
}
static const std::set<std::string> mysql_variables_boolean = {
"aurora_read_replica_read_committed",
"foreign_key_checks",
"innodb_strict_mode",
"innodb_table_locks",
"sql_auto_is_null",
"sql_big_selects",
"sql_log_bin",
"sql_safe_updates",
"unique_checks",
};
static const std::set<std::string> mysql_variables_numeric = {
"auto_increment_increment",
"auto_increment_offset",
"group_concat_max_len",
"innodb_lock_wait_timeout",
"join_buffer_size",
"lock_wait_timeout",
"long_query_time",
"max_execution_time",
"max_heap_table_size",
"max_join_size",
"max_sort_length",
"optimizer_prune_level",
"optimizer_search_depth",
"optimizer_use_condition_selectivity",
"query_cache_type",
"sort_buffer_size",
"sql_select_limit",
"timestamp",
"tmp_table_size",
"wsrep_sync_wait"
};
static const std::set<std::string> mysql_variables_strings = {
"default_storage_engine",
"default_tmp_storage_engine",
"group_replication_consistency",
"lc_messages",
"lc_time_names",
"optimizer_switch",
"wsrep_osu_method",
};
extern MARIADB_CHARSET_INFO * proxysql_find_charset_name(const char * const name);
extern MARIADB_CHARSET_INFO * proxysql_find_charset_collate_names(const char *csname, const char *collatename);
extern const MARIADB_CHARSET_INFO * proxysql_find_charset_nr(unsigned int nr);
extern MARIADB_CHARSET_INFO * proxysql_find_charset_collate(const char *collatename);
extern MySQL_Authentication *GloMyAuth;
extern MySQL_LDAP_Authentication *GloMyLdapAuth;
extern ProxySQL_Admin *GloAdmin;
extern MySQL_Logger *GloMyLogger;
extern MySQL_STMT_Manager_v14 *GloMyStmt;
extern SQLite3_Server *GloSQLite3Server;
#ifdef PROXYSQLCLICKHOUSE
extern ClickHouse_Authentication *GloClickHouseAuth;
extern ClickHouse_Server *GloClickHouseServer;
#endif /* PROXYSQLCLICKHOUSE */
std::string proxysql_session_type_str(enum proxysql_session_type session_type) {
if (session_type == PROXYSQL_SESSION_MYSQL) {
return "PROXYSQL_SESSION_MYSQL";
} else if (session_type == PROXYSQL_SESSION_ADMIN) {
return "PROXYSQL_SESSION_ADMIN";
} else if (session_type == PROXYSQL_SESSION_STATS) {
return "PROXYSQL_SESSION_STATS";
} else if (session_type == PROXYSQL_SESSION_SQLITE) {
return "PROXYSQL_SESSION_SQLITE";
} else if (session_type == PROXYSQL_SESSION_CLICKHOUSE) {
return "PROXYSQL_SESSION_CLICKHOUSE";
} else if (session_type == PROXYSQL_SESSION_MYSQL_EMU) {
return "PROXYSQL_SESSION_MYSQL_EMU";
} else {
return "PROXYSQL_SESSION_NONE";
}
};
Session_Regex::Session_Regex(char *p) {
s=strdup(p);
re2::RE2::Options *opt2=new re2::RE2::Options(RE2::Quiet);
opt2->set_case_sensitive(false);
opt=(void *)opt2;
re=(RE2 *)new RE2(s, *opt2);
}
Session_Regex::~Session_Regex() {
free(s);
delete (RE2 *)re;
delete (re2::RE2::Options *)opt;
}
bool Session_Regex::match(char *m) {
bool rc=false;
rc=RE2::PartialMatch(m,*(RE2 *)re);
return rc;
}
KillArgs::KillArgs(char* u, char* p, char* h, unsigned int P, unsigned int _hid, unsigned long i, int kt, MySQL_Thread* _mt) :
KillArgs(u, p, h, P, _hid, i, kt, _mt, NULL) {
// resolving DNS if available in Cache
if (h) {
const std::string& ip = MySQL_Monitor::dns_lookup(h, false);
if (ip.empty() == false) {
ip_addr = strdup(ip.c_str());
}
}
}
KillArgs::KillArgs(char *u, char *p, char *h, unsigned int P, unsigned int _hid, unsigned long i, int kt, MySQL_Thread *_mt, char *ip) {
username=strdup(u);
password=strdup(p);
hostname=strdup(h);
ip_addr = NULL;
if (ip)
ip_addr = strdup(ip);
port=P;
hid=_hid;
id=i;
kill_type=kt;
mt=_mt;
}
KillArgs::~KillArgs() {
free(username);
free(password);
free(hostname);
if (ip_addr)
free(ip_addr);
}
const char* KillArgs::get_host_address() const {
const char* host_address = hostname;
if (ip_addr)
host_address = ip_addr;
return host_address;
}
void * kill_query_thread(void *arg) {
KillArgs *ka=(KillArgs *)arg;
MYSQL *mysql;
MySQL_Thread * thread = ka->mt;
mysql=mysql_init(NULL);
mysql_options4(mysql, MYSQL_OPT_CONNECT_ATTR_ADD, "program_name", "proxysql_killer");
mysql_options4(mysql, MYSQL_OPT_CONNECT_ATTR_ADD, "_server_host", ka->hostname);
if (!mysql) {
goto __exit_kill_query_thread;
}
MYSQL *ret;
if (ka->port) {
switch (ka->kill_type) {
case KILL_QUERY:
proxy_warning("KILL QUERY %lu on %s:%d\n", ka->id, ka->hostname, ka->port);
if (thread) {
thread->status_variables.stvar[st_var_killed_queries]++;
}
break;
case KILL_CONNECTION:
proxy_warning("KILL CONNECTION %lu on %s:%d\n", ka->id, ka->hostname, ka->port);
if (thread) {
thread->status_variables.stvar[st_var_killed_connections]++;
}
break;
default:
break;
}
ret=mysql_real_connect(mysql, ka->get_host_address(), ka->username, ka->password, NULL, ka->port, NULL, 0);
} else {
switch (ka->kill_type) {
case KILL_QUERY:
proxy_warning("KILL QUERY %lu on localhost\n", ka->id);
break;
case KILL_CONNECTION:
proxy_warning("KILL CONNECTION %lu on localhost\n", ka->id);
break;
default:
break;
}
ret=mysql_real_connect(mysql,"localhost",ka->username,ka->password,NULL,0,ka->hostname,0);
}
if (!ret) {
proxy_error("Failed to connect to server %s:%d to run KILL %s %lu: Error: %s\n" , ka->hostname, ka->port, ( ka->kill_type==KILL_QUERY ? "QUERY" : "CONNECTION" ) , ka->id, mysql_error(mysql));
MyHGM->p_update_mysql_error_counter(p_mysql_error_type::mysql, ka->hid, ka->hostname, ka->port, mysql_errno(mysql));
goto __exit_kill_query_thread;
}
MySQL_Monitor::dns_cache_update_socket(mysql->host, mysql->net.fd);
char buf[100];
switch (ka->kill_type) {
case KILL_QUERY:
sprintf(buf,"KILL QUERY %lu", ka->id);
break;
case KILL_CONNECTION:
sprintf(buf,"KILL CONNECTION %lu", ka->id);
break;
default:
sprintf(buf,"KILL %lu", ka->id);
break;
}
// FIXME: these 2 calls are blocking, fortunately on their own thread
mysql_query(mysql,buf);
__exit_kill_query_thread:
if (mysql)
mysql_close(mysql);
delete ka;
return NULL;
}
extern Query_Processor *GloQPro;
extern Query_Cache *GloQC;
extern ProxySQL_Admin *GloAdmin;
extern MySQL_Threads_Handler *GloMTH;
Query_Info::Query_Info() {
MyComQueryCmd=MYSQL_COM_QUERY___NONE;
QueryPointer=NULL;
QueryLength=0;
QueryParserArgs.digest_text=NULL;
QueryParserArgs.first_comment=NULL;
stmt_info=NULL;
bool_is_select_NOT_for_update=false;
bool_is_select_NOT_for_update_computed=false;
have_affected_rows=false;
waiting_since = 0;
affected_rows=0;
rows_sent=0;
start_time=0;
end_time=0;
stmt_client_id=0;
}
Query_Info::~Query_Info() {
GloQPro->query_parser_free(&QueryParserArgs);
if (stmt_info) {
stmt_info=NULL;
}
}
void Query_Info::begin(unsigned char *_p, int len, bool mysql_header) {
MyComQueryCmd=MYSQL_COM_QUERY___NONE;
QueryPointer=NULL;
QueryLength=0;
mysql_stmt=NULL;
stmt_meta=NULL;
QueryParserArgs.digest_text=NULL;
QueryParserArgs.first_comment=NULL;
start_time=sess->thread->curtime;
init(_p, len, mysql_header);
if (mysql_thread___commands_stats || mysql_thread___query_digests) {
query_parser_init();
if (mysql_thread___commands_stats)
query_parser_command_type();
}
bool_is_select_NOT_for_update=false;
bool_is_select_NOT_for_update_computed=false;
have_affected_rows=false;
waiting_since = 0;
affected_rows=0;
rows_sent=0;
sess->gtid_hid=-1;
stmt_client_id=0;
}
void Query_Info::end() {
query_parser_update_counters();
query_parser_free();
if ((end_time-start_time) > (unsigned int)mysql_thread___long_query_time*1000) {
__sync_add_and_fetch(&sess->thread->status_variables.stvar[st_var_queries_slow],1);
}
if (sess->with_gtid) {
__sync_add_and_fetch(&sess->thread->status_variables.stvar[st_var_queries_gtid],1);
}
assert(mysql_stmt==NULL);
if (stmt_info) {
stmt_info=NULL;
}
if (stmt_meta) { // fix bug #796: memory is not freed in case of error during STMT_EXECUTE
if (stmt_meta->pkt) {
uint32_t stmt_global_id=0;
memcpy(&stmt_global_id,(char *)(stmt_meta->pkt)+5,sizeof(uint32_t));
sess->SLDH->reset(stmt_global_id);
free(stmt_meta->pkt);
stmt_meta->pkt=NULL;
}
stmt_meta = NULL;
}
}
void Query_Info::init(unsigned char *_p, int len, bool mysql_header) {
QueryLength=(mysql_header ? len-5 : len);
QueryPointer=(mysql_header ? _p+5 : _p);
MyComQueryCmd = MYSQL_COM_QUERY__UNINITIALIZED;
bool_is_select_NOT_for_update=false;
bool_is_select_NOT_for_update_computed=false;
have_affected_rows=false;
waiting_since = 0;
affected_rows=0;
rows_sent=0;
}
void Query_Info::query_parser_init() {
GloQPro->query_parser_init(&QueryParserArgs,(char *)QueryPointer,QueryLength,0);
}
enum MYSQL_COM_QUERY_command Query_Info::query_parser_command_type() {
MyComQueryCmd=GloQPro->query_parser_command_type(&QueryParserArgs);
return MyComQueryCmd;
}
void Query_Info::query_parser_free() {
GloQPro->query_parser_free(&QueryParserArgs);
}
unsigned long long Query_Info::query_parser_update_counters() {
if (stmt_info) {
MyComQueryCmd=stmt_info->MyComQueryCmd;
}
if (MyComQueryCmd==MYSQL_COM_QUERY___NONE) return 0; // this means that it was never initialized
if (MyComQueryCmd == MYSQL_COM_QUERY__UNINITIALIZED) return 0; // this means that it was never initialized
unsigned long long ret=GloQPro->query_parser_update_counters(sess, MyComQueryCmd, &QueryParserArgs, end_time-start_time);
MyComQueryCmd=MYSQL_COM_QUERY___NONE;
QueryPointer=NULL;
QueryLength=0;
return ret;
}
char * Query_Info::get_digest_text() {
return GloQPro->get_digest_text(&QueryParserArgs);
}
bool Query_Info::is_select_NOT_for_update() {
if (stmt_info) { // we are processing a prepared statement. We already have the information
return stmt_info->is_select_NOT_for_update;
}
if (QueryPointer==NULL) {
return false;
}
if (bool_is_select_NOT_for_update_computed) {
return bool_is_select_NOT_for_update;
}
bool_is_select_NOT_for_update_computed=true;
if (QueryLength<7) {
return false;
}
char *QP = (char *)QueryPointer;
size_t ql = QueryLength;
// we try to use the digest, if avaiable
if (QueryParserArgs.digest_text) {
QP = QueryParserArgs.digest_text;
ql = strlen(QP);
}
if (strncasecmp(QP,(char *)"SELECT ",7)) {
return false;
}
// if we arrive till here, it is a SELECT
if (ql>=17) {
char *p=QP;
p+=ql-11;
if (strncasecmp(p," FOR UPDATE",11)==0) {
__sync_fetch_and_add(&MyHGM->status.select_for_update_or_equivalent, 1);
return false;
}
p=QP;
p+=ql-10;
if (strncasecmp(p," FOR SHARE",10)==0) {
__sync_fetch_and_add(&MyHGM->status.select_for_update_or_equivalent, 1);
return false;
}
if (ql>=25) {
char *p=QP;
p+=ql-19;
if (strncasecmp(p," LOCK IN SHARE MODE",19)==0) {
__sync_fetch_and_add(&MyHGM->status.select_for_update_or_equivalent, 1);
return false;
}
p=QP;
p+=ql-7;
if (strncasecmp(p," NOWAIT",7)==0) {
// let simplify. If NOWAIT is used, we assume FOR UPDATE|SHARE is used
__sync_fetch_and_add(&MyHGM->status.select_for_update_or_equivalent, 1);
return false;
/*
if (strcasestr(QP," FOR UPDATE ")==NULL) {
__sync_fetch_and_add(&MyHGM->status.select_for_update_or_equivalent, 1);
return false;
}
if (strcasestr(QP," FOR SHARE ")==NULL) {
__sync_fetch_and_add(&MyHGM->status.select_for_update_or_equivalent, 1);
return false;
}
*/
}
p=QP;
p+=ql-12;
if (strncasecmp(p," SKIP LOCKED",12)==0) {
// let simplify. If SKIP LOCKED is used, we assume FOR UPDATE|SHARE is used
__sync_fetch_and_add(&MyHGM->status.select_for_update_or_equivalent, 1);
return false;
/*
if (strcasestr(QP," FOR UPDATE ")) {
__sync_fetch_and_add(&MyHGM->status.select_for_update_or_equivalent, 1);
return false;
}
if (strcasestr(QP," FOR SHARE ")) {
__sync_fetch_and_add(&MyHGM->status.select_for_update_or_equivalent, 1);
return false;
}
*/
}
p=QP;
char buf[129];
if (ql>=128) { // for long query, just check the last 128 bytes
p+=ql-128;
memcpy(buf,p,128);
buf[128]=0;
} else {
memcpy(buf,p,ql);
buf[ql]=0;
}
if (strcasestr(buf," FOR ")) {
if (strcasestr(buf," FOR UPDATE ")) {
__sync_fetch_and_add(&MyHGM->status.select_for_update_or_equivalent, 1);
return false;
}
if (strcasestr(buf," FOR SHARE ")) {
__sync_fetch_and_add(&MyHGM->status.select_for_update_or_equivalent, 1);
return false;
}
}
}
}
bool_is_select_NOT_for_update=true;
return true;
}
void * MySQL_Session::operator new(size_t size) {
return l_alloc(size);
}
void MySQL_Session::operator delete(void *ptr) {
l_free(sizeof(MySQL_Session),ptr);
}
void MySQL_Session::set_status(enum session_status e) {
if (e==session_status___NONE) {
if (mybe) {
if (mybe->server_myds) {
assert(mybe->server_myds->myconn==0);
if (mybe->server_myds->myconn) {
assert(mybe->server_myds->myconn->async_state_machine==ASYNC_IDLE);
}
}
}
}
status=e;
}
MySQL_Session::MySQL_Session() {
thread_session_id=0;
//handler_ret = 0;
pause_until=0;
qpo=new Query_Processor_Output();
start_time=0;
command_counters=new StatCounters(15,10);
healthy=1;
autocommit=true;
autocommit_handled=false;
sending_set_autocommit=false;
autocommit_on_hostgroup=-1;
killed=false;
session_type=PROXYSQL_SESSION_MYSQL;
//admin=false;
connections_handler=false;
max_connections_reached=false;
//stats=false;
client_authenticated=false;
default_schema=NULL;
user_attributes=NULL;
schema_locked=false;
session_fast_forward=false;
started_sending_data_to_client=false;
handler_function=NULL;
client_myds=NULL;
to_process=0;
mybe=NULL;
mirror=false;
mirrorPkt.ptr=NULL;
mirrorPkt.size=0;
set_status(session_status___NONE);
idle_since = 0;
transaction_started_at = 0;
CurrentQuery.sess=this;
CurrentQuery.mysql_stmt=NULL;
CurrentQuery.stmt_meta=NULL;
CurrentQuery.stmt_global_id=0;
CurrentQuery.stmt_client_id=0;
CurrentQuery.stmt_info=NULL;
current_hostgroup=-1;
default_hostgroup=-1;
locked_on_hostgroup=-1;
locked_on_hostgroup_and_all_variables_set=false;
next_query_flagIN=-1;
mirror_hostgroup=-1;
mirror_flagOUT=-1;
active_transactions=0;
with_gtid = false;
use_ssl = false;
change_user_auth_switch = false;
//gtid_trxid = 0;
gtid_hid = -1;
memset(gtid_buf,0,sizeof(gtid_buf));
match_regexes=NULL;
init(); // we moved this out to allow CHANGE_USER
last_insert_id=0; // #1093
last_HG_affected_rows = -1; // #1421 : advanced support for LAST_INSERT_ID()
proxysql_node_address = NULL;
use_ldap_auth = false;
}
void MySQL_Session::init() {
transaction_persistent_hostgroup=-1;
transaction_persistent=false;
mybes= new PtrArray(4);
sess_STMTs_meta=new MySQL_STMTs_meta();
SLDH=new StmtLongDataHandler();
}
void MySQL_Session::reset() {
autocommit=true;
autocommit_handled=false;
sending_set_autocommit=false;
autocommit_on_hostgroup=-1;
current_hostgroup=-1;
default_hostgroup=-1;
locked_on_hostgroup=-1;
locked_on_hostgroup_and_all_variables_set=false;
if (sess_STMTs_meta) {
delete sess_STMTs_meta;
sess_STMTs_meta=NULL;
}
if (SLDH) {
delete SLDH;
SLDH=NULL;
}
if (mybes) {
reset_all_backends();
delete mybes;
mybes=NULL;
}
mybe=NULL;
with_gtid = false;
//gtid_trxid = 0;
gtid_hid = -1;
memset(gtid_buf,0,sizeof(gtid_buf));
if (session_type == PROXYSQL_SESSION_SQLITE) {
SQLite3_Session *sqlite_sess = (SQLite3_Session *)thread->gen_args;
if (sqlite_sess && sqlite_sess->sessdb) {
sqlite3 *db = sqlite_sess->sessdb->get_db();
if ((*proxy_sqlite3_get_autocommit)(db)==0) {
sqlite_sess->sessdb->execute((char *)"COMMIT");
}
}
}
if (client_myds) {
if (client_myds->myconn) {
client_myds->myconn->reset();
}
}
}
MySQL_Session::~MySQL_Session() {
reset(); // we moved this out to allow CHANGE_USER
if (locked_on_hostgroup >= 0) {
thread->status_variables.stvar[st_var_hostgroup_locked]--;
}
if (client_myds) {
if (client_authenticated) {
switch (session_type) {
#ifdef PROXYSQLCLICKHOUSE
case PROXYSQL_SESSION_CLICKHOUSE:
GloClickHouseAuth->decrease_frontend_user_connections(client_myds->myconn->userinfo->username);
break;
#endif /* PROXYSQLCLICKHOUSE */
default:
if (use_ldap_auth == false) {
GloMyAuth->decrease_frontend_user_connections(client_myds->myconn->userinfo->username);
} else {
GloMyLdapAuth->decrease_frontend_user_connections(client_myds->myconn->userinfo->fe_username);
}
break;
}
}
delete client_myds;
}
if (default_schema) {
free(default_schema);
}
if (user_attributes) {
free(user_attributes);
user_attributes = NULL;
}
proxy_debug(PROXY_DEBUG_NET,1,"Thread=%p, Session=%p -- Shutdown Session %p\n" , this->thread, this, this);
delete command_counters;
if (session_type==PROXYSQL_SESSION_MYSQL && connections_handler==false && mirror==false) {
__sync_fetch_and_sub(&MyHGM->status.client_connections,1);
}
assert(qpo);
delete qpo;
match_regexes=NULL;
if (mirror) {
__sync_sub_and_fetch(&GloMTH->status_variables.mirror_sessions_current,1);
GloMTH->status_variables.p_gauge_array[p_th_gauge::mirror_concurrency]->Decrement();
}
if (proxysql_node_address) {
delete proxysql_node_address;
proxysql_node_address = NULL;
}
}
// scan the pointer array of mysql backends (mybes) looking for a backend for the specified hostgroup_id
MySQL_Backend * MySQL_Session::find_backend(int hostgroup_id) {
MySQL_Backend *_mybe;
unsigned int i;
for (i=0; i < mybes->len; i++) {
_mybe=(MySQL_Backend *)mybes->index(i);
if (_mybe->hostgroup_id==hostgroup_id) {
return _mybe;
}
}
return NULL; // NULL = backend not found
};
void MySQL_Session::update_expired_conns(const vector<function<bool(MySQL_Connection*)>>& checks) {
for (uint32_t i = 0; i < mybes->len; i++) {
MySQL_Backend* mybe = static_cast<MySQL_Backend*>(mybes->index(i));
MySQL_Data_Stream* myds = mybe != nullptr ? mybe->server_myds : nullptr;
MySQL_Connection* myconn = myds != nullptr ? myds->myconn : nullptr;
if (myconn != nullptr) {
const bool is_active_transaction = myconn->IsActiveTransaction();
const bool multiplex_disabled = myconn->MultiplexDisabled(false);
const bool is_idle = myconn->async_state_machine == ASYNC_IDLE;
// Make sure the connection is reusable before performing any check
if (myconn->reusable==true && is_active_transaction==false && multiplex_disabled==false && is_idle) {
for (const function<bool(MySQL_Connection*)>& check : checks) {
if (check(myconn)) {
this->hgs_expired_conns.push_back(mybe->hostgroup_id);
break;
}
}
}
}
}
}
MySQL_Backend * MySQL_Session::create_backend(int hostgroup_id, MySQL_Data_Stream *_myds) {
MySQL_Backend *_mybe=new MySQL_Backend();
proxy_debug(PROXY_DEBUG_NET,4,"HID=%d, _myds=%p, _mybe=%p\n" , hostgroup_id, _myds, _mybe);
_mybe->hostgroup_id=hostgroup_id;
if (_myds) {
_mybe->server_myds=_myds;
} else {
_mybe->server_myds = new MySQL_Data_Stream();
_mybe->server_myds->DSS=STATE_NOT_INITIALIZED;
_mybe->server_myds->init(MYDS_BACKEND_NOT_CONNECTED, this, 0);
}
mybes->add(_mybe);
return _mybe;
};
MySQL_Backend * MySQL_Session::find_or_create_backend(int hostgroup_id, MySQL_Data_Stream *_myds) {
MySQL_Backend *_mybe=find_backend(hostgroup_id);
proxy_debug(PROXY_DEBUG_NET,4,"HID=%d, _myds=%p, _mybe=%p\n" , hostgroup_id, _myds, _mybe);
return ( _mybe ? _mybe : create_backend(hostgroup_id, _myds) );
};
void MySQL_Session::reset_all_backends() {
MySQL_Backend *mybe;
while(mybes->len) {
mybe=(MySQL_Backend *)mybes->remove_index_fast(0);
mybe->reset();
delete mybe;
}
};
void MySQL_Session::writeout() {
int tps = 10; // throttling per second , by default every 100ms
int total_written = 0;
unsigned long long last_sent_=0;
bool disable_throttle = mysql_thread___throttle_max_bytes_per_second_to_client == 0;
int mwpl = mysql_thread___throttle_max_bytes_per_second_to_client; // max writes per call
mwpl = mwpl/tps;
if (session_type!=PROXYSQL_SESSION_MYSQL) {
disable_throttle = true;
}
if (client_myds) client_myds->array2buffer_full();
if (mybe && mybe->server_myds && mybe->server_myds->myds_type==MYDS_BACKEND) {
if (session_type==PROXYSQL_SESSION_MYSQL) {
if (mybe->server_myds->net_failure==false) {
if (mybe->server_myds->poll_fds_idx>-1) { // NOTE: attempt to force writes
mybe->server_myds->array2buffer_full();
}
}
} else {
mybe->server_myds->array2buffer_full();
}
}
if (client_myds && thread->curtime >= client_myds->pause_until) {
if (mirror==false) {
bool runloop=false;
if (client_myds->mypolls) {
last_sent_ = client_myds->mypolls->last_sent[client_myds->poll_fds_idx];
}
int retbytes=client_myds->write_to_net_poll();
total_written+=retbytes;
if (retbytes==QUEUE_T_DEFAULT_SIZE) { // optimization to solve memory bloat
runloop=true;
}
while (runloop && (disable_throttle || total_written < mwpl)) {
runloop=false; // the default
client_myds->array2buffer_full();
struct pollfd fds;
fds.fd=client_myds->fd;
fds.events=POLLOUT;
fds.revents=0;
int retpoll=poll(&fds, 1, 0);
if (retpoll>0) {
if (fds.revents==POLLOUT) {
retbytes=client_myds->write_to_net_poll();
total_written+=retbytes;
if (retbytes==QUEUE_T_DEFAULT_SIZE) { // optimization to solve memory bloat
runloop=true;
}
}
}
}
}
}
// flow control
if (!disable_throttle && total_written > 0) {
if (total_written > mwpl) {
unsigned long long add_ = 1000000/tps + 1000000/tps*((unsigned long long)total_written - (unsigned long long)mwpl)/mwpl;
pause_until = thread->curtime + add_;
client_myds->remove_pollout();
client_myds->pause_until = thread->curtime + add_;
} else {
if (total_written >= QUEUE_T_DEFAULT_SIZE) {
unsigned long long time_diff = thread->curtime - last_sent_;
if (time_diff == 0) { // sending data really too fast!
unsigned long long add_ = 1000000/tps + 1000000/tps*((unsigned long long)total_written - (unsigned long long)mwpl)/mwpl;
pause_until = thread->curtime + add_;
client_myds->remove_pollout();
client_myds->pause_until = thread->curtime + add_;
} else {
float current_Bps = (float)total_written*1000*1000/time_diff;
if (current_Bps > mysql_thread___throttle_max_bytes_per_second_to_client) {
unsigned long long add_ = 1000000/tps;
pause_until = thread->curtime + add_;
assert(pause_until > thread->curtime);
client_myds->remove_pollout();
client_myds->pause_until = thread->curtime + add_;
}
}
}
}
}
if (mybe) {
if (mybe->server_myds) mybe->server_myds->write_to_net_poll();
}
proxy_debug(PROXY_DEBUG_NET,1,"Thread=%p, Session=%p -- Writeout Session %p\n" , this->thread, this, this);
}
bool MySQL_Session::handler_CommitRollback(PtrSize_t *pkt) {
if (pkt->size <= 5) { return false; }
char c=((char *)pkt->ptr)[5];
bool ret=false;
if (c=='c' || c=='C') {
if (pkt->size==strlen("commit")+5) {
if (strncasecmp((char *)"commit",(char *)pkt->ptr+5,6)==0) {
__sync_fetch_and_add(&MyHGM->status.commit_cnt, 1);
ret=true;
}
}
} else {
if (c=='r' || c=='R') {
if (pkt->size==strlen("rollback")+5) {
if ( strncasecmp((char *)"rollback",(char *)pkt->ptr+5,8)==0 ) {
__sync_fetch_and_add(&MyHGM->status.rollback_cnt, 1);
ret=true;
}
}
}
}
if (ret==false) {
return false; // quick exit
}
// in this part of the code (as at release 2.4.3) where we call
// NumActiveTransactions() with the check_savepoint flag .
// This to try to handle MySQL bug https://bugs.mysql.com/bug.php?id=107875
unsigned int nTrx=NumActiveTransactions(true);
if (nTrx) {
// there is an active transaction, we must forward the request
return false;
} else {
// there is no active transaction, we will just reply OK
client_myds->DSS=STATE_QUERY_SENT_NET;
uint16_t setStatus = 0;
if (autocommit) setStatus |= SERVER_STATUS_AUTOCOMMIT;
client_myds->myprot.generate_pkt_OK(true,NULL,NULL,1,0,0,setStatus,0,NULL);
client_myds->DSS=STATE_SLEEP;
status=WAITING_CLIENT_DATA;
if (mirror==false) {
RequestEnd(NULL);
}
l_free(pkt->size,pkt->ptr);
if (c=='c' || c=='C') {
__sync_fetch_and_add(&MyHGM->status.commit_cnt_filtered, 1);
} else {
__sync_fetch_and_add(&MyHGM->status.rollback_cnt_filtered, 1);
}
return true;
}
return false;
}
bool MySQL_Session::handler_SetAutocommit(PtrSize_t *pkt) {
autocommit_handled=false;
sending_set_autocommit=false;
size_t sal=strlen("set autocommit");
char * _ptr = (char *)pkt->ptr;
#ifdef DEBUG
string nqn = string((char *)CurrentQuery.QueryPointer,CurrentQuery.QueryLength);
proxy_debug(PROXY_DEBUG_MYSQL_QUERY_PROCESSOR, 5, "Parsing SET command = %s\n", nqn.c_str());
#endif
if ( pkt->size >= 7+sal) {
if (strncasecmp((char *)"SET @@session.autocommit",(char *)pkt->ptr+5,strlen((char *)"SET @@session.autocommit"))==0) {
memmove(_ptr+9, _ptr+19, pkt->size - 19);
memset(_ptr+pkt->size-10,' ',10);
}
if (strncasecmp((char *)"set autocommit",(char *)pkt->ptr+5,sal)==0) {
void *p = NULL;
// make a copy
PtrSize_t _new_pkt;
_new_pkt.size = pkt->size;
_new_pkt.ptr = malloc(_new_pkt.size);
memcpy(_new_pkt.ptr, pkt->ptr, _new_pkt.size);
_ptr = (char *)_new_pkt.ptr;
for (int i=5+sal; i < (int)_new_pkt.size; i++) {
*((char *)_new_pkt.ptr+i) = tolower(*((char *)_new_pkt.ptr+i));
}
p = memmem(_ptr+5+sal, pkt->size-5-sal, (void *)"false", 5);
if (p) {
memcpy(p,(void *)"0 ",5);
}
p = memmem(_ptr+5+sal, pkt->size-5-sal, (void *)"true", 4);
if (p) {
memcpy(p,(void *)"1 ",4);
}
p = memmem(_ptr+5+sal, pkt->size-5-sal, (void *)"off", 3);
if (p) {
memcpy(p,(void *)"0 ",3);
}
p = memmem(_ptr+5+sal, pkt->size-5-sal, (void *)"on", 2);
if (p) {
memcpy(p,(void *)"1 ",2);
}
unsigned int i;
bool eq=false;
int fd=-1; // first digit
for (i=5+sal;i<_new_pkt.size;i++) {
char c=((char *)_new_pkt.ptr)[i];
if (c!='0' && c!='1' && c!=' ' && c!='=' && c!='/') {
free(_new_pkt.ptr);
return false; // found a not valid char
}
if (eq==false) {
if (c!=' ' && c!='=') {
free(_new_pkt.ptr);
return false; // found a not valid char
}
if (c=='=') eq=true;
} else {
if (c!='0' && c!='1' && c!=' ' && c!='/') {
free(_new_pkt.ptr);
return false; // found a not valid char
}
if (fd==-1) {
if (c=='0' || c=='1') { // found first digit
if (c=='0')
fd=0;
else
fd=1;
}
} else {
if (c=='0' || c=='1') { // found second digit
free(_new_pkt.ptr);
return false;
} else {
if (c=='/' || c==' ') {