-
Notifications
You must be signed in to change notification settings - Fork 79
/
percona-scheduler-admin
executable file
·3251 lines (2799 loc) · 111 KB
/
percona-scheduler-admin
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
#!/bin/bash
# This script will assist with configuring ProxySQL
# (currently only Percona XtraDB cluster in combination with ProxySQL is supported)
# Version 2.0
###############################################################################################
# This program is copyright 2016-2022 Percona LLC and/or its affiliates.
#
# THIS PROGRAM IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
# WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation, version 2 or later
#
# You should have received a copy of the GNU General Public License version 2
# along with this program; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
# shellcheck disable=SC2046,SC2181,SC2086,SC1091
#-------------------------------------------------------------------------------
#
# Step 1 : Bash internal configuration
#
set -o nounset # no undefined variables
set -o pipefail # internal pipe failures cause an exit
# Include the common functions
. $(dirname ${BASH_SOURCE[0]})/proxysql-common
. $(dirname ${BASH_SOURCE[0]})/proxysql-admin-common
#-------------------------------------------------------------------------------
#
# Step 2 : Global variables
#
#
# Script parameters/constants
#
# default timeout is 10 seconds
declare -i TIMEOUT=10
#
# Global variables used by the script
#
declare CONFIG_FILE=""
declare CONFIG_PATH
declare CONFIG_FILENAME
#
# Location of executables
#
declare MY_PRINT_DEFAULTS=""
declare SCHEDULER_BINARY=""
# Variables declared in proxysql-common
# ----------------------------------------
# readonly PROXYSQL_ADMIN_VERSION="2.0.12"
# readonly REQUIRED_OPENSSL_VERSION="1.1.1"
# readonly PROXYSQL_ADMIN_OPENSSL_NAME="proxysql-admin-openssl"
# declare -i DEBUG=0
# declare PROXYSQL_USERNAME=""
# declare PROXYSQL_PASSWORD=""
# declare PROXYSQL_PORT=""
# declare PROXYSQL_HOSTNAME=""
# declare CLUSTER_USERNAME=""
# declare CLUSTER_PASSWORD=""
# declare CLUSTER_HOSTNAME=""
# declare CLUSTER_PORT=""
# declare CLUSTER_APP_USERNAME=""
# declare CLUSTER_APP_PASSWORD=""
# declare MONITOR_USERNAME=""
# declare MONITOR_PASSWORD=""
# The SAFE_XXX versions are the version that have
# been escaped. The single quotes will have been
# SQL-escaped, which means ' -> ''
# So these are the versions that should be used in any SQL query.
declare SAFE_MONITOR_USERNAME=""
declare SAFE_MONITOR_PASSWORD=""
declare LOCK_FILE_PATH=""
declare WRITE_NODE=""
declare UPDATE_READ_WEIGHT=""
declare UPDATE_WRITE_WEIGHT=""
declare MODE="singlewrite"
declare -i NODE_CHECK_INTERVAL=-1
declare -i WRITER_HOSTGROUP_ID=-1
declare -i READER_HOSTGROUP_ID=-1
declare -i WRITER_CONFIG_HOSTGROUP_ID=-1
declare -i READER_CONFIG_HOSTGROUP_ID=-1
declare -i WRITER_MAINT_HOSTGROUP_ID=-1
declare -i READER_MAINT_HOSTGROUP_ID=-1
declare -i AUTO_ASSIGN_WEIGHTS=0
declare -i QUICK_DEMO=0
declare -i ENABLE=0
declare -i DISABLE=0
declare -i ADDUSER=0
declare -i SYNCUSERS=0
declare -i SYNCMULTICLUSTERUSERS=0
declare -i ADD_QUERY_RULE=0
declare -i UPDATE_CLUSTER=0
declare -i UPDATE_MYSQL_VERSION=0
declare -i CHECK_IF_ENABLED=0
declare -i FORCE=0
declare -i REPORT_STATUS=0
# This can be specifed by the "--server=IP:PORT" option for
# a single address. This is used by --syncusers to sync a
# single node (that does not need to be part of a cluster)
declare SINGLE_SERVER=""
# For the scheduler-admin, we do not allow prompts, so just
# use the existing monitor password
declare -i USE_EXISTING_MONITOR_PASSWORD=1
declare -i WITH_CLUSTER_APP_USER=1
declare -i DISABLE_UPDATES=0
# If we have to disable updates, store the original values
# so that we can restore them back to these values.
# These variables have the value of 'true' | 'false'
declare ADMIN_CHECKSUM_MYSQL_QUERY_RULES_ORIGINAL_VALUE=""
declare ADMIN_CHECKSUM_MYSQL_SERVERS_ORIGINAL_VALUE=""
declare ADMIN_CHECKSUM_MYSQL_USERS_ORIGINAL_VALUE=""
declare ADMIN_CLUSTER_USERNAME_ORIGINAL_VALUE=""
declare ADMIN_CLUSTER_CHECK_INTERVAL_ORIGINAL_VALUE=""
declare MYSQL_CLIENT_VERSION=""
# SSL options
declare -i USE_SSL_OPTION=0
declare SSL_CERTIFICATE_PATH=""
#
# Default value for max_connections in mysql_servers
#
declare MAX_CONNECTIONS="1000"
declare -i WRITERS_ARE_READERS_OPTION=-1
declare -i REMOVE_ALL_SERVERS=0
#
# If set to 1, then calls to MySQL/ProxySQL via the MySQL client
# will have credentials passed via stdin rather than using bash
# process substitution.
#
declare USE_STDIN_FOR_CREDENTIALS=0
#-------------------------------------------------------------------------------
#
# Step 3 : Helper functions
#
#
# Dispay script usage details
#
function usage() {
local path=$0
cat << EOF
Usage: ${path##*/} [ options ]
You must include at least one option. Independent options do not require another
option to run successfully. Dependent options require another option to run
successfully. If you run a dependent option without the required option you see
an error message and the option does not run.
These options can be run without another option:
--adduser Adds the Percona XtraDB Cluster application user to the ProxySQL database
--config-file=<config-file> Read login credentials from a configuration file
(command line options override any configuration file values)
--debug Enables additional debug logging.
--disable, -d Removes any Percona XtraDB Cluster configurations from ProxySQL
--disable-updates Disable admin updates for ProxySQL cluster for the
current operation. The default is to not change the
admin variable settings. If this option is specifed,
these options will be set to false.
(default: updates are not disabled)
--enable, -e Auto-configure Percona XtraDB Cluster nodes into ProxySQL
--help Displays this help text.
--is-enabled Checks if the current configuration is enabled in ProxySQL.
--status Returns a status report on the current configuration.
--trace Enables shell-level tracing for this shell script
--update-cluster Updates the cluster membership, adds new cluster nodes
to the configuration.
--update-mysql-version Updates the mysql-server_version variable in ProxySQL with the version
from a node in the cluster.
--use-stdin-for-credentials If set, then the MySQL client uses stdin to send credentials
to the client (instead of process substition).
(default: process subsitution is used)
--version, -v Prints the version info
The following options require another option or a specific mode. Running these
options by themselves or with an incorrect option causes an error.
--add-query-rule Creates query rules for synced mysql user. This is applicable only
for singlewrite mode and works only with '--syncusers'
and '--sync-multi-cluster-users' options.
--auto-assign-weights When used with '--update-cluster', this option will auto assign
the weights if in 'singlewrite' mode.
--force Skips existing configuration checks in mysql_servers,
mysql_users and mysql_galera_hostgroups tables. This option will
work with '--enable' and '--update-cluster'.
This will also cause certain checks to issue warnings instead
of an error.
--remove-all-servers When used with '--update-cluster', this will remove all
servers belonging to the current cluster before
updating the list.
--server=<IPADDRESS>:<PORT> This option can be used with --syncusers or
--sync-multi-cluster-users to sync a single non-cluster server
node.
--syncusers Sync user accounts currently configured in MySQL to ProxySQL
May be used with '--enable'. '--server' may be used with this
to specify a single server to sync.
NOTE: This option deletes the ProxySQL users not present in MySQL.
--sync-multi-cluster-users Sync user accounts currently configured in MySQL to ProxySQL
May be used with '--enable'. '--server' may be used with this
to specify a single server to sync.
NOTE: This option works in the same way as --syncusers but does not
delete ProxySQL users not present in MySQL. It's indicated to be
used when syncing proxysql instances that manage multiple clusters.
--update-read-weight=<IP:PORT,WT> When used with '--update-cluster', this option will assign the
specified read weight to the given node.
--update-write-weight=<IP:PORT,WT> When used with '--update-cluster', this option will assign the
specified write weight to the given node.
--write-node=<IPADDRESS>:<PORT> Specifies the node that is to be used for writes for singlewrite mode.
If left unspecified, the cluster node is then used as the write node.
This only applies when 'mode=singlewrite' is used.
EOF
}
#
# Prints out the script version
#
# Globals:
# PROXYSQL_ADMIN_VERSION
#
# Parameters:
# None
#
function version()
{
local path=$0
printf "%s Version: %s\n" "${path##*/}" "${PROXYSQL_ADMIN_VERSION}"
printf "%s\n" "$($SCHEDULER_BINARY --version)"
}
# Reads in the given line from the section in a config file
#
# Globals:
# MY_PRINT_DEFAULTS (this must be setup beforehand)
#
# Arguments:
# 1: lineno
# 2: the path to the config file
# 3: the section in the config file
# 4: the option name
# 5: default value (if option does not exist)
# 6: required (set to 1 if a required value)
#
# Output:
# Writes out the value of the option to stdout (if found)
# Writes out the error message to stderr
#
# Returns:
# 0 (success) : if value is found
# if value is not found (returns 0 if not required)
# 1 (failure) : if value is not found and is required
#
function read_from_config_file()
{
local lineno=$1
local config_path="$2"
local section=$3
local option=$4
local default=$5
local required=$6
local retval
retval=$(${MY_PRINT_DEFAULTS} --defaults-file="${config_path}" --show "${section}" | \
awk -F= '{
sub(/^--loose/,"-",$0);
st=index($0,"="); \
cur=$0; \
if ($1 ~ /_/) \
{ gsub(/_/,"-",$1);} \
if (st != 0) \
{ print $1"="substr(cur,st+1) } \
else { print cur }
}' | grep -- "--${option}=" | cut -d= -f2- | tail -1)
# use default if we haven't found a value
if [[ -z ${retval} ]]; then
[[ -n ${default} ]] && retval=${default}
if [[ $required -eq 1 ]]; then
# This is a required value
error "$LINENO" "Cannot find a required value : '${option}' in section '${section}'" \
"\n-- in the config file:${config_path}"
echo "${retval}"
return 1
fi
fi
echo "${retval}"
return 0
}
# Executes a SQL query with the (fully) specified server
#
# Globals:
# DEBUG
# TIMEOUT
#
# Arguments:
# 1: lineno
# 2: the name of the user
# 3: the user's password
# 4: the hostname of the server
# 5: the port used to connect to the server
# 6: the query to be run
# 7: (optional) arguments to the mysql client
# 8: (optional) additional options, space separated
# Available options:
# "hide_output"
# This will not show the output of the query when DEBUG is set.
# Used to stop the display of sensitve information (such as passwords)
# from being displayed when debugging.
#
function exec_sql() {
local lineno=$1
local user=$2
local password=$3
local hostname=$4
local port=$5
local query=$6
local args=""
local more_options=""
local retvalue
local retoutput
local default_auth=""
local defaults=""
if [[ $# -ge 7 ]]; then
args=$7
fi
if [[ $# -ge 8 ]]; then
more_options=$8
fi
debug "$lineno" "exec_sql : $user@$hostname:$port ==> $query"
if [[ $MYSQL_CLIENT_VERSION == "8.0" ]]; then
default_auth="default-auth=mysql_native_password"
fi
defaults=$(printf '[client]\nuser=%s\npassword="%s"\nhost=%s\nport=%s\nconnect-timeout=%s\n%s' \
"${user}" \
"${password}" \
"${hostname}" \
"${port}" \
"${TIMEOUT}" \
"${default_auth}"
)
if [[ $USE_STDIN_FOR_CREDENTIALS -eq 1 ]]; then
retoutput=$(printf "%s" "${defaults}" | mysql --defaults-file=/dev/stdin --protocol=tcp --unbuffered --batch --silent ${args} -e "$query")
retvalue=$?
else
retoutput=$(mysql --defaults-file=<(echo "${defaults}") --protocol=tcp --unbuffered --batch --silent ${args} -e "$query")
retvalue=$?
fi
if [[ $DEBUG -eq 1 ]]; then
local number_of_newlines=0
local dbgoutput=$retoutput
if [[ " $more_options " =~ [[:space:]]hide_output[[:space:]] ]]; then
dbgoutput="**** data hidden ****"
fi
if [[ -n $dbgoutput ]]; then
number_of_newlines=$(printf "%s" "${dbgoutput}" | wc -l)
fi
if [[ $retvalue -ne 0 ]]; then
debug "" "--> query failed $retvalue"
elif [[ -z $dbgoutput ]]; then
debug "" "--> query returned $retvalue : <query returned no data>"
elif [[ ${number_of_newlines} -eq 0 ]]; then
debug "" "--> query returned $retvalue : ${dbgoutput}"
else
debug "" "--> query returned $retvalue : <data follows>"
printf "%s\n" "${dbgoutput}" | while IFS= read -r line; do
debug "" "----> $line"
done
fi
fi
printf "%s" "${retoutput}"
return $retvalue
}
# Executes a SQL query on proxysql
#
# Globals:
# PROXYSQL_USERNAME
# PROXYSQL_PASSWORD
# PROXYSQL_HOSTNAME
# PROXYSQL_PORT
#
# Arguments:
# 1: lineno
# 2: The SQL query
# 3: (optional) Additional arguments to the mysql client for the query
# 4: (optional) more options, see exec_sql
#
function proxysql_exec() {
local lineno=$1
local query=$2
local args=""
local more_options=""
if [[ $# -ge 3 ]]; then
args=$3
fi
if [[ -z $args ]]; then
args="--skip-column_names"
fi
if [[ $# -ge 4 ]]; then
more_options=$4
fi
exec_sql "$lineno" "$PROXYSQL_USERNAME" "$PROXYSQL_PASSWORD" \
"$PROXYSQL_HOSTNAME" "$PROXYSQL_PORT" \
"$query" "$args" "$more_options"
return $?
}
# Executes a SQL query on a specific node in the cluster
#
# Globals:
# CLUSTER_USERNAME
# CLUSTER_PASSWORD
#
# Arguments:
# 1: lineno
# 2: cluster host
# 3: cluster port
# 4: The SQL query
# 5: Additional arguments to the mysql client for the query
# 6: (optional) more options, see exec_sql
#
function cluster_exec() {
local lineno=$1
local cluster_host=$2
local cluster_port=$3
local query=$4
local args=""
local more_options=""
if [[ $# -ge 5 ]]; then
args=$5
fi
if [[ $# -ge 6 ]]; then
more_options=$6
fi
exec_sql "$lineno" "$CLUSTER_USERNAME" "$CLUSTER_PASSWORD" \
"$cluster_host" "$cluster_port" \
"$query" "$args" "$more_options"
return $?
}
# Executes a SQL query on the CLUSTER_HOSTNAME/CLUSTER_PORT
# specified in the config file.
#
# Globals:
# CLUSTER_USERNAME
# CLUSTER_PASSWORD
# CLUSTER_HOSTNAME
# CLUSTER_PORT
#
# Arguments:
# 1: lineno
# 2: The SQL query
# 3: Additional arguments to the mysql client for the query
# 4: (optional) more options, see exec_sql
#
function mysql_exec() {
local lineno=$1
local query=$2
local args=""
local more_options=""
if [[ $# -ge 3 ]]; then
args=$3
fi
if [[ $# -ge 4 ]]; then
more_options=$4
fi
cluster_exec "$lineno" "$CLUSTER_HOSTNAME" "$CLUSTER_PORT" \
"$query" "$args" "$more_options"
return $?
}
# Executes a SQL query on a cluster ndde with the monitor credentials
#
# Globals:
# CLUSTER_HOSTNAME
# CLUSTER_PORT
#
# Arguments:
# 1: lineno
# 2: The monitor username
# 3: The monitor password
# 4: Additional arguments to the mysql client for the query
# 5: The SQL query
# 6: (optional) more options, see exec_sql
#
function monitor_exec() {
local lineno=$1
local user=$2
local password=$3
local args=$4
local query=$5
local more_options=""
if [[ $# -ge 6 ]]; then
more_options=$7
fi
exec_sql "$lineno" "$user" "$password" \
"$CLUSTER_HOSTNAME" "$CLUSTER_PORT" \
"$query" "$args" "$more_options"
return $?
}
# Check proxysql running status
#
# Globals:
# None
#
# Arguments:
# None
#
# Exits if we could not connect to the proxysql instance
#
function proxysql_connection_check() {
proxysql_exec "$LINENO" "SELECT 1" >/dev/null
check_cmd $? "$LINENO" "ProxySQL connection check failed."\
"\n-- Could not connect to ProxySQL at $PROXYSQL_HOSTNAME:$PROXYSQL_PORT"\
"\n-- Please check the ProxySQL connection parameters and status."
debug "$LINENO" "ProxySQL connection check succeeded"
}
# Check the PXC cluster running status
# (well one node in the cluster anyway)
#
# Globals:
# None
#
# Arguments:
# None
#
# Exits if we could not connect to a cluster node
#
function cluster_connection_check() {
mysql_exec "$LINENO" "SELECT @@PORT" >/dev/null
check_cmd $? "$LINENO" "Server connection check failed."\
"\n-- Could not connect to the server at $CLUSTER_HOSTNAME:$CLUSTER_PORT"\
"\n-- Please check the connection parameters and status."
debug "$LINENO" "server connection check succeeded"
}
# Checks for certain variables and prompts the user for
# the values if necessary.
#
# Globals:
# QUICK_DEMO
# MONITOR_USERNAME, MONITOR_PASSWORD
# CLUSTER_APP_USERNAME, CLUSTER_APP_PASSWORD
# CLUSTER_HOSTNAME, CLUSTER_USERNAME
# USER_HOST_RANGE
#
# Arguments:
# 1: the category for the variable, this may either be MONITOR or CLUSTER_APP
# 2: a description of the user
# 3: the hostgroup to associate the user with
# (only needed if user_category='CLISTER APP')
#
function user_input_check() {
debug "$LINENO" "user_input_check ( $(dump_arguments "$@") )"
local user_category=$1
local user_description=$2
local hostgroup_id
local username
local password
local safe_username
local safe_password
if [[ $user_category == "CLUSTER_APP" ]]; then
hostgroup_id=$3
fi
username=$(eval "echo \$${user_category}_USERNAME")
password=$(eval "echo \$${user_category}_PASSWORD")
if [[ -z $username ]]; then
read -r -p "Enter ${user_description}name : " "${user_category}"_USERNAME
username=$(eval "echo \$${user_category}_USERNAME")
while [[ -z ${username} ]]
do
echo -n "No input entered, Enter ${user_description} name: "
read -r "${user_category}"_USERNAME
username=$(eval "echo \$${user_category}_USERNAME")
done
else
if [[ $QUICK_DEMO -eq 0 ]]; then
echo -e "${user_description} name as per command line/config-file is ${BD}$(eval "echo \$${user_category}_USERNAME")${NBD}"
fi
fi
if [[ -z $password ]]; then
if [[ $QUICK_DEMO -eq 0 ]]; then
read -r -s -p "Enter ${user_description} password: " "${user_category}"_PASSWORD
password=$(eval "echo \$${user_category}_PASSWORD")
while [[ -z $password ]]
do
read -r -s -p "No input entered, Enter ${user_description} password: " "${user_category}"_PASSWORD
password=$(eval "echo \$${user_category}_PASSWORD")
done
fi
fi
username=$(eval "echo \$${user_category}_USERNAME")
password=$(eval "echo \$${user_category}_PASSWORD")
safe_username=${username//\'/\'\'}
safe_password=${password//\'/\'\'}
if [[ $user_category == "CLUSTER_APP" ]]; then
local check_user
check_user=$(mysql_exec "$LINENO" "SELECT user,host FROM mysql.user where user='$safe_username' and host='$USER_HOST_RANGE';")
check_cmd $? "$LINENO" "Failed to retrieve the user information from PXC."\
"\n-- Please check the PXC connection parameters and status."
if [[ -z "$check_user" ]]; then
if [[ $FORCE -eq 1 ]]; then
proxysql_exec "$LINENO" "DELETE FROM mysql_users where username='$safe_username';"
check_cmd $? "$LINENO" "Failed to delete the PXC application user: '$username' from the ProxySQL database."\
"\n-- Please check the ProxySQL connection parameters and status."
fi
local precheck_user
precheck_user=$(proxysql_exec "$LINENO" "SELECT username FROM mysql_users where username='$safe_username'")
check_cmd $? "$LINENO" "Failed to query ProxySQL for the user."\
"\n-- Please check the ProxySQL connection parameters and status."
if [[ -z "$precheck_user" ]]; then
mysql_exec "$LINENO" "CREATE USER '$safe_username'@'$USER_HOST_RANGE' IDENTIFIED WITH mysql_native_password BY '$safe_password';"
check_cmd $? "$LINENO" "Failed to add the PXC application user to PXC: $username" \
"\n-- Please check if '$CLUSTER_USERNAME'@'$CLUSTER_HOSTNAME' has the proper permissions to create the montioring user"
if [[ $QUICK_DEMO -eq 1 ]]; then
mysql_exec "$LINENO" "GRANT ALL ON *.* to '$safe_username'@'$USER_HOST_RANGE'"
check_cmd $? "$LINENO" "Failed to grant permissions to '$username'@'$USER_HOST_RANGE'"\
"\n-- Please check if $CLUSTER_USERNAME@'$CLUSTER_HOSTNAME' has the GRANT privilege"\
"\n-- required to assign the requested permissions"
fi
proxysql_exec "$LINENO" \
"INSERT INTO mysql_users
(username,password,active,default_hostgroup)
VALUES
('$safe_username','$safe_password',1,$hostgroup_id);"
check_cmd $? "$LINENO" "Failed to add the PXC application user: '$username' to the ProxySQL database."\
"\n-- Please check the ProxySQL connection parameters and status."
proxysql_load_to_runtime_save_to_disk "MYSQL USERS" "$LINENO" 1
if [[ $QUICK_DEMO -eq 0 ]]; then
echo -e "\nPercona XtraDB Cluster application user '${BD}$username'@'$USER_HOST_RANGE${NBD}' has been added with ${BD}ALL${NBD} privileges, ${BD}this user is created for testing purposes${NBD}"
else
echo -e "\nPercona XtraDB Cluster application user '${BD}$username'@'$USER_HOST_RANGE${NBD}' has been added with the USAGE privilege, please make sure to the grant appropriate privileges"
fi
else
error "$LINENO" "The application user ${BD}$username${NBD} is already present in the ProxySQL database."
echo -e "-- Note: ProxySQL does not allow duplicate usernames."
exit 1
fi
else
if [[ $FORCE -eq 1 ]]; then
proxysql_exec "$LINENO" "DELETE FROM mysql_users where username='$safe_username';"
check_cmd $? "$LINENO" "Failed to delete the PXC application user: '$safe_username' from the ProxySQL database."\
"\n-- Please check the ProxySQL connection parameters and status."
fi
local check_user
check_user=$(proxysql_exec "$LINENO" "SELECT username FROM mysql_users where username='$safe_username'")
check_cmd $? "$LINENO" "Could not retrieve the users from the ProxySQL database."\
"\n-- Please check the ProxySQL connection parameters and status."
if [[ -z "$check_user" ]]; then
echo -e "\nApplication user '${BD}${username}'@'$USER_HOST_RANGE${NBD}' already present in PXC.\n"
proxysql_exec "$LINENO" "INSERT INTO mysql_users (username,password,active,default_hostgroup) values ('$safe_username','$safe_password',1,$hostgroup_id);"
check_cmd $? "$LINENO" "Failed to add the PXC application user: '$username' to the ProxySQL database."\
"\n-- Please check the ProxySQL connection parameters and status."
proxysql_load_to_runtime_save_to_disk "MYSQL USERS" "$LINENO" 1
else
error "$LINENO" "The application user ${BD}$username${NBD} is already present in the ProxySQL database."
echo -e "-- Note: ProxySQL does not allow duplicate usernames."
exit 1
fi
fi
fi
}
# Gets the list of hostgroups given only the writer hostgroup
#
# Globals:
# None
#
# Arguments:
# Parameter 1: the writer hostgroup
#
# Outputs:
# A list of hostgroups, separated by commas (',')
# The order of the hostgroups is:
# 1. writer hostgroup
# 2. reader hostgroup
# 3. backup writer hostgroup
# 4. offline hostgroup
#
function get_all_hostgroups_from_writer_hostgroup()
{
echo "$WRITER_HOSTGROUP_ID,$READER_HOSTGROUP_ID,$WRITER_MAINT_HOSTGROUP_ID,$WRITER_CONFIG_HOSTGROUP_ID,$READER_MAINT_HOSTGROUP_ID,$READER_CONFIG_HOSTGROUP_ID"
}
# Adds the list of servers to ProxySQL
# This will add all of the servers in the list to the:
# Writer hostgroup
# Reader hostgroup
# Writer Configuration hostgroup
# Reader Configuration hostgroup
#
# ProxySQL is responsible for moving them to the correct hostgroup
#
# Globals:
# WRITER_HOSTGROUP_ID
# READER_HOSTGROUP_ID
# WRITER_CONFIG_HOSTGROUP_ID
# READER_CONFIG_HOSTGROUP_ID
# MAX_CONNECTIONS
# USE_SSL_OPTION
#
# Arguments:
# Parameter 1 : A list of servers (space-separated in a string)
#
function add_servers_to_proxysql()
{
local server_list=$1
for i in ${server_list}; do
local ws_address ws_ip ws_port
ws_address=$(separate_ip_port_from_address "$i")
ws_ip=$(echo "$ws_address" | cut -d' ' -f1)
ws_port=$(echo "$ws_address" | cut -d' ' -f2)
proxysql_exec "$LINENO" \
"INSERT INTO mysql_servers
(hostname,hostgroup_id,port,weight,max_connections,use_ssl)
VALUES
('$ws_ip',$WRITER_HOSTGROUP_ID,$ws_port,1000,$MAX_CONNECTIONS,$USE_SSL_OPTION),
('$ws_ip',$READER_HOSTGROUP_ID,$ws_port,1000,$MAX_CONNECTIONS,$USE_SSL_OPTION),
('$ws_ip',$WRITER_CONFIG_HOSTGROUP_ID,$ws_port,1000,$MAX_CONNECTIONS,$USE_SSL_OPTION),
('$ws_ip',$READER_CONFIG_HOSTGROUP_ID,$ws_port,1000,$MAX_CONNECTIONS,$USE_SSL_OPTION)
;"
check_cmd $? "$LINENO" "Failed to add the PXC server node with address: $i."\
"\n-- Please check the ProxySQL connection parameters and status."
done
}
# Updates the weight of a given node to a specific value
#
# Globals:
# WRITER_HOSTGROUP_ID
# READER_HOSTGROUP_ID
# WRITER_CONFIG_HOSTGROUP_ID
# READER_CONFIG_HOSTGROUP_ID
#
function update_weight() {
local type=$1
local update_weight=$2
local update_hgs operation
if [[ $type == "READ" ]]; then
operation="--update-read-weight"
update_hgs="($READER_HOSTGROUP_ID,$READER_CONFIG_HOSTGROUP_ID)"
else
operation="--update-write-weight"
update_hgs="($WRITER_HOSTGROUP_ID,$WRITER_CONFIG_HOSTGROUP_ID)"
fi
# Extract node details and validate inputs
local address
local weight
local node_address
local node_ip
local node_port
address=$(echo "$update_weight" | cut -d, -f1)
weight=$(echo "$update_weight" | cut -d, -f2)
node_address=$(separate_ip_port_from_address "$address")
node_ip=$(echo "$node_address" | cut -d' ' -f1)
node_port=$(echo "$node_address" | cut -d' ' -f2)
host_info=$(proxysql_exec "$LINENO" \
"SELECT COUNT(*)
FROM mysql_servers
WHERE hostgroup_id IN $update_hgs AND
hostname='$node_ip' AND
port=$node_port")
check_cmd $? "$LINENO" "Could not retrieve hostgroup and server information from ProxySQL"\
"\n-- Please check the ProxySQL connection parameters and status."
if [ "$host_info" -eq 0 ]; then
error "$LINENO" "Failed to execute $operation: Could not find the node belonging to the cluster with address $address"
exit 1
fi
# We are here means we are good to update the weight.
proxysql_exec "$LINENO" \
"UPDATE mysql_servers
SET weight = $weight
WHERE
hostname='$node_ip' AND
hostgroup_id IN $update_hgs AND
port=$node_port"
check_cmd $? "$LINENO" "Failed to update the write-node" \
"\n-- Please check the ProxySQL connection parameters and status."
}
# Adjusts the weights of the servers when in a singlewrite configuration.
#
# This will adjust the weights of the servers in the list
#
# Election of primary MUST be deterministic, this is a must have requirement in
# real-world. So we must set a clear priority for the writers like: 1000, 999,
# 998.
#
# At the same time when possible we should also reduce the load of reads on the
# primary, which means that we should have something like: 900 for the writer
# while 1000,1000 for the other readers.
#
# Also, this should be consistent both in writer HG and Writer Config HG after
# which the scheduler will manage it using the Writer Config HG as reference.
#
# Globals:
# WRITER_HOSTGROUP_ID
# READER_HOSTGROUP_ID
# WRITER_CONFIG_HOSTGROUP_ID
# READER_CONFIG_HOSTGROUP_ID
#
function adjust_weights () {
local errcode
is_mode_singlewrite $WRITER_HOSTGROUP_ID
if [[ $? -eq 0 && $AUTO_ASSIGN_WEIGHTS -eq 1 ]]; then
# Load the servers to runtime and wait till the scheduler processes the cluster nodes.
proxysql_load_to_runtime_save_to_disk "MYSQL SERVERS" $LINENO
wait_for_scheduler_processing
# Fetch the writer node.
local writer_node
writer_node=$(proxysql_exec "$LINENO" \
"SELECT hostname || ':' || port
FROM mysql_servers
WHERE
hostgroup_id = $WRITER_HOSTGROUP_ID AND
status NOT IN (\"OFFLINE_HARD\",\"OFFLINE_SOFT\")")
check_cmd $? "$LINENO" "Failed to query ProxySQL for the user."\
"\n-- Please check the ProxySQL connection parameters and status."
local writer_host=${writer_node%:*}
local writer_port=${writer_node##*:}
debug "Chosen writer node = $writer_host:$writer_port, reducing its reader's weightage to 900"
# Set the weight of all nodes to 1000
proxysql_exec "$LINENO" \
"UPDATE mysql_servers
SET weight = 1000"
check_cmd $? "$LINENO" "Failed to update the weight" \
"\n-- Please check the ProxySQL connection parameters and status."
# Set the writer node's weight in reader HG
proxysql_exec "$LINENO" \
"UPDATE mysql_servers
SET weight = 900
WHERE
hostname = '$writer_host' AND
port = $writer_port AND
hostgroup_id IN ($READER_HOSTGROUP_ID,$READER_CONFIG_HOSTGROUP_ID);"
check_cmd $? "$LINENO" "Failed to update weight" \
"\n-- Please check the ProxySQL connection parameters and status."
# Now update write weights of other nodes.
# To do so, update the writer-config HG.
#
# Get the list of nodes in writer config other than the current writer.
# For each node update weight.
local backup_writers
backup_writers=$(proxysql_exec "$LINENO" \
"SELECT hostname || ':' || port AS bkp_writer
FROM mysql_servers
WHERE
hostgroup_id = $WRITER_CONFIG_HOSTGROUP_ID AND
bkp_writer != \"$writer_host:$writer_port\" AND
status NOT IN (\"OFFLINE_HARD\",\"OFFLINE_SOFT\")")
check_cmd $? "$LINENO" "Failed to query ProxySQL for the user."\
"\n-- Please check the ProxySQL connection parameters and status."
if [[ -n $backup_writers ]]; then
# Extract the hostname and port from the rows
# Creates a string of "host:port" separated by spaces
local counter=1
while read -r line; do
if [[ -z $line ]]; then
continue
fi
local ip_addr=${line%:*}
local port=${line##*:}
local new_weight=$((1000-counter))
# Update the new weights in WRITER_CONFIG_HOSTGROUP_ID
proxysql_exec "$LINENO" \
"UPDATE mysql_servers
SET weight = $new_weight
WHERE
hostgroup_id IN ($WRITER_HOSTGROUP_ID, $WRITER_CONFIG_HOSTGROUP_ID) AND
hostname = '$ip_addr' AND
port = '$port' AND
status NOT IN ('OFFLINE_HARD','OFFLINE_SOFT')"
check_cmd $? "$LINENO" "Failed to query ProxySQL for the user."\
"\n-- Please check the ProxySQL connection parameters and status."
counter=$((counter+1))
done< <(printf "%s\n" "$backup_writers")
# Set the writer weight to 1000.
proxysql_exec "$LINENO" \
"UPDATE mysql_servers
SET weight = 1000
WHERE
hostname='$writer_host' AND