forked from mrqwer88/MySQLTuner-perl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mysqltuner.pl
executable file
·6058 lines (5495 loc) · 199 KB
/
mysqltuner.pl
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
#!/usr/bin/env perl
# mysqltuner.pl - Version 1.7.0
# High Performance MySQL Tuning Script
# Copyright (C) 2006-2016 Major Hayden - major@mhtx.net
#
# For the latest updates, please visit http://mysqltuner.com/
# Git repository available at http://github.com/major/MySQLTuner-perl
#
# 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, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# This project would not be possible without help from:
# Matthew Montgomery Paul Kehrer Dave Burgess
# Jonathan Hinds Mike Jackson Nils Breunese
# Shawn Ashlee Luuk Vosslamber Ville Skytta
# Trent Hornibrook Jason Gill Mark Imbriaco
# Greg Eden Aubin Galinotti Giovanni Bechis
# Bill Bradford Ryan Novosielski Michael Scheidell
# Blair Christensen Hans du Plooy Victor Trac
# Everett Barnes Tom Krouper Gary Barrueto
# Simon Greenaway Adam Stein Isart Montane
# Baptiste M. Cole Turner Major Hayden
# Joe Ashcraft Jean-Marie Renouard Christian Loos
#
# Inspired by Matthew Montgomery's tuning-primer.sh script:
# http://forge.mysql.com/projects/view.php?id=44
#
package main;
use 5.005;
use strict;
use warnings;
use diagnostics;
use File::Spec;
use Getopt::Long;
use File::Basename;
use Cwd 'abs_path';
use Data::Dumper;
$Data::Dumper::Pair = " : ";
# for which()
#use Env;
# Set up a few variables for use in the script
my $tunerversion = "1.7.0";
my ( @adjvars, @generalrec );
# Set defaults
my %opt = (
"silent" => 0,
"nobad" => 0,
"nogood" => 0,
"noinfo" => 0,
"debug" => 0,
"nocolor" => 0,
"forcemem" => 0,
"forceswap" => 0,
"host" => 0,
"socket" => 0,
"port" => 0,
"user" => 0,
"pass" => 0,
"password" => 0,
"skipsize" => 0,
"checkversion" => 0,
"updateversion" => 0,
"buffers" => 0,
"passwordfile" => 0,
"bannedports" => '',
"maxportallowed" => 0,
"outputfile" => 0,
"dbstat" => 0,
"idxstat" => 0,
"sysstat" => 0,
"pfstat" => 0,
"skippassword" => 0,
"noask" => 0,
"template" => 0,
"json" => 0,
"prettyjson" => 0,
"reportfile" => 0,
"verbose" => 0,
"defaults-file" => '',
);
# Gather the options from the command line
my $getOptionsCheck = GetOptions(
\%opt, 'nobad',
'nogood', 'noinfo',
'debug', 'nocolor',
'forcemem=i', 'forceswap=i',
'host=s', 'socket=s',
'port=i', 'user=s',
'pass=s', 'skipsize',
'checkversion', 'mysqladmin=s',
'mysqlcmd=s', 'help',
'buffers', 'skippassword',
'passwordfile=s', 'outputfile=s',
'silent', 'dbstat',
'json', 'prettyjson',
'idxstat', 'noask',
'template=s', 'reportfile=s',
'cvefile=s', 'bannedports=s',
'updateversion', 'maxportallowed=s',
'verbose', 'sysstat',
'password=s', 'pfstat',
'defaults-file=s'
);
#If params are incorrect return help
if ( $getOptionsCheck ne 1 ) {
usage();
}
if ( defined $opt{'help'} && $opt{'help'} == 1 ) { usage(); }
sub usage {
# Shown with --help option passed
print " MySQLTuner $tunerversion - MySQL High Performance Tuning Script\n"
. " Bug reports, feature requests, and downloads at http://mysqltuner.com/\n"
. " Maintained by Major Hayden (major\@mhtx.net) - Licensed under GPL\n"
. "\n"
. " Important Usage Guidelines:\n"
. " To run the script with the default options, run the script without arguments\n"
. " Allow MySQL server to run for at least 24-48 hours before trusting suggestions\n"
. " Some routines may require root level privileges (script will provide warnings)\n"
. " You must provide the remote server's total memory when connecting to other servers\n"
. "\n"
. " Connection and Authentication\n"
. " --host <hostname> Connect to a remote host to perform tests (default: localhost)\n"
. " --socket <socket> Use a different socket for a local connection\n"
. " --port <port> Port to use for connection (default: 3306)\n"
. " --user <username> Username to use for authentication\n"
. " --pass <password> Password to use for authentication\n"
. " --defaults-file <path> Path to a custom .my.cnf\n"
. " --mysqladmin <path> Path to a custom mysqladmin executable\n"
. " --mysqlcmd <path> Path to a custom mysql executable\n" . "\n"
. " --noask Don't ask password if needed\n" . "\n"
. " Performance and Reporting Options\n"
. " --skipsize Don't enumerate tables and their types/sizes (default: on)\n"
. " (Recommended for servers with many tables)\n"
. " --skippassword Don't perform checks on user passwords(default: off)\n"
. " --checkversion Check for updates to MySQLTuner (default: don't check)\n"
. " --updateversion Check for updates to MySQLTuner and update when newer version is available (default: don't check)\n"
. " --forcemem <size> Amount of RAM installed in megabytes\n"
. " --forceswap <size> Amount of swap memory configured in megabytes\n"
. " --passwordfile <path>Path to a password file list(one password by line)\n"
. " Output Options:\n"
. " --silent Don't output anything on screen\n"
. " --nogood Remove OK responses\n"
. " --nobad Remove negative/suggestion responses\n"
. " --noinfo Remove informational responses\n"
. " --debug Print debug information\n"
. " --dbstat Print database information\n"
. " --idxstat Print index information\n"
. " --sysstat Print system information\n"
. " --pfstat Print Performance schema information\n"
. " --bannedports Ports banned separated by comma(,)\n"
. " --maxportallowed Number of ports opened allowed on this hosts\n"
. " --cvefile CVE File for vulnerability checks\n"
. " --nocolor Don't print output in color\n"
. " --json Print result as JSON string\n"
. " --prettyjson Print result as human readable JSON\n"
. " --buffers Print global and per-thread buffer values\n"
. " --outputfile <path> Path to a output txt file\n" . "\n"
. " --reportfile <path> Path to a report txt file\n" . "\n"
. " --template <path> Path to a template file\n" . "\n"
. " --verbose Prints out all options (default: no verbose) \n"
. "\n";
exit 0;
}
my $devnull = File::Spec->devnull();
my $basic_password_files =
( $opt{passwordfile} eq "0" )
? abs_path( dirname(__FILE__) ) . "/basic_passwords.txt"
: abs_path( $opt{passwordfile} );
# Related to password option
$opt{pass} = $opt{password} if ( $opt{pass} eq 0 and $opt{password} ne 0 );
# for RPM distributions
$basic_password_files = "/usr/share/mysqltuner/basic_passwords.txt"
unless -f "$basic_password_files";
# check if we need to enable verbose mode
if ( $opt{verbose} ) {
$opt{checkversion} = 1; #Check for updates to MySQLTuner
$opt{dbstat} = 1; #Print database information
$opt{idxstat} = 1; #Print index information
$opt{sysstat} = 1; #Print index information
$opt{buffers} = 1; #Print global and per-thread buffer values
$opt{pfstat} = 1; #Print performance schema info.
$opt{cvefile} = 'vulnerabilities.csv'; #CVE File for vulnerability checks
}
# for RPM distributions
$opt{cvefile} = "/usr/share/mysqltuner/vulnerabilities.csv"
unless ( defined $opt{cvefile} and -f "$opt{cvefile}" );
$opt{cvefile} = '' unless -f "$opt{cvefile}";
$opt{cvefile} = './vulnerabilities.csv' if -f './vulnerabilities.csv';
$opt{'bannedports'} = '' unless defined( $opt{'bannedports'} );
my @banned_ports = split ',', $opt{'bannedports'};
#
my $outputfile = undef;
$outputfile = abs_path( $opt{outputfile} ) unless $opt{outputfile} eq "0";
my $fh = undef;
open( $fh, '>', $outputfile )
or die("Fail opening $outputfile")
if defined($outputfile);
$opt{nocolor} = 1 if defined($outputfile);
# Setting up the colors for the print styles
my $me = `whoami`;
$me =~ s/\n//g;
# Setting up the colors for the print styles
my $good = ( $opt{nocolor} == 0 ) ? "[\e[0;32mOK\e[0m]" : "[OK]";
my $bad = ( $opt{nocolor} == 0 ) ? "[\e[0;31m!!\e[0m]" : "[!!]";
my $info = ( $opt{nocolor} == 0 ) ? "[\e[0;34m--\e[0m]" : "[--]";
my $deb = ( $opt{nocolor} == 0 ) ? "[\e[0;31mDG\e[0m]" : "[DG]";
my $cmd = ( $opt{nocolor} == 0 ) ? "\e[1;32m[CMD]($me)" : "[CMD]($me)";
my $end = ( $opt{nocolor} == 0 ) ? "\e[0m" : "";
# Checks for supported or EOL'ed MySQL versions
my ( $mysqlvermajor, $mysqlverminor, $mysqlvermicro );
# Super structure containing all information
my %result;
$result{'MySQLTuner'}{'version'} = $tunerversion;
$result{'MySQLTuner'}{'options'} = \%opt;
# Functions that handle the print styles
sub prettyprint {
print $_[0] . "\n" unless ( $opt{'silent'} or $opt{'json'} );
print $fh $_[0] . "\n" if defined($fh);
}
sub goodprint { prettyprint $good. " " . $_[0] unless ( $opt{nogood} == 1 ); }
sub infoprint { prettyprint $info. " " . $_[0] unless ( $opt{noinfo} == 1 ); }
sub badprint { prettyprint $bad. " " . $_[0] unless ( $opt{nobad} == 1 ); }
sub debugprint { prettyprint $deb. " " . $_[0] unless ( $opt{debug} == 0 ); }
sub redwrap {
return ( $opt{nocolor} == 0 ) ? "\e[0;31m" . $_[0] . "\e[0m" : $_[0];
}
sub greenwrap {
return ( $opt{nocolor} == 0 ) ? "\e[0;32m" . $_[0] . "\e[0m" : $_[0];
}
sub cmdprint { prettyprint $cmd. " " . $_[0] . $end; }
sub infoprintml {
for my $ln (@_) { $ln =~ s/\n//g; infoprint "\t$ln"; }
}
sub infoprintcmd {
cmdprint "@_";
infoprintml grep { $_ ne '' and $_ !~ /^\s*$/ } `@_ 2>&1`;
}
sub subheaderprint {
my $tln = 100;
my $sln = 8;
my $ln = length("@_") + 2;
prettyprint " ";
prettyprint "-" x $sln . " @_ " . "-" x ( $tln - $ln - $sln );
}
sub infoprinthcmd {
subheaderprint "$_[0]";
infoprintcmd "$_[1]";
}
# Calculates the parameter passed in bytes, then rounds it to one decimal place
sub hr_bytes {
my $num = shift;
if ( $num >= ( 1024**3 ) ) { #GB
return sprintf( "%.1f", ( $num / ( 1024**3 ) ) ) . "G";
}
elsif ( $num >= ( 1024**2 ) ) { #MB
return sprintf( "%.1f", ( $num / ( 1024**2 ) ) ) . "M";
}
elsif ( $num >= 1024 ) { #KB
return sprintf( "%.1f", ( $num / 1024 ) ) . "K";
}
else {
return $num . "B";
}
}
# Calculates the parameter passed in bytes, then rounds it to the nearest integer
sub hr_bytes_rnd {
my $num = shift;
if ( $num >= ( 1024**3 ) ) { #GB
return int( ( $num / ( 1024**3 ) ) ) . "G";
}
elsif ( $num >= ( 1024**2 ) ) { #MB
return int( ( $num / ( 1024**2 ) ) ) . "M";
}
elsif ( $num >= 1024 ) { #KB
return int( ( $num / 1024 ) ) . "K";
}
else {
return $num . "B";
}
}
# Calculates the parameter passed to the nearest power of 1000, then rounds it to the nearest integer
sub hr_num {
my $num = shift;
if ( $num >= ( 1000**3 ) ) { # Billions
return int( ( $num / ( 1000**3 ) ) ) . "B";
}
elsif ( $num >= ( 1000**2 ) ) { # Millions
return int( ( $num / ( 1000**2 ) ) ) . "M";
}
elsif ( $num >= 1000 ) { # Thousands
return int( ( $num / 1000 ) ) . "K";
}
else {
return $num;
}
}
# Calculate Percentage
sub percentage {
my $value = shift;
my $total = shift;
$total = 0 unless defined $total;
return 100, 00 if $total == 0;
return sprintf( "%.2f", ( $value * 100 / $total ) );
}
# Calculates uptime to display in a more attractive form
sub pretty_uptime {
my $uptime = shift;
my $seconds = $uptime % 60;
my $minutes = int( ( $uptime % 3600 ) / 60 );
my $hours = int( ( $uptime % 86400 ) / (3600) );
my $days = int( $uptime / (86400) );
my $uptimestring;
if ( $days > 0 ) {
$uptimestring = "${days}d ${hours}h ${minutes}m ${seconds}s";
}
elsif ( $hours > 0 ) {
$uptimestring = "${hours}h ${minutes}m ${seconds}s";
}
elsif ( $minutes > 0 ) {
$uptimestring = "${minutes}m ${seconds}s";
}
else {
$uptimestring = "${seconds}s";
}
return $uptimestring;
}
# Retrieves the memory installed on this machine
my ( $physical_memory, $swap_memory, $duflags );
sub memerror {
badprint
"Unable to determine total memory/swap; use '--forcemem' and '--forceswap'";
exit 1;
}
sub os_setup {
my $os = `uname`;
$duflags = ( $os =~ /Linux/ ) ? '-b' : '';
if ( $opt{'forcemem'} > 0 ) {
$physical_memory = $opt{'forcemem'} * 1048576;
infoprint "Assuming $opt{'forcemem'} MB of physical memory";
if ( $opt{'forceswap'} > 0 ) {
$swap_memory = $opt{'forceswap'} * 1048576;
infoprint "Assuming $opt{'forceswap'} MB of swap space";
}
else {
$swap_memory = 0;
badprint "Assuming 0 MB of swap space (use --forceswap to specify)";
}
}
else {
if ( $os =~ /Linux|CYGWIN/ ) {
$physical_memory =
`grep -i memtotal: /proc/meminfo | awk '{print \$2}'`
or memerror;
$physical_memory *= 1024;
$swap_memory =
`grep -i swaptotal: /proc/meminfo | awk '{print \$2}'`
or memerror;
$swap_memory *= 1024;
}
elsif ( $os =~ /Darwin/ ) {
$physical_memory = `sysctl -n hw.memsize` or memerror;
$swap_memory =
`sysctl -n vm.swapusage | awk '{print \$3}' | sed 's/\..*\$//'`
or memerror;
}
elsif ( $os =~ /NetBSD|OpenBSD|FreeBSD/ ) {
$physical_memory = `sysctl -n hw.physmem` or memerror;
if ( $physical_memory < 0 ) {
$physical_memory = `sysctl -n hw.physmem64` or memerror;
}
$swap_memory =
`swapctl -l | grep '^/' | awk '{ s+= \$2 } END { print s }'`
or memerror;
}
elsif ( $os =~ /BSD/ ) {
$physical_memory = `sysctl -n hw.realmem` or memerror;
$swap_memory =
`swapinfo | grep '^/' | awk '{ s+= \$2 } END { print s }'`;
}
elsif ( $os =~ /SunOS/ ) {
$physical_memory =
`/usr/sbin/prtconf | grep Memory | cut -f 3 -d ' '`
or memerror;
chomp($physical_memory);
$physical_memory = $physical_memory * 1024 * 1024;
}
elsif ( $os =~ /AIX/ ) {
$physical_memory =
`lsattr -El sys0 | grep realmem | awk '{print \$2}'`
or memerror;
chomp($physical_memory);
$physical_memory = $physical_memory * 1024;
$swap_memory = `lsps -as | awk -F"(MB| +)" '/MB /{print \$2}'`
or memerror;
chomp($swap_memory);
$swap_memory = $swap_memory * 1024 * 1024;
}
elsif ( $os =~ /windows/i ) {
$physical_memory =
`wmic ComputerSystem get TotalPhysicalMemory | perl -ne "chomp; print if /[0-9]+/;"`
or memerror;
$swap_memory =
`wmic OS get FreeVirtualMemory | perl -ne "chomp; print if /[0-9]+/;"`
or memerror;
}
}
debugprint "Physical Memory: $physical_memory";
debugprint "Swap Memory: $swap_memory";
chomp($physical_memory);
chomp($swap_memory);
chomp($os);
$result{'OS'}{'OS Type'} = $os;
$result{'OS'}{'Physical Memory'}{'bytes'} = $physical_memory;
$result{'OS'}{'Physical Memory'}{'pretty'} = hr_bytes($physical_memory);
$result{'OS'}{'Swap Memory'}{'bytes'} = $swap_memory;
$result{'OS'}{'Swap Memory'}{'pretty'} = hr_bytes($swap_memory);
$result{'OS'}{'Other Processes'}{'bytes'} = get_other_process_memory();
$result{'OS'}{'Other Processes'}{'pretty'} =
hr_bytes( get_other_process_memory() );
}
sub get_http_cli {
my $httpcli = which( "curl", $ENV{'PATH'} );
chomp($httpcli);
if ($httpcli) {
return $httpcli;
}
$httpcli = which( "wget", $ENV{'PATH'} );
chomp($httpcli);
if ($httpcli) {
return $httpcli;
}
return "";
}
# Checks for updates to MySQLTuner
sub validate_tuner_version {
if ( $opt{'checkversion'} eq 0 and $opt{'updateversion'} eq 0 ) {
print "\n" unless ( $opt{'silent'} or $opt{'json'} );
infoprint "Skipped version check for MySQLTuner script";
return;
}
my $update;
my $url =
"https://raw.githubusercontent.com/major/MySQLTuner-perl/master/mysqltuner.pl";
my $httpcli = get_http_cli();
if ( $httpcli =~ /curl$/ ) {
debugprint "$httpcli is available.";
debugprint
"$httpcli --connect-timeout 5 -silent '$url' 2>/dev/null | grep 'my \$tunerversion'| cut -d\\\" -f2";
$update =
`$httpcli --connect-timeout 5 -silent '$url' 2>/dev/null | grep 'my \$tunerversion'| cut -d\\\" -f2`;
chomp($update);
debugprint "VERSION: $update";
compare_tuner_version($update);
return;
}
if ( $httpcli =~ /wget$/ ) {
debugprint "$httpcli is available.";
debugprint
"$httpcli -e timestamping=off -T 5 -O - '$url' 2>$devnull| grep 'my \$tunerversion'| cut -d\\\" -f2";
$update =
`$httpcli -e timestamping=off -T 5 -O - '$url' 2>$devnull| grep 'my \$tunerversion'| cut -d\\\" -f2`;
chomp($update);
compare_tuner_version($update);
return;
}
debugprint "curl and wget are not available.";
infoprint "Unable to check for the latest MySQLTuner version";
}
# Checks for updates to MySQLTuner
sub update_tuner_version {
if ( $opt{'updateversion'} eq 0 ) {
badprint "Skipped version update for MySQLTuner script";
print "\n" unless ( $opt{'silent'} or $opt{'json'} );
return;
}
#use Cwd;
my $update;
my $url = "https://raw.githubusercontent.com/major/MySQLTuner-perl/master/";
my @scripts =
( "mysqltuner.pl", "basic_passwords.txt", "vulnerabilities.csv" );
my $totalScripts = scalar(@scripts);
my $receivedScripts = 0;
my $httpcli = get_http_cli();
foreach my $script (@scripts) {
if ( $httpcli =~ /curl$/ ) {
debugprint "$httpcli is available.";
debugprint
"$httpcli --connect-timeout 5 '$url$script' 2>$devnull > $script";
$update =
`$httpcli --connect-timeout 5 '$url$script' 2>$devnull > $script`;
chomp($update);
debugprint "$script updated: $update";
if ( -s $script eq 0 ) {
badprint "Couldn't update $script";
}
else {
++$receivedScripts;
debugprint "$script updated: $update";
}
}
elsif ( $httpcli =~ /wget$/ ) {
debugprint "$httpcli is available.";
debugprint
"$httpcli -qe timestamping=off -T 5 -O $script '$url$script'";
$update =
`$httpcli -qe timestamping=off -T 5 -O $script '$url$script'`;
chomp($update);
if ( -s $script eq 0 ) {
badprint "Couldn't update $script";
}
else {
++$receivedScripts;
debugprint "$script updated: $update";
}
}
else {
debugprint "curl and wget are not available.";
infoprint "Unable to check for the latest MySQLTuner version";
}
}
if ( $receivedScripts eq $totalScripts ) {
goodprint "Successfully updated MySQLTuner script";
}
else {
badprint "Couldn't update MySQLTuner script";
}
exit 0;
}
sub compare_tuner_version {
my $remoteversion = shift;
debugprint "Remote data: $remoteversion";
#exit 0;
if ( $remoteversion ne $tunerversion ) {
badprint
"There is a new version of MySQLTuner available ($remoteversion)";
update_tuner_version();
return;
}
goodprint "You have the latest version of MySQLTuner($tunerversion)";
return;
}
# Checks to see if a MySQL login is possible
my ( $mysqllogin, $doremote, $remotestring, $mysqlcmd, $mysqladmincmd );
my $osname = $^O;
if ( $osname eq 'MSWin32' ) {
eval { require Win32; } or last;
$osname = Win32::GetOSName();
infoprint "* Windows OS($osname) is not fully supported.\n";
#exit 1;
}
sub mysql_setup {
$doremote = 0;
$remotestring = '';
if ( $opt{mysqladmin} ) {
$mysqladmincmd = $opt{mysqladmin};
}
else {
$mysqladmincmd = which( "mysqladmin", $ENV{'PATH'} );
}
chomp($mysqladmincmd);
if ( !-e $mysqladmincmd && $opt{mysqladmin} ) {
badprint "Unable to find the mysqladmin command you specified: "
. $mysqladmincmd . "";
exit 1;
}
elsif ( !-e $mysqladmincmd ) {
badprint "Couldn't find mysqladmin in your \$PATH. Is MySQL installed?";
exit 1;
}
if ( $opt{mysqlcmd} ) {
$mysqlcmd = $opt{mysqlcmd};
}
else {
$mysqlcmd = which( "mysql", $ENV{'PATH'} );
}
chomp($mysqlcmd);
if ( !-e $mysqlcmd && $opt{mysqlcmd} ) {
badprint "Unable to find the mysql command you specified: "
. $mysqlcmd . "";
exit 1;
}
elsif ( !-e $mysqlcmd ) {
badprint "Couldn't find mysql in your \$PATH. Is MySQL installed?";
exit 1;
}
$mysqlcmd =~ s/\n$//g;
my $mysqlclidefaults = `$mysqlcmd --print-defaults`;
debugprint "MySQL Client: $mysqlclidefaults";
if ( $mysqlclidefaults =~ /auto-vertical-output/ ) {
badprint
"Avoid auto-vertical-output in configuration file(s) for MySQL like";
exit 1;
}
debugprint "MySQL Client: $mysqlcmd";
# Are we being asked to connect via a socket?
if ( $opt{socket} ne 0 ) {
$remotestring = " -S $opt{socket}";
}
# Are we being asked to connect to a remote server?
if ( $opt{host} ne 0 ) {
chomp( $opt{host} );
$opt{port} = ( $opt{port} eq 0 ) ? 3306 : $opt{port};
# If we're doing a remote connection, but forcemem wasn't specified, we need to exit
if ( $opt{'forcemem'} eq 0
&& ( $opt{host} ne "127.0.0.1" )
&& ( $opt{host} ne "localhost" ) )
{
badprint "The --forcemem option is required for remote connections";
exit 1;
}
infoprint "Performing tests on $opt{host}:$opt{port}";
$remotestring = " -h $opt{host} -P $opt{port}";
if ( ( $opt{host} ne "127.0.0.1" ) && ( $opt{host} ne "localhost" ) ) {
$doremote = 1;
}
}
# Did we already get a username without password on the command line?
if ( $opt{user} ne 0 and $opt{pass} eq 0 ) {
$mysqllogin = "-u $opt{user} " . $remotestring;
my $loginstatus = `$mysqladmincmd ping $mysqllogin 2>&1`;
if ( $loginstatus =~ /mysqld is alive/ ) {
goodprint "Logged in using credentials passed on the command line";
return 1;
}
else {
badprint
"Attempted to use login credentials, but they were invalid";
exit 1;
}
}
# Did we already get a username and password passed on the command line?
if ( $opt{user} ne 0 and $opt{pass} ne 0 ) {
$mysqllogin = "-u $opt{user} -p'$opt{pass}'" . $remotestring;
my $loginstatus = `$mysqladmincmd ping $mysqllogin 2>&1`;
if ( $loginstatus =~ /mysqld is alive/ ) {
goodprint "Logged in using credentials passed on the command line";
return 1;
}
else {
badprint
"Attempted to use login credentials, but they were invalid";
exit 1;
}
}
my $svcprop = which( "svcprop", $ENV{'PATH'} );
if ( substr( $svcprop, 0, 1 ) =~ "/" ) {
# We are on solaris
( my $mysql_login =
`svcprop -p quickbackup/username svc:/network/mysql-quickbackup:default`
) =~ s/\s+$//;
( my $mysql_pass =
`svcprop -p quickbackup/password svc:/network/mysql-quickbackup:default`
) =~ s/\s+$//;
if ( substr( $mysql_login, 0, 7 ) ne "svcprop" ) {
# mysql-quickbackup is installed
$mysqllogin = "-u $mysql_login -p$mysql_pass";
my $loginstatus = `mysqladmin $mysqllogin ping 2>&1`;
if ( $loginstatus =~ /mysqld is alive/ ) {
goodprint "Logged in using credentials from mysql-quickbackup.";
return 1;
}
else {
badprint
"Attempted to use login credentials from mysql-quickbackup, but they failed.";
exit 1;
}
}
}
elsif ( -r "/etc/psa/.psa.shadow" and $doremote == 0 ) {
# It's a Plesk box, use the available credentials
$mysqllogin = "-u admin -p`cat /etc/psa/.psa.shadow`";
my $loginstatus = `$mysqladmincmd ping $mysqllogin 2>&1`;
unless ( $loginstatus =~ /mysqld is alive/ ) {
# Plesk 10+
$mysqllogin =
"-u admin -p`/usr/local/psa/bin/admin --show-password`";
$loginstatus = `$mysqladmincmd ping $mysqllogin 2>&1`;
unless ( $loginstatus =~ /mysqld is alive/ ) {
badprint
"Attempted to use login credentials from Plesk and Plesk 10+, but they failed.";
exit 1;
}
}
}
elsif ( -r "/usr/local/directadmin/conf/mysql.conf" and $doremote == 0 ) {
# It's a DirectAdmin box, use the available credentials
my $mysqluser =
`cat /usr/local/directadmin/conf/mysql.conf | egrep '^user=.*'`;
my $mysqlpass =
`cat /usr/local/directadmin/conf/mysql.conf | egrep '^passwd=.*'`;
$mysqluser =~ s/user=//;
$mysqluser =~ s/[\r\n]//;
$mysqlpass =~ s/passwd=//;
$mysqlpass =~ s/[\r\n]//;
$mysqllogin = "-u $mysqluser -p$mysqlpass";
my $loginstatus = `mysqladmin ping $mysqllogin 2>&1`;
unless ( $loginstatus =~ /mysqld is alive/ ) {
badprint
"Attempted to use login credentials from DirectAdmin, but they failed.";
exit 1;
}
}
elsif ( -r "/etc/mysql/debian.cnf" and $doremote == 0 ) {
# We have a debian maintenance account, use it
$mysqllogin = "--defaults-file=/etc/mysql/debian.cnf";
my $loginstatus = `$mysqladmincmd $mysqllogin ping 2>&1`;
if ( $loginstatus =~ /mysqld is alive/ ) {
goodprint
"Logged in using credentials from debian maintenance account.";
return 1;
}
else {
badprint
"Attempted to use login credentials from debian maintenance account, but they failed.";
exit 1;
}
}
elsif ( $opt{'defaults-file'} ne 0 and -r "$opt{'defaults-file'}" ) {
# defaults-file
debugprint "defaults file detected: $opt{'defaults-file'}";
my $mysqlclidefaults = `$mysqlcmd --print-defaults`;
debugprint "MySQL Client Default File: $opt{'defaults-file'}";
$mysqllogin = "--defaults-file=" . $opt{'defaults-file'};
my $loginstatus = `$mysqladmincmd $mysqllogin ping 2>&1`;
if ( $loginstatus =~ /mysqld is alive/ ) {
goodprint "Logged in using credentials from defaults file account.";
return 1;
}
}
else {
# It's not Plesk or debian, we should try a login
debugprint "$mysqladmincmd $remotestring ping 2>&1";
my $loginstatus = `$mysqladmincmd $remotestring ping 2>&1`;
if ( $loginstatus =~ /mysqld is alive/ ) {
# Login went just fine
$mysqllogin = " $remotestring ";
# Did this go well because of a .my.cnf file or is there no password set?
my $userpath = `printenv HOME`;
if ( length($userpath) > 0 ) {
chomp($userpath);
}
unless ( -e "${userpath}/.my.cnf" or -e "${userpath}/.mylogin.cnf" )
{
badprint
"Successfully authenticated with no password - SECURITY RISK!";
}
return 1;
}
else {
if ( $opt{'noask'} == 1 ) {
badprint
"Attempted to use login credentials, but they were invalid";
exit 1;
}
my ( $name, $password );
# If --user is defined no need to ask for username
if ( $opt{user} ne 0 ) {
$name = $opt{user};
}
else {
print STDERR "Please enter your MySQL administrative login: ";
$name = <STDIN>;
}
# If --pass is defined no need to ask for password
if ( $opt{pass} ne 0 ) {
$password = $opt{pass};
}
else {
print STDERR
"Please enter your MySQL administrative password: ";
system("stty -echo >$devnull 2>&1");
$password = <STDIN>;
system("stty echo >$devnull 2>&1");
}
chomp($password);
chomp($name);
$mysqllogin = "-u $name";
if ( length($password) > 0 ) {
$mysqllogin .= " -p'$password'";
}
$mysqllogin .= $remotestring;
my $loginstatus = `$mysqladmincmd ping $mysqllogin 2>&1`;
if ( $loginstatus =~ /mysqld is alive/ ) {
print STDERR "";
if ( !length($password) ) {
# Did this go well because of a .my.cnf file or is there no password set?
my $userpath = `printenv HOME`;
chomp($userpath);
unless ( -e "$userpath/.my.cnf" ) {
badprint
"Successfully authenticated with no password - SECURITY RISK!";
}
}
return 1;
}
else {
badprint
"Attempted to use login credentials, but they were invalid.";
exit 1;
}
exit 1;
}
}
}
# MySQL Request Array
sub select_array {
my $req = shift;
debugprint "PERFORM: $req ";
my @result = `$mysqlcmd $mysqllogin -Bse "\\w$req" 2>>/dev/null`;
if ( $? != 0 ) {
badprint "failed to execute: $req";
badprint "FAIL Execute SQL / return code: $?";
debugprint "CMD : $mysqlcmd";
debugprint "OPTIONS: $mysqllogin";
debugprint `$mysqlcmd $mysqllogin -Bse "$req" 2>&1`;
#exit $?;
}
debugprint "select_array: return code : $?";
chomp(@result);
return @result;
}
# MySQL Request one
sub select_one {
my $req = shift;
debugprint "PERFORM: $req ";
my $result = `$mysqlcmd $mysqllogin -Bse "\\w$req" 2>>/dev/null`;
if ( $? != 0 ) {
badprint "failed to execute: $req";
badprint "FAIL Execute SQL / return code: $?";
debugprint "CMD : $mysqlcmd";
debugprint "OPTIONS: $mysqllogin";
debugprint `$mysqlcmd $mysqllogin -Bse "$req" 2>&1`;
#exit $?;
}
debugprint "select_array: return code : $?";
chomp($result);
return $result;
}
sub get_tuning_info {
my @infoconn = select_array "\\s";
my ( $tkey, $tval );
@infoconn =
grep { !/Threads:/ and !/Connection id:/ and !/pager:/ and !/Using/ }
@infoconn;
foreach my $line (@infoconn) {
if ( $line =~ /\s*(.*):\s*(.*)/ ) {
debugprint "$1 => $2";
$tkey = $1;
$tval = $2;
chomp($tkey);
chomp($tval);
$result{'MySQL Client'}{$tkey} = $tval;
}
}
$result{'MySQL Client'}{'Client Path'} = $mysqlcmd;
$result{'MySQL Client'}{'Admin Path'} = $mysqladmincmd;
$result{'MySQL Client'}{'Authentication Info'} = $mysqllogin;
}
# Populates all of the variable and status hashes
my ( %mystat, %myvar, $dummyselect, %myrepl, %myslaves );
sub arr2hash {
my $href = shift;
my $harr = shift;
my $sep = shift;
$sep = '\s' unless defined($sep);
foreach my $line (@$harr) {
next if ( $line =~ m/^\*\*\*\*\*\*\*/ );
$line =~ /([a-zA-Z_]*)\s*$sep\s*(.*)/;
$$href{$1} = $2;
debugprint "V: $1 = $2";
}
}
sub get_all_vars {
# We need to initiate at least one query so that our data is useable
$dummyselect = select_one "SELECT VERSION()";
if ( not defined($dummyselect) or $dummyselect eq "" ) {
badprint
"You probably doesn't get enough privileges for running MySQLTuner ...";
exit(256);
}
$dummyselect =~ s/(.*?)\-.*/$1/;
debugprint "VERSION: " . $dummyselect . "";
$result{'MySQL Client'}{'Version'} = $dummyselect;
my @mysqlvarlist = select_array("SHOW VARIABLES");
push( @mysqlvarlist, select_array("SHOW GLOBAL VARIABLES") );
arr2hash( \%myvar, \@mysqlvarlist );
$result{'Variables'} = \%myvar;
my @mysqlstatlist = select_array("SHOW STATUS");
push( @mysqlstatlist, select_array("SHOW GLOBAL STATUS") );