-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathMySQL_Session.cpp
8071 lines (7670 loc) · 311 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 "../deps/json/json.hpp"
using json = nlohmann::json;
#define PROXYJSON
#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 "MySQL_Data_Stream.h"
#include "MySQL_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 "MySQL_Query_Cache.h"
#include "libinjection.h"
#include "libinjection_sqli.h"
#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_STATUS "select @@character_set_client, @@character_set_connection, @@character_set_server, @@character_set_database limit 1"
#define SELECT_CHARSET_STATUS_LEN 115
#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_FROM_DUAL "SELECT LAST_INSERT_ID() FROM DUAL"
#define SELECT_LAST_INSERT_ID_FROM_DUAL_LEN 33
#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_generate_invisible_primary_key",
"sql_log_bin",
"sql_quote_show_create",
"sql_require_primary_key",
"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",
"max_statement_time",
"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",
"log_slow_filter",
"optimizer_switch",
"wsrep_osu_method",
};
#include "proxysql_find_charset.h"
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 */
/**
* @brief Converts session type to a human-readable string.
* @param session_type The session type to convert.
* @return A string representing the session type.
*/
/*
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";
}
};*/
KillArgs::KillArgs(char* u, char* p, char* h, unsigned int P, unsigned int _hid, unsigned long i, int kt, int _use_ssl, MySQL_Thread* _mt) :
KillArgs(u, p, h, P, _hid, i, kt, _use_ssl, _mt, NULL) {
// resolving DNS if available in Cache
if (h && P) {
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, int _use_ssl, 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;
use_ssl=_use_ssl;
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;
}
/**
* @brief Thread function to kill a query or connection on a MySQL server.
*
* This function is executed in a separate thread to kill a query or connection on a MySQL server.
* It establishes a connection to the MySQL server and sends a kill command to terminate the specified query or connection.
*
* @param[in] arg A pointer to a KillArgs structure containing the necessary parameters for killing the query or connection.
* @return nullptr.
*/
void* kill_query_thread(void *arg) {
KillArgs *ka=(KillArgs *)arg;
//! It initializes a new MySQL_Thread object to handle MySQL-related operations.
std::unique_ptr<MySQL_Thread> mysql_thr(new MySQL_Thread());
set_thread_name("KillQuery", GloVars.set_thread_name);
//! Retrieves the current time and refreshes thread variables.
mysql_thr->curtime=monotonic_time();
mysql_thr->refresh_variables();
//! Initializes ssl_params to NULL, which holds SSL parameters for the MySQL connection.
MySQLServers_SslParams * ssl_params = NULL;
//! Initializes a new MySQL connection using mysql_init(NULL).
MYSQL *mysql=mysql_init(NULL);
if (!mysql) {
goto __exit_kill_query_thread;
}
//! Sets specific connection attributes such as program_name and _server_host using mysql_options4().
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 SSL is enabled and port information is available, it retrieves SSL parameters for the server from MyHGM and configures the MySQL connection accordingly.
if (ka->use_ssl && ka->port) {
ssl_params = MyHGM->get_Server_SSL_Params(ka->hostname, ka->port, ka->username);
MySQL_Connection::set_ssl_params(mysql,ssl_params);
mysql_options(mysql, MARIADB_OPT_SSL_KEYLOG_CALLBACK, (void*)proxysql_keylog_write_line_callback);
}
MYSQL *ret;
//! Depending on the type of operation (kill_type), constructs a KILL command string (buf) to terminate the specified query or connection.
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 (ka->mt) {
ka->mt->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 (ka->mt) {
ka->mt->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) {
int myerr = mysql_errno(mysql);
if (ssl_params != NULL && myerr == 2026) {
proxy_error("Failed to connect to server %s:%d to run KILL %s %lu. SSL Params: %s , %s , %s , %s , %s , %s , %s , %s\n",
ka->hostname, ka->port, ( ka->kill_type==KILL_QUERY ? "QUERY" : "CONNECTION" ) , ka->id,
ssl_params->ssl_ca.c_str() , ssl_params->ssl_cert.c_str() , ssl_params->ssl_key.c_str() , ssl_params->ssl_capath.c_str() ,
ssl_params->ssl_crl.c_str() , ssl_params->ssl_crlpath.c_str() , ssl_params->ssl_cipher.c_str() , ssl_params->tls_version.c_str()
);
} else {
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::update_dns_cache_from_mysql_conn(mysql);
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;
}
//! Executes the KILL command using mysql_query() on the established MySQL connection. Note that this call is blocking.
// FIXME: these 2 calls are blocking, fortunately on their own thread
mysql_query(mysql,buf);
__exit_kill_query_thread:
//! clean-up
if (mysql)
mysql_close(mysql);
delete ka;
if (ssl_params != NULL) {
delete ssl_params;
ssl_params = NULL;
}
// De-initializes per-thread structures. Required in all auxiliary threads using MySQL and SSL.
mysql_thread_end();
return NULL;
}
extern MySQL_Query_Processor* GloMyQPro;
extern MySQL_Query_Cache *GloMyQC;
extern ProxySQL_Admin *GloAdmin;
extern MySQL_Threads_Handler *GloMTH;
/**
* @brief Default constructor.
* Initializes all member variables to their default values.
*/
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; // if affected rows is set, last_insert_id is set too
waiting_since = 0;
affected_rows=0;
last_insert_id = 0;
rows_sent=0;
start_time=0;
end_time=0;
stmt_client_id=0;
}
/**
* @brief Destructor.
* Frees resources associated with QueryParserArgs and stmt_info.
*/
Query_Info::~Query_Info() {
GloMyQPro->query_parser_free(&QueryParserArgs);
if (stmt_info) {
stmt_info=NULL;
}
}
/**
* @brief Initializes query information.
* @param _p Pointer to the query data.
* @param len Length of the query data.
* @param mysql_header Flag indicating whether MySQL header is present.
*/
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; // if affected rows is set, last_insert_id is set too
waiting_since = 0;
affected_rows=0;
last_insert_id = 0;
rows_sent=0;
sess->gtid_hid=-1;
stmt_client_id=0;
}
/**
* @brief Finalizes query information.
* Updates query counters and performs clean-up.
*/
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;
}
}
/**
* @brief Initializes query information with the given parameters.
* @param _p Pointer to the query data.
* @param len Length of the query data.
* @param mysql_header Flag indicating whether MySQL header is present.
*/
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; // if affected rows is set, last_insert_id is set too
waiting_since = 0;
affected_rows=0;
last_insert_id = 0;
rows_sent=0;
}
/**
* @brief Initializes the query parser.
*/
void Query_Info::query_parser_init() {
GloMyQPro->query_parser_init(&QueryParserArgs,(char *)QueryPointer,QueryLength,0);
}
/**
* @brief Retrieves the command type of the query from the query parser.
* @return The command type of the query.
*/
enum MYSQL_COM_QUERY_command Query_Info::query_parser_command_type() {
MyComQueryCmd= GloMyQPro->query_parser_command_type(&QueryParserArgs);
return MyComQueryCmd;
}
/**
* @brief Frees resources associated with the query parser.
*/
void Query_Info::query_parser_free() {
GloMyQPro->query_parser_free(&QueryParserArgs);
}
/**
* @brief Updates query counters and resets member variables.
* @return The number of rows affected by the query.
*/
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= GloMyQPro->query_parser_update_counters(sess, MyComQueryCmd, &QueryParserArgs, end_time-start_time);
MyComQueryCmd=MYSQL_COM_QUERY___NONE;
QueryPointer=NULL;
QueryLength=0;
return ret;
}
/**
* @brief Retrieves the digest text of the query from the query parser.
* @return The digest text of the query.
*/
char * Query_Info::get_digest_text() {
return GloMyQPro->get_digest_text(&QueryParserArgs);
}
/**
* @brief Checks if the query is a SELECT statement with the NOT FOR UPDATE clause.
* @return True if the query is a SELECT statement with the NOT FOR UPDATE clause, false otherwise.
*/
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;
}
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;
}
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::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;
}
/**
* @brief Constructs a new MySQL session object.
*/
MySQL_Session::MySQL_Session() {
thread_session_id=0;
//handler_ret = 0;
pause_until=0;
qpo=new MySQL_Query_Processor_Output();
qpo->init();
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=SESSION_FORWARD_TYPE_NONE;
//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);
warning_in_hg = -1;
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;
previous_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;
}
/**
* @brief Resets the MySQL session to its initial state.
*/
void MySQL_Session::reset() {
autocommit=true;
autocommit_handled=false;
sending_set_autocommit=false;
autocommit_on_hostgroup=-1;
warning_in_hg = -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();
}
}
}
/**
* @brief Destructor for the MySQL session.
*/
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,
client_myds->myconn->userinfo->passtype
);
} else {
GloMyLdapAuth->decrease_frontend_user_connections(client_myds->myconn->userinfo->fe_username);
}
break;
}
if (client_myds->myconn) {
__sync_fetch_and_sub(
client_myds->myconn->userinfo->passtype == PASSWORD_TYPE::PRIMARY ?
&MyHGM->status.client_connections_prim_pass :
&MyHGM->status.client_connections_addl_pass,
1
);
}
}
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;
}
}
/**
* @brief Handles COMMIT or ROLLBACK commands received from the client.
*
* The handler_CommitRollback() function processes COMMIT or ROLLBACK commands received from the client. It checks
* the command type and verifies if the command matches the expected syntax for COMMIT or ROLLBACK. If the command
* matches, it updates the respective commit or rollback count in the global monitor's status. Additionally, it
* checks for the presence of an active transaction to determine whether to forward the command or reply with an OK
* status.
*
* If there is an active transaction, the function sets the current hostgroup to the hostgroup of the active transaction
* and returns false, indicating that the command should be forwarded. If there are no active transactions, the function
* replies with an OK status and updates the client data stream accordingly.
*
* @param pkt Pointer to the packet containing the COMMIT or ROLLBACK command.
* @return True if the command is successfully handled and replied to, false otherwise.
*
* @see MySQL_Session::FindOneActiveTransaction()
* @see MySQL_Session::current_hostgroup
* @see MySQL_Session::autocommit
* @see MySQL_Session::client_myds
* @see MySQL_Data_Stream::DSS
* @see MySQL_Protocol::generate_pkt_OK()
* @see MySQL_Session::RequestEnd()
*/
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
//
// Since we are limited to forwarding just one 'COMMIT|ROLLBACK', we work under the assumption that we
// only have one active transaction. Under this premise, we should execute this command under that
// specific connection, for that, we update 'current_hostgroup' with the first active transaction we are
// able to find. If more transactions are simultaneously open for the session, more 'COMMIT|ROLLBACK'
// commands are required to be issued by the client to continue ending transactions.
int hg = FindOneActiveTransaction(true);
if (hg != -1) {
// there is an active transaction, we must forward the request
current_hostgroup = hg;
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);
if (mirror==false) {
RequestEnd(NULL);
} else {
client_myds->DSS=STATE_SLEEP;
status=WAITING_CLIENT_DATA;
}
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;
}
/**
* @brief Handles the SET AUTOCOMMIT command received from the client.
*
* The handler_SetAutocommit() function processes the SET AUTOCOMMIT command received from the client.
* It parses the command to determine the new autocommit value and updates the autocommit status accordingly.
* Additionally, it checks for the presence of active transactions and handles the forwarding of the command if needed.
* The function also replies with an OK status to the client after processing the command.
*
* @param pkt Pointer to the packet containing the SET AUTOCOMMIT command.
* @return True if the command is successfully handled and replied to, false otherwise.
*
* @see MySQL_Session::autocommit_handled
* @see MySQL_Session::sending_set_autocommit
* @see MySQL_Session::current_hostgroup
* @see MySQL_Session::autocommit
* @see MySQL_Session::client_myds
* @see MySQL_Session::NumActiveTransactions()
* @see MySQL_Data_Stream::DSS
* @see MySQL_Protocol::generate_pkt_OK()
* @see MySQL_Session::RequestEnd()
*/
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==' ') {
break;
}
}
}
}
}
if (fd >= 0) { // we can set autocommit
autocommit_handled=true;
#ifdef DEBUG
proxy_debug(PROXY_DEBUG_MYSQL_QUERY_PROCESSOR, 5, "Setting autocommit to = %d\n", fd);
#endif
__sync_fetch_and_add(&MyHGM->status.autocommit_cnt, 1);
// we immediately process the number of transactions
unsigned int nTrx=NumActiveTransactions();
if (fd==1 && autocommit==true) {
// nothing to do, return OK