-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathMySQL_HostGroups_Manager.cpp
More file actions
7430 lines (6856 loc) · 305 KB
/
Copy pathMySQL_HostGroups_Manager.cpp
File metadata and controls
7430 lines (6856 loc) · 305 KB
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 "proxysql.h"
#include "cpp.h"
#include "MySQL_PreparedStatement.h"
#include "MySQL_Data_Stream.h"
#include <memory>
#include <pthread.h>
#include <string>
#include "prometheus/counter.h"
#include "prometheus/detail/builder.h"
#include "prometheus/family.h"
#include "prometheus/gauge.h"
#include "prometheus_helpers.h"
#include "proxysql_utils.h"
#define char_malloc (char *)malloc
#define itostr(__s, __i) { __s=char_malloc(32); sprintf(__s, "%lld", __i); }
#include "thread.h"
#include "wqueue.h"
#include "ev.h"
#include <functional>
#include <mutex>
#include <type_traits>
using std::function;
#define SAFE_SQLITE3_STEP(_stmt) do {\
do {\
rc=(*proxy_sqlite3_step)(_stmt);\
if (rc!=SQLITE_DONE) {\
assert(rc==SQLITE_LOCKED);\
usleep(100);\
}\
} while (rc!=SQLITE_DONE);\
} while (0)
extern ProxySQL_Admin *GloAdmin;
extern MySQL_Threads_Handler *GloMTH;
extern MySQL_Monitor *GloMyMon;
class MySrvConnList;
class MySrvC;
class MySrvList;
class MyHGC;
const int MYSQL_ERRORS_STATS_FIELD_NUM = 11;
struct ev_io * new_connector(char *address, uint16_t gtid_port, uint16_t mysql_port);
void * GTID_syncer_run();
static int wait_for_mysql(MYSQL *mysql, int status) {
struct pollfd pfd;
int timeout, res;
pfd.fd = mysql_get_socket(mysql);
pfd.events =
(status & MYSQL_WAIT_READ ? POLLIN : 0) |
(status & MYSQL_WAIT_WRITE ? POLLOUT : 0) |
(status & MYSQL_WAIT_EXCEPT ? POLLPRI : 0);
timeout = 1;
res = poll(&pfd, 1, timeout);
if (res == 0)
return MYSQL_WAIT_TIMEOUT | status;
else if (res < 0)
return MYSQL_WAIT_TIMEOUT;
else {
int status = 0;
if (pfd.revents & POLLIN) status |= MYSQL_WAIT_READ;
if (pfd.revents & POLLOUT) status |= MYSQL_WAIT_WRITE;
if (pfd.revents & POLLPRI) status |= MYSQL_WAIT_EXCEPT;
return status;
}
}
/**
* @brief Helper function used to try to extract a value from the JSON field 'servers_defaults'.
*
* @param j JSON object constructed from 'servers_defaults' field.
* @param hid Hostgroup for which the 'servers_defaults' is defined in 'mysql_hostgroup_attributes'. Used for
* error logging.
* @param key The key for the value to be extracted.
* @param val_check A validation function, checks if the value is within a expected range.
*
* @return The value extracted from the supplied JSON. In case of error '-1', and error cause is logged.
*/
template <typename T, typename std::enable_if<std::is_integral<T>::value, bool>::type = true>
T j_get_srv_default_int_val(
const json& j, uint32_t hid, const string& key, const function<bool(T)>& val_check
) {
if (j.find(key) != j.end()) {
const json::value_t val_type = j[key].type();
const char* type_name = j[key].type_name();
if (val_type == json::value_t::number_integer || val_type == json::value_t::number_unsigned) {
T val = j[key].get<T>();
if (val_check(val)) {
return val;
} else {
proxy_error(
"Invalid value %ld supplied for 'mysql_hostgroup_attributes.servers_defaults.%s' for hostgroup %d."
" Value NOT UPDATED.\n",
static_cast<int64_t>(val), key.c_str(), hid
);
}
} else {
proxy_error(
"Invalid type '%s'(%hhu) supplied for 'mysql_hostgroup_attributes.servers_defaults.%s' for hostgroup %d."
" Value NOT UPDATED.\n",
type_name, static_cast<std::uint8_t>(val_type), key.c_str(), hid
);
}
}
return static_cast<T>(-1);
}
//static void * HGCU_thread_run() {
static void * HGCU_thread_run() {
PtrArray *conn_array=new PtrArray();
set_thread_name("MyHGCU", GloVars.set_thread_name);
while(1) {
MySQL_Connection *myconn= NULL;
myconn = (MySQL_Connection *)MyHGM->queue.remove();
if (myconn==NULL) {
// intentionally exit immediately
delete conn_array;
return NULL;
}
conn_array->add(myconn);
while (MyHGM->queue.size()) {
myconn=(MySQL_Connection *)MyHGM->queue.remove();
if (myconn==NULL) {
delete conn_array;
return NULL;
}
conn_array->add(myconn);
}
unsigned int l=conn_array->len;
int *errs=(int *)malloc(sizeof(int)*l);
int *statuses=(int *)malloc(sizeof(int)*l);
my_bool *ret=(my_bool *)malloc(sizeof(my_bool)*l);
int i;
for (i=0;i<(int)l;i++) {
myconn->reset();
MyHGM->increase_reset_counter();
myconn=(MySQL_Connection *)conn_array->index(i);
if (myconn->mysql->net.pvio && myconn->mysql->net.fd && myconn->mysql->net.buff) {
MySQL_Connection_userinfo *userinfo = myconn->userinfo;
char *auth_password = NULL;
if (userinfo->password) {
if (userinfo->password[0]=='*') { // we don't have the real password, let's pass sha1
auth_password=userinfo->sha1_pass;
} else {
auth_password=userinfo->password;
}
}
//async_exit_status = mysql_change_user_start(&ret_bool,mysql,_ui->username, auth_password, _ui->schemaname);
// we first reset the charset to a default one.
// this to solve the problem described here:
// https://github.com/sysown/proxysql/pull/3249#issuecomment-761887970
if (myconn->mysql->charset->nr >= 255)
mysql_options(myconn->mysql, MYSQL_SET_CHARSET_NAME, myconn->mysql->charset->csname);
statuses[i]=mysql_change_user_start(&ret[i], myconn->mysql, myconn->userinfo->username, auth_password, myconn->userinfo->schemaname);
if (myconn->mysql->net.pvio==NULL || myconn->mysql->net.fd==0 || myconn->mysql->net.buff==NULL) {
statuses[i]=0; ret[i]=1;
}
} else {
statuses[i]=0;
ret[i]=1;
}
}
for (i=0;i<(int)conn_array->len;i++) {
if (statuses[i]==0) {
myconn=(MySQL_Connection *)conn_array->remove_index_fast(i);
if (!ret[i]) {
MyHGM->push_MyConn_to_pool(myconn);
} else {
myconn->send_quit=false;
MyHGM->destroy_MyConn_from_pool(myconn);
}
statuses[i]=statuses[conn_array->len];
ret[i]=ret[conn_array->len];
i--;
}
}
unsigned long long now=monotonic_time();
while (conn_array->len && ((monotonic_time() - now) < 1000000)) {
usleep(50);
for (i=0;i<(int)conn_array->len;i++) {
myconn=(MySQL_Connection *)conn_array->index(i);
if (myconn->mysql->net.pvio && myconn->mysql->net.fd && myconn->mysql->net.buff) {
statuses[i]=wait_for_mysql(myconn->mysql, statuses[i]);
if (myconn->mysql->net.pvio && myconn->mysql->net.fd && myconn->mysql->net.buff) {
if ((statuses[i] & MYSQL_WAIT_TIMEOUT) == 0) {
statuses[i]=mysql_change_user_cont(&ret[i], myconn->mysql, statuses[i]);
if (myconn->mysql->net.pvio==NULL || myconn->mysql->net.fd==0 || myconn->mysql->net.buff==NULL ) {
statuses[i]=0; ret[i]=1;
}
}
} else {
statuses[i]=0; ret[i]=1;
}
} else {
statuses[i]=0; ret[i]=1;
}
}
for (i=0;i<(int)conn_array->len;i++) {
if (statuses[i]==0) {
myconn=(MySQL_Connection *)conn_array->remove_index_fast(i);
if (!ret[i]) {
myconn->reset();
MyHGM->push_MyConn_to_pool(myconn);
} else {
myconn->send_quit=false;
MyHGM->destroy_MyConn_from_pool(myconn);
}
statuses[i]=statuses[conn_array->len];
ret[i]=ret[conn_array->len];
i--;
}
}
}
while (conn_array->len) {
// we reached here, and there are still connections
myconn=(MySQL_Connection *)conn_array->remove_index_fast(0);
myconn->send_quit=false;
MyHGM->destroy_MyConn_from_pool(myconn);
}
free(statuses);
free(errs);
free(ret);
}
delete conn_array;
}
using metric_name = std::string;
using metric_help = std::string;
using metric_tags = std::map<std::string, std::string>;
using hg_counter_tuple =
std::tuple<
p_hg_counter::metric,
metric_name,
metric_help,
metric_tags
>;
using hg_gauge_tuple =
std::tuple<
p_hg_gauge::metric,
metric_name,
metric_help,
metric_tags
>;
using hg_dyn_counter_tuple =
std::tuple<
p_hg_dyn_counter::metric,
metric_name,
metric_help,
metric_tags
>;
using hg_dyn_gauge_tuple =
std::tuple<
p_hg_dyn_gauge::metric,
metric_name,
metric_help,
metric_tags
>;
using hg_counter_vector = std::vector<hg_counter_tuple>;
using hg_gauge_vector = std::vector<hg_gauge_tuple>;
using hg_dyn_counter_vector = std::vector<hg_dyn_counter_tuple>;
using hg_dyn_gauge_vector = std::vector<hg_dyn_gauge_tuple>;
/**
* @brief Metrics map holding the metrics for the 'MySQL_HostGroups_Manager' module.
*
* @note Many metrics in this map, share a common "id name", because
* they differ only by label, because of this, HELP is shared between
* them. For better visual identification of this groups they are
* sepparated using a line separator comment.
*/
const std::tuple<
hg_counter_vector,
hg_gauge_vector,
hg_dyn_counter_vector,
hg_dyn_gauge_vector
>
hg_metrics_map = std::make_tuple(
hg_counter_vector {
std::make_tuple (
p_hg_counter::servers_table_version,
"proxysql_servers_table_version_total",
"Number of times the \"servers_table\" have been modified.",
metric_tags {}
),
// ====================================================================
std::make_tuple (
p_hg_counter::server_connections_created,
"proxysql_server_connections_total",
"Total number of server connections (created|delayed|aborted).",
metric_tags {
{ "status", "created" }
}
),
std::make_tuple (
p_hg_counter::server_connections_delayed,
"proxysql_server_connections_total",
"Total number of server connections (created|delayed|aborted).",
metric_tags {
{ "status", "delayed" }
}
),
std::make_tuple (
p_hg_counter::server_connections_aborted,
"proxysql_server_connections_total",
"Total number of server connections (created|delayed|aborted).",
metric_tags {
{ "status", "aborted" }
}
),
// ====================================================================
// ====================================================================
std::make_tuple (
p_hg_counter::client_connections_created,
"proxysql_client_connections_total",
"Total number of client connections created.",
metric_tags {
{ "status", "created" }
}
),
std::make_tuple (
p_hg_counter::client_connections_sha2cached,
"proxysql_client_connections_sha2cached_total",
"Total number of attempted client connections with known cached passwords.",
metric_tags {}
),
std::make_tuple (
p_hg_counter::client_connections_aborted,
"proxysql_client_connections_total",
"Total number of client failed connections (or closed improperly).",
metric_tags {
{ "status", "aborted" }
}
),
// ====================================================================
std::make_tuple (
p_hg_counter::com_autocommit,
"proxysql_com_autocommit_total",
"Total queries autocommited.",
metric_tags {}
),
std::make_tuple (
p_hg_counter::com_autocommit_filtered,
"proxysql_com_autocommit_filtered_total",
"Total queries filtered autocommit.",
metric_tags {}
),
std::make_tuple (
p_hg_counter::com_rollback,
"proxysql_com_rollback_total",
"Total queries rollbacked.",
metric_tags {}
),
std::make_tuple (
p_hg_counter::com_rollback_filtered,
"proxysql_com_rollback_filtered_total",
"Total queries filtered rollbacked.",
metric_tags {}
),
std::make_tuple (
p_hg_counter::com_backend_change_user,
"proxysql_com_backend_change_user_total",
"Total CHANGE_USER queries backend.",
metric_tags {}
),
std::make_tuple (
p_hg_counter::com_backend_init_db,
"proxysql_com_backend_init_db_total",
"Total queries backend INIT DB.",
metric_tags {}
),
std::make_tuple (
p_hg_counter::com_backend_set_names,
"proxysql_com_backend_set_names_total",
"Total queries backend SET NAMES.",
metric_tags {}
),
std::make_tuple (
p_hg_counter::com_frontend_init_db,
"proxysql_com_frontend_init_db_total",
"Total INIT DB queries frontend.",
metric_tags {}
),
std::make_tuple (
p_hg_counter::com_frontend_set_names,
"proxysql_com_frontend_set_names_total",
"Total SET NAMES frontend queries.",
metric_tags {}
),
std::make_tuple (
p_hg_counter::com_frontend_use_db,
"proxysql_com_frontend_use_db_total",
"Total USE DB queries frontend.",
metric_tags {}
),
std::make_tuple (
p_hg_counter::com_commit_cnt,
"proxysql_com_commit_cnt_total",
"Total queries commit.",
metric_tags {}
),
std::make_tuple (
p_hg_counter::com_commit_cnt_filtered,
"proxysql_com_commit_cnt_filtered_total",
"Total queries commit filtered.",
metric_tags {}
),
std::make_tuple (
p_hg_counter::selects_for_update__autocommit0,
"proxysql_selects_for_update__autocommit0_total",
"Total queries that are SELECT for update or equivalent.",
metric_tags {}
),
std::make_tuple (
p_hg_counter::access_denied_wrong_password,
"proxysql_access_denied_wrong_password_total",
"Total access denied \"wrong password\".",
metric_tags {}
),
std::make_tuple (
p_hg_counter::access_denied_max_connections,
"proxysql_access_denied_max_connections_total",
"Total access denied \"max connections\".",
metric_tags {}
),
std::make_tuple (
p_hg_counter::access_denied_max_user_connections,
"proxysql_access_denied_max_user_connections_total",
"Total access denied \"max user connections\".",
metric_tags {}
),
// ====================================================================
std::make_tuple (
p_hg_counter::myhgm_myconnpool_get,
"proxysql_myhgm_myconnpool_get_total",
"The number of requests made to the connection pool.",
metric_tags {}
),
std::make_tuple (
p_hg_counter::myhgm_myconnpool_get_ok,
"proxysql_myhgm_myconnpool_get_ok_total",
"The number of successful requests to the connection pool (i.e. where a connection was available).",
metric_tags {}
),
std::make_tuple (
p_hg_counter::myhgm_myconnpool_get_ping,
"proxysql_myhgm_myconnpool_get_ping_total",
"The number of connections that were taken from the pool to run a ping to keep them alive.",
metric_tags {}
),
// ====================================================================
std::make_tuple (
p_hg_counter::myhgm_myconnpool_push,
"proxysql_myhgm_myconnpool_push_total",
"The number of connections returned to the connection pool.",
metric_tags {}
),
std::make_tuple (
p_hg_counter::myhgm_myconnpool_reset,
"proxysql_myhgm_myconnpool_reset_total",
"The number of connections that have been reset / re-initialized using \"COM_CHANGE_USER\"",
metric_tags {}
),
std::make_tuple (
p_hg_counter::myhgm_myconnpool_destroy,
"proxysql_myhgm_myconnpool_destroy_total",
"The number of connections considered unhealthy and therefore closed.",
metric_tags {}
),
// ====================================================================
std::make_tuple (
p_hg_counter::auto_increment_delay_multiplex,
"proxysql_myhgm_auto_increment_multiplex_total",
"The number of times that 'auto_increment_delay_multiplex' has been triggered.",
metric_tags {}
),
},
// prometheus gauges
hg_gauge_vector {
std::make_tuple (
p_hg_gauge::server_connections_connected,
"proxysql_server_connections_connected",
"Backend connections that are currently connected.",
metric_tags {}
),
std::make_tuple (
p_hg_gauge::client_connections_connected,
"proxysql_client_connections_connected",
"Client connections that are currently connected.",
metric_tags {}
),
std::make_tuple (
p_hg_gauge::client_connections_connected_prim,
"proxysql_client_connections_connected_primary",
"Client connections that are currently connected using primary password.",
metric_tags {}
),
std::make_tuple (
p_hg_gauge::client_connections_connected_addl,
"proxysql_client_connections_connected_additional",
"Client connections that are currently connected using additional password.",
metric_tags {}
)
},
// prometheus dynamic counters
hg_dyn_counter_vector {
// connection_pool
// ====================================================================
// ====================================================================
std::make_tuple (
p_hg_dyn_counter::conn_pool_bytes_data_recv,
"proxysql_connpool_data_bytes_total",
"Amount of data (sent|recv) from the backend, excluding metadata.",
metric_tags {
{ "traffic_flow", "recv" }
}
),
std::make_tuple (
p_hg_dyn_counter::conn_pool_bytes_data_sent,
"proxysql_connpool_data_bytes_total",
"Amount of data (sent|recv) from the backend, excluding metadata.",
metric_tags {
{ "traffic_flow", "sent" }
}
),
// ====================================================================
// ====================================================================
std::make_tuple (
p_hg_dyn_counter::connection_pool_conn_err,
"proxysql_connpool_conns_total",
"How many connections have been tried to be established.",
metric_tags {
{ "status", "err" }
}
),
std::make_tuple (
p_hg_dyn_counter::connection_pool_conn_ok,
"proxysql_connpool_conns_total",
"How many connections have been tried to be established.",
metric_tags {
{ "status", "ok" }
}
),
// ====================================================================
std::make_tuple (
p_hg_dyn_counter::connection_pool_queries,
"proxysql_connpool_conns_queries_total",
"The number of queries routed towards this particular backend server.",
metric_tags {}
),
// gtid
std::make_tuple (
p_hg_dyn_counter::gtid_executed,
"proxysql_gtid_executed_total",
"Tracks the number of executed gtid per host and port.",
metric_tags {}
),
// mysql_error
std::make_tuple (
p_hg_dyn_counter::proxysql_mysql_error,
"proxysql_mysql_error_total",
"Tracks the mysql errors generated by proxysql.",
metric_tags {}
),
std::make_tuple (
p_hg_dyn_counter::mysql_error,
"mysql_error_total",
"Tracks the mysql errors encountered.",
metric_tags {}
)
},
// prometheus dynamic gauges
hg_dyn_gauge_vector {
std::make_tuple (
p_hg_dyn_gauge::connection_pool_conn_free,
"proxysql_connpool_conns",
"How many backend connections are currently (free|used).",
metric_tags {
{ "status", "free" }
}
),
std::make_tuple (
p_hg_dyn_gauge::connection_pool_conn_used,
"proxysql_connpool_conns",
"How many backend connections are currently (free|used).",
metric_tags {
{ "status", "used" }
}
),
std::make_tuple (
p_hg_dyn_gauge::connection_pool_latency_us,
"proxysql_connpool_conns_latency_us",
"The currently ping time in microseconds, as reported from Monitor.",
metric_tags {}
),
std::make_tuple (
p_hg_dyn_gauge::connection_pool_status,
"proxysql_connpool_conns_status",
"The status of the backend server (1 - ONLINE, 2 - SHUNNED, 3 - OFFLINE_SOFT, 4 - OFFLINE_HARD, 5 - SHUNNED_REPLICATION_LAG).",
metric_tags {}
)
}
);
MySQL_HostGroups_Manager::MySQL_HostGroups_Manager() {
status.client_connections=0;
status.client_connections_prim_pass=0;
status.client_connections_addl_pass=0;
status.client_connections_aborted=0;
status.client_connections_created=0;
status.client_connections_sha2cached=0;
status.server_connections_connected=0;
status.server_connections_aborted=0;
status.server_connections_created=0;
status.server_connections_delayed=0;
status.servers_table_version=0;
pthread_mutex_init(&status.servers_table_version_lock, NULL);
pthread_cond_init(&status.servers_table_version_cond, NULL);
status.myconnpoll_get=0;
status.myconnpoll_get_ok=0;
status.myconnpoll_get_ping=0;
status.myconnpoll_push=0;
status.myconnpoll_destroy=0;
status.myconnpoll_reset=0;
status.autocommit_cnt=0;
status.commit_cnt=0;
status.rollback_cnt=0;
status.autocommit_cnt_filtered=0;
status.commit_cnt_filtered=0;
status.rollback_cnt_filtered=0;
status.backend_change_user=0;
status.backend_init_db=0;
status.backend_set_names=0;
status.frontend_init_db=0;
status.frontend_set_names=0;
status.frontend_use_db=0;
status.access_denied_wrong_password=0;
status.access_denied_max_connections=0;
status.access_denied_max_user_connections=0;
status.select_for_update_or_equivalent=0;
status.auto_increment_delay_multiplex=0;
#if 0
pthread_mutex_init(&readonly_mutex, NULL);
#endif // 0
pthread_mutex_init(&Group_Replication_Info_mutex, NULL);
pthread_mutex_init(&Galera_Info_mutex, NULL);
pthread_mutex_init(&AWS_Aurora_Info_mutex, NULL);
#if 0
pthread_mutex_init(&lock, NULL);
admindb=NULL; // initialized only if needed
mydb=new SQLite3DB();
#endif // 0
#ifdef DEBUG
mydb->open((char *)"file:mem_mydb?mode=memory&cache=shared", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX);
#else
mydb->open((char *)"file:mem_mydb?mode=memory", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX);
#endif /* DEBUG */
mydb->execute(MYHGM_MYSQL_SERVERS);
mydb->execute(MYHGM_MYSQL_SERVERS_INCOMING);
mydb->execute(MYHGM_MYSQL_REPLICATION_HOSTGROUPS);
mydb->execute(MYHGM_MYSQL_GROUP_REPLICATION_HOSTGROUPS);
mydb->execute(MYHGM_MYSQL_GALERA_HOSTGROUPS);
mydb->execute(MYHGM_MYSQL_AWS_AURORA_HOSTGROUPS);
mydb->execute(MYHGM_MYSQL_HOSTGROUP_ATTRIBUTES);
mydb->execute(MYHGM_MYSQL_SERVERS_SSL_PARAMS);
mydb->execute("CREATE INDEX IF NOT EXISTS idx_mysql_servers_hostname_port ON mysql_servers (hostname,port)");
MyHostGroups=new PtrArray();
runtime_mysql_servers=NULL;
incoming_replication_hostgroups=NULL;
incoming_group_replication_hostgroups=NULL;
incoming_galera_hostgroups=NULL;
incoming_aws_aurora_hostgroups = NULL;
incoming_hostgroup_attributes = NULL;
incoming_mysql_servers_ssl_params = NULL;
incoming_mysql_servers_v2 = NULL;
pthread_rwlock_init(>id_rwlock, NULL);
gtid_missing_nodes = false;
gtid_ev_loop=NULL;
gtid_ev_timer=NULL;
gtid_ev_async = (struct ev_async *)malloc(sizeof(struct ev_async));
mysql_servers_to_monitor = NULL;
{
static const char alphanum[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
rand_del[0] = '-';
for (int i = 1; i < 6; i++) {
rand_del[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
}
rand_del[6] = '-';
rand_del[7] = 0;
}
pthread_mutex_init(&mysql_errors_mutex, NULL);
// Initialize prometheus metrics
init_prometheus_counter_array<hg_metrics_map_idx, p_hg_counter>(hg_metrics_map, this->status.p_counter_array);
init_prometheus_gauge_array<hg_metrics_map_idx, p_hg_gauge>(hg_metrics_map, this->status.p_gauge_array);
init_prometheus_dyn_counter_array<hg_metrics_map_idx, p_hg_dyn_counter>(hg_metrics_map, this->status.p_dyn_counter_array);
init_prometheus_dyn_gauge_array<hg_metrics_map_idx, p_hg_dyn_gauge>(hg_metrics_map, this->status.p_dyn_gauge_array);
pthread_mutex_init(&mysql_errors_mutex, NULL);
}
void MySQL_HostGroups_Manager::init() {
//conn_reset_queue = NULL;
//conn_reset_queue = new wqueue<MySQL_Connection *>();
HGCU_thread = new std::thread(&HGCU_thread_run);
//pthread_create(&HGCU_thread_id, NULL, HGCU_thread_run , NULL);
// gtid initialization;
GTID_syncer_thread = new std::thread(>ID_syncer_run);
//pthread_create(>ID_syncer_thread_id, NULL, GTID_syncer_run , NULL);
}
void MySQL_HostGroups_Manager::shutdown() {
queue.add(NULL);
HGCU_thread->join();
delete HGCU_thread;
ev_async_send(gtid_ev_loop, gtid_ev_async);
GTID_syncer_thread->join();
delete GTID_syncer_thread;
}
MySQL_HostGroups_Manager::~MySQL_HostGroups_Manager() {
while (MyHostGroups->len) {
MyHGC *myhgc=(MyHGC *)MyHostGroups->remove_index_fast(0);
delete myhgc;
}
delete MyHostGroups;
delete mydb;
if (admindb) {
delete admindb;
}
for (auto info : AWS_Aurora_Info_Map)
delete info.second;
free(gtid_ev_async);
if (gtid_ev_loop)
ev_loop_destroy(gtid_ev_loop);
if (gtid_ev_timer)
free(gtid_ev_timer);
pthread_mutex_destroy(&lock);
}
void MySQL_HostGroups_Manager::p_update_mysql_error_counter(p_mysql_error_type err_type, unsigned int hid, char* address, uint16_t port, unsigned int code) {
p_hg_dyn_counter::metric metric = p_hg_dyn_counter::mysql_error;
if (err_type == p_mysql_error_type::proxysql) {
metric = p_hg_dyn_counter::proxysql_mysql_error;
}
std::string s_hostgroup = std::to_string(hid);
std::string s_address = std::string(address);
std::string s_port = std::to_string(port);
// TODO: Create switch here to classify error codes
std::string s_code = std::to_string(code);
std::string metric_id = s_hostgroup + ":" + address + ":" + s_port + ":" + s_code;
std::map<string, string> metric_labels {
{ "hostgroup", s_hostgroup },
{ "address", address },
{ "port", s_port },
{ "code", s_code }
};
pthread_mutex_lock(&mysql_errors_mutex);
p_inc_map_counter(
status.p_mysql_errors_map,
status.p_dyn_counter_array[metric],
metric_id,
metric_labels
);
pthread_mutex_unlock(&mysql_errors_mutex);
}
void MySQL_HostGroups_Manager::wait_servers_table_version(unsigned v, unsigned w) {
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
//ts.tv_sec += w;
unsigned int i = 0;
int rc = 0;
pthread_mutex_lock(&status.servers_table_version_lock);
while ((rc == 0 || rc == ETIMEDOUT) && (i < w) && (__sync_fetch_and_add(&glovars.shutdown,0)==0) && (__sync_fetch_and_add(&status.servers_table_version,0) < v)) {
i++;
ts.tv_sec += 1;
rc = pthread_cond_timedwait( &status.servers_table_version_cond, &status.servers_table_version_lock, &ts);
}
pthread_mutex_unlock(&status.servers_table_version_lock);
}
unsigned int MySQL_HostGroups_Manager::get_servers_table_version() {
return __sync_fetch_and_add(&status.servers_table_version,0);
}
// we always assume that the calling thread has acquired a rdlock()
int MySQL_HostGroups_Manager::servers_add(SQLite3_result *resultset) {
if (resultset==NULL) {
return 0;
}
int rc;
mydb->execute("DELETE FROM mysql_servers_incoming");
sqlite3_stmt *statement1=NULL;
sqlite3_stmt *statement32=NULL;
//sqlite3 *mydb3=mydb->get_db();
char *query1=(char *)"INSERT INTO mysql_servers_incoming VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)";
std::string query32s = "INSERT INTO mysql_servers_incoming VALUES " + generate_multi_rows_query(32,12);
char *query32 = (char *)query32s.c_str();
//rc=(*proxy_sqlite3_prepare_v2)(mydb3, query1, -1, &statement1, 0);
rc = mydb->prepare_v2(query1, &statement1);
ASSERT_SQLITE_OK(rc, mydb);
//rc=(*proxy_sqlite3_prepare_v2)(mydb3, query32, -1, &statement32, 0);
rc = mydb->prepare_v2(query32, &statement32);
ASSERT_SQLITE_OK(rc, mydb);
MySerStatus status1=MYSQL_SERVER_STATUS_ONLINE;
int row_idx=0;
int max_bulk_row_idx=resultset->rows_count/32;
max_bulk_row_idx=max_bulk_row_idx*32;
for (std::vector<SQLite3_row *>::iterator it = resultset->rows.begin() ; it != resultset->rows.end(); ++it) {
SQLite3_row *r1=*it;
status1=MYSQL_SERVER_STATUS_ONLINE;
if (strcasecmp(r1->fields[4],"ONLINE")) {
if (!strcasecmp(r1->fields[4],"SHUNNED")) {
status1=MYSQL_SERVER_STATUS_SHUNNED;
} else {
if (!strcasecmp(r1->fields[4],"OFFLINE_SOFT")) {
status1=MYSQL_SERVER_STATUS_OFFLINE_SOFT;
} else {
if (!strcasecmp(r1->fields[4],"OFFLINE_HARD")) {
status1=MYSQL_SERVER_STATUS_OFFLINE_HARD;
}
}
}
}
int idx=row_idx%32;
if (row_idx<max_bulk_row_idx) { // bulk
rc=(*proxy_sqlite3_bind_int64)(statement32, (idx*12)+1, atoi(r1->fields[0])); ASSERT_SQLITE_OK(rc, mydb);
rc=(*proxy_sqlite3_bind_text)(statement32, (idx*12)+2, r1->fields[1], -1, SQLITE_TRANSIENT); ASSERT_SQLITE_OK(rc, mydb);
rc=(*proxy_sqlite3_bind_int64)(statement32, (idx*12)+3, atoi(r1->fields[2])); ASSERT_SQLITE_OK(rc, mydb);
rc=(*proxy_sqlite3_bind_int64)(statement32, (idx*12)+4, atoi(r1->fields[3])); ASSERT_SQLITE_OK(rc, mydb);
rc=(*proxy_sqlite3_bind_int64)(statement32, (idx*12)+5, atoi(r1->fields[5])); ASSERT_SQLITE_OK(rc, mydb);
rc=(*proxy_sqlite3_bind_int64)(statement32, (idx*12)+6, status1); ASSERT_SQLITE_OK(rc, mydb);
rc=(*proxy_sqlite3_bind_int64)(statement32, (idx*12)+7, atoi(r1->fields[6])); ASSERT_SQLITE_OK(rc, mydb);
rc=(*proxy_sqlite3_bind_int64)(statement32, (idx*12)+8, atoi(r1->fields[7])); ASSERT_SQLITE_OK(rc, mydb);
rc=(*proxy_sqlite3_bind_int64)(statement32, (idx*12)+9, atoi(r1->fields[8])); ASSERT_SQLITE_OK(rc, mydb);
rc=(*proxy_sqlite3_bind_int64)(statement32, (idx*12)+10, atoi(r1->fields[9])); ASSERT_SQLITE_OK(rc, mydb);
rc=(*proxy_sqlite3_bind_int64)(statement32, (idx*12)+11, atoi(r1->fields[10])); ASSERT_SQLITE_OK(rc, mydb);
rc=(*proxy_sqlite3_bind_text)(statement32, (idx*12)+12, r1->fields[11], -1, SQLITE_TRANSIENT); ASSERT_SQLITE_OK(rc, mydb);
if (idx==31) {
SAFE_SQLITE3_STEP2(statement32);
rc=(*proxy_sqlite3_clear_bindings)(statement32); ASSERT_SQLITE_OK(rc, mydb);
rc=(*proxy_sqlite3_reset)(statement32); ASSERT_SQLITE_OK(rc, mydb);
}
} else { // single row
rc=(*proxy_sqlite3_bind_int64)(statement1, 1, atoi(r1->fields[0])); ASSERT_SQLITE_OK(rc, mydb);
rc=(*proxy_sqlite3_bind_text)(statement1, 2, r1->fields[1], -1, SQLITE_TRANSIENT); ASSERT_SQLITE_OK(rc, mydb);
rc=(*proxy_sqlite3_bind_int64)(statement1, 3, atoi(r1->fields[2])); ASSERT_SQLITE_OK(rc, mydb);
rc=(*proxy_sqlite3_bind_int64)(statement1, 4, atoi(r1->fields[3])); ASSERT_SQLITE_OK(rc, mydb);
rc=(*proxy_sqlite3_bind_int64)(statement1, 5, atoi(r1->fields[5])); ASSERT_SQLITE_OK(rc, mydb);
rc=(*proxy_sqlite3_bind_int64)(statement1, 6, status1); ASSERT_SQLITE_OK(rc, mydb);
rc=(*proxy_sqlite3_bind_int64)(statement1, 7, atoi(r1->fields[6])); ASSERT_SQLITE_OK(rc, mydb);
rc=(*proxy_sqlite3_bind_int64)(statement1, 8, atoi(r1->fields[7])); ASSERT_SQLITE_OK(rc, mydb);
rc=(*proxy_sqlite3_bind_int64)(statement1, 9, atoi(r1->fields[8])); ASSERT_SQLITE_OK(rc, mydb);
rc=(*proxy_sqlite3_bind_int64)(statement1, 10, atoi(r1->fields[9])); ASSERT_SQLITE_OK(rc, mydb);
rc=(*proxy_sqlite3_bind_int64)(statement1, 11, atoi(r1->fields[10])); ASSERT_SQLITE_OK(rc, mydb);
rc=(*proxy_sqlite3_bind_text)(statement1, 12, r1->fields[11], -1, SQLITE_TRANSIENT); ASSERT_SQLITE_OK(rc, mydb);
SAFE_SQLITE3_STEP2(statement1);
rc=(*proxy_sqlite3_clear_bindings)(statement1); ASSERT_SQLITE_OK(rc, mydb);
rc=(*proxy_sqlite3_reset)(statement1); ASSERT_SQLITE_OK(rc, mydb);
}
row_idx++;
}
(*proxy_sqlite3_finalize)(statement1);
(*proxy_sqlite3_finalize)(statement32);
return 0;
}
/**
* @brief Calculate and update the checksum for a specified table in the database.
*
* This function calculates the checksum for a specified table in the database using the provided SpookyHash object.
* The checksum is computed based on the table's contents, sorted by the specified column name. If the initialization
* flag is false, the SpookyHash object is initialized with predefined parameters. The calculated checksum is stored
* in the raw_checksum parameter.
*
* @param myhash A reference to the SpookyHash object used for calculating the checksum.
* @param init A reference to a boolean flag indicating whether the SpookyHash object has been initialized.
* @param TableName The name of the table for which the checksum is to be calculated.
* @param ColumnName The name of the column to be used for sorting the table before calculating the checksum.
* @param raw_checksum A reference to a uint64_t variable where the calculated checksum will be stored.
*/
void MySQL_HostGroups_Manager::CUCFT1(
SpookyHash& myhash, bool& init, const string& TableName, const string& ColumnName, uint64_t& raw_checksum
) {
char *error=NULL;
int cols=0;
int affected_rows=0;
SQLite3_result *resultset=NULL;
string query = "SELECT * FROM " + TableName + " ORDER BY " + ColumnName;
mydb->execute_statement(query.c_str(), &error , &cols , &affected_rows , &resultset);
if (resultset) {
if (resultset->rows_count) {
if (init == false) {
init = true;
myhash.Init(19,3);
}
uint64_t hash1_ = resultset->raw_checksum();
raw_checksum = hash1_;
myhash.Update(&hash1_, sizeof(hash1_));
proxy_info("Checksum for table %s is 0x%lX\n", TableName.c_str(), hash1_);
}
delete resultset;
} else {
proxy_info("Checksum for table %s is 0x%lX\n", TableName.c_str(), (long unsigned int)0);
}
}
/**
* @brief Compute and update checksum values for specified tables.
*
* This function computes checksum values for specified tables by executing checksum calculation queries for each table.
* It updates the checksum values in the `table_resultset_checksum` array.
*
* @param myhash A reference to a SpookyHash object used for computing the checksums.
* @param init A reference to a boolean flag indicating whether the checksum computation has been initialized.
* @note This function resets the current checksum values for all tables except MYSQL_SERVERS and MYSQL_SERVERS_V2
* before recomputing the checksums.
* @note The computed checksum values are stored in the `table_resultset_checksum` array.
*/
void MySQL_HostGroups_Manager::commit_update_checksums_from_tables(SpookyHash& myhash, bool& init) {
// Always reset the current table values before recomputing
for (size_t i = 0; i < table_resultset_checksum.size(); i++) {
if (i != HGM_TABLES::MYSQL_SERVERS && i != HGM_TABLES::MYSQL_SERVERS_V2) {
table_resultset_checksum[i] = 0;
}
}
CUCFT1(myhash,init,"mysql_replication_hostgroups","writer_hostgroup", table_resultset_checksum[HGM_TABLES::MYSQL_REPLICATION_HOSTGROUPS]);
CUCFT1(myhash,init,"mysql_group_replication_hostgroups","writer_hostgroup", table_resultset_checksum[HGM_TABLES::MYSQL_GROUP_REPLICATION_HOSTGROUPS]);
CUCFT1(myhash,init,"mysql_galera_hostgroups","writer_hostgroup", table_resultset_checksum[HGM_TABLES::MYSQL_GALERA_HOSTGROUPS]);
CUCFT1(myhash,init,"mysql_aws_aurora_hostgroups","writer_hostgroup", table_resultset_checksum[HGM_TABLES::MYSQL_AWS_AURORA_HOSTGROUPS]);
CUCFT1(myhash,init,"mysql_hostgroup_attributes","hostgroup_id", table_resultset_checksum[HGM_TABLES::MYSQL_HOSTGROUP_ATTRIBUTES]);
CUCFT1(myhash,init,"mysql_servers_ssl_params","hostname,port,username", table_resultset_checksum[HGM_TABLES::MYSQL_SERVERS_SSL_PARAMS]);
}
/**
* @brief This code updates the 'hostgroup_server_mapping' table with the most recent mysql_servers and mysql_replication_hostgroups
* records while utilizing checksums to prevent unnecessary updates.
*
* IMPORTANT: Make sure wrlock() is called before calling this method.
*
*/
void MySQL_HostGroups_Manager::update_hostgroup_manager_mappings() {
if (hgsm_mysql_servers_checksum != table_resultset_checksum[HGM_TABLES::MYSQL_SERVERS] ||
hgsm_mysql_replication_hostgroups_checksum != table_resultset_checksum[HGM_TABLES::MYSQL_REPLICATION_HOSTGROUPS])
{
proxy_info("Rebuilding 'Hostgroup_Manager_Mapping' due to checksums change - mysql_servers { old: 0x%lX, new: 0x%lX }, mysql_replication_hostgroups { old:0x%lX, new:0x%lX }\n",
hgsm_mysql_servers_checksum, table_resultset_checksum[HGM_TABLES::MYSQL_SERVERS],
hgsm_mysql_replication_hostgroups_checksum, table_resultset_checksum[HGM_TABLES::MYSQL_REPLICATION_HOSTGROUPS]);
char* error = NULL;