forked from major/MySQLTuner-perl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mysqltuner.pl
7640 lines (6921 loc) · 255 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 2.2.8
# High Performance MySQL Tuning Script
# Copyright (C) 2015-2023 Jean-Marie Renouard - jmrenouard@gmail.com
# Copyright (C) 2006-2023 Major Hayden - major@mhtx.net
# For the latest updates, please visit http://mysqltuner.pl/
# Git repository available at https://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 <https://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
# Julien Francoz Daniel Black Long Radix
#
# Inspired by Matthew Montgomery's tuning-primer.sh script:
# http://www.day32.com/MySQL/
#
package main;
use 5.005;
use strict;
use warnings;
use diagnostics;
use File::Spec;
use Getopt::Long;
use Pod::Usage;
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 = "2.2.8";
my ( @adjvars, @generalrec );
# Set defaults
my %opt = (
"silent" => 0,
"nobad" => 0,
"nogood" => 0,
"noinfo" => 0,
"debug" => 0,
"nocolor" => ( !-t STDOUT ),
"color" => 0,
"forcemem" => 0,
"forceswap" => 0,
"host" => 0,
"socket" => 0,
"port" => 0,
"user" => 0,
"pass" => 0,
"password" => 0,
"ssl-ca" => 0,
"skipsize" => 0,
"checkversion" => 0,
"updateversion" => 0,
"buffers" => 0,
"passwordfile" => 0,
"bannedports" => '',
"maxportallowed" => 0,
"outputfile" => 0,
"noprocess" => 0,
"dbstat" => 0,
"nodbstat" => 0,
"server-log" => '',
"tbstat" => 0,
"notbstat" => 0,
"colstat" => 0,
"nocolstat" => 0,
"idxstat" => 0,
"noidxstat" => 0,
"nomyisamstat" => 0,
"nostructstat" => 0,
"sysstat" => 0,
"nosysstat" => 0,
"pfstat" => 0,
"nopfstat" => 0,
"skippassword" => 0,
"noask" => 0,
"template" => 0,
"json" => 0,
"prettyjson" => 0,
"reportfile" => 0,
"verbose" => 0,
"defaults-file" => '',
"defaults-extra-file" => '',
"protocol" => '',
"dumpdir" => '',
"feature" => '',
"dbgpattern" => '',
"defaultarch" => 64
);
# Gather the options from the command line
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', 'noask',
'json', 'prettyjson',
'template=s', 'reportfile=s',
'cvefile=s', 'bannedports=s',
'updateversion', 'maxportallowed=s',
'verbose', 'password=s',
'passenv=s', 'userenv=s',
'defaults-file=s', 'ssl-ca=s',
'color', 'noprocess',
'dbstat', 'nodbstat',
'tbstat', 'notbstat',
'colstat', 'nocolstat',
'sysstat', 'nosysstat',
'pfstat', 'nopfstat',
'idxstat', 'noidxstat',
'structstat', 'nostructstat',
'myisamstat', 'nomyisamstat',
'server-log=s', 'protocol=s',
'defaults-extra-file=s', 'dumpdir=s',
'feature=s', 'dbgpattern=s',
'defaultarch=i'
)
or pod2usage(
-exitval => 1,
-verbose => 99,
-sections => [
"NAME",
"IMPORTANT USAGE GUIDELINES",
"CONNECTION AND AUTHENTICATION",
"PERFORMANCE AND REPORTING OPTIONS",
"OUTPUT OPTIONS"
]
);
if ( defined $opt{'help'} && $opt{'help'} == 1 ) {
pod2usage(
-exitval => 0,
-verbose => 99,
-sections => [
"NAME",
"IMPORTANT USAGE GUIDELINES",
"CONNECTION AND AUTHENTICATION",
"PERFORMANCE AND REPORTING OPTIONS",
"OUTPUT OPTIONS"
]
);
}
my $devnull = File::Spec->devnull();
my $basic_password_files =
( $opt{passwordfile} eq "0" )
? abs_path( dirname(__FILE__) ) . "/basic_passwords.txt"
: abs_path( $opt{passwordfile} );
# Username from envvar
if ( exists $opt{userenv} && exists $ENV{ $opt{userenv} } ) {
$opt{user} = $ENV{ $opt{userenv} };
}
# Related to password option
if ( exists $opt{passenv} && exists $ENV{ $opt{passenv} } ) {
$opt{pass} = $ENV{ $opt{passenv} };
}
$opt{pass} = $opt{password} if ( $opt{pass} eq 0 and $opt{password} ne 0 );
if ( $opt{dumpdir} ne '' ) {
$opt{dumpdir} = abs_path( $opt{dumpdir} );
if ( !-d $opt{dumpdir} ) {
mkdir $opt{dumpdir} or die "Cannot create directory $opt{dumpdir}: $!";
}
}
# for RPM distributions
$basic_password_files = "/usr/share/mysqltuner/basic_passwords.txt"
unless -f "$basic_password_files";
$opt{dbgpattern} = '.*' if ( $opt{dbgpattern} eq '' );
# check if we need to enable verbose mode
if ( $opt{feature} ne '' ) { $opt{verbose} = 1; }
if ( $opt{verbose} ) {
$opt{checkversion} = 1; # Check for updates to MySQLTuner
$opt{dbstat} = 1; # Print database information
$opt{tbstat} = 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{structstat} = 1; # Print table structure information
$opt{myisamstat} = 1; # Print MyISAM table information
$opt{cvefile} = 'vulnerabilities.csv'; #CVE File for vulnerability checks
}
$opt{nocolor} = 1 if defined( $opt{outputfile} );
$opt{tbstat} = 0 if ( $opt{notbstat} == 1 ); # Don't print table information
$opt{colstat} = 0 if ( $opt{nocolstat} == 1 ); # Don't print column information
$opt{dbstat} = 0 if ( $opt{nodbstat} == 1 ); # Don't print database information
$opt{noprocess} = 0
if ( $opt{noprocess} == 1 ); # Don't print process information
$opt{sysstat} = 0 if ( $opt{nosysstat} == 1 ); # Don't print sysstat information
$opt{pfstat} = 0
if ( $opt{nopfstat} == 1 ); # Don't print performance schema information
$opt{idxstat} = 0 if ( $opt{noidxstat} == 1 ); # Don't print index information
$opt{structstat} = 0
if ( not defined( $opt{structstat} ) or $opt{nostructstat} == 1 )
; # Don't print table struct information
$opt{myisamstat} = 1
if ( not defined( $opt{myisamstat} ) or $opt{nomyisamstat} == 0 )
; # Don't print MyISAM table information
# 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);
$opt{nocolor} = 1 unless ( -t STDOUT );
$opt{nocolor} = 0 if ( $opt{color} == 1 );
# Setting up the colors for the print styles
my $me = `whoami`;
$me =~ s/\n//g;
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" : "";
# Maximum lines of log output to read from end
my $maxlines = 30000;
# Checks for supported or EOL'ed MySQL versions
my ( $mysqlvermajor, $mysqlverminor, $mysqlvermicro );
# Database
my @dblist;
# Super structure containing all information
my %result;
$result{'MySQLTuner'}{'version'} = $tunerversion;
$result{'MySQLTuner'}{'datetime'} = `date '+%d-%m-%Y %H:%M:%S'`;
$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]";
}
sub is_remote() {
my $host = $opt{'host'};
return 0 if ( $host eq '' );
return 0 if ( $host eq 'localhost' );
return 0 if ( $host eq '127.0.0.1' );
return 1;
}
sub is_int {
return 0 unless defined $_[0];
my $str = $_[0];
#trim whitespace both sides
$str =~ s/^\s+|\s+$//g;
#Alternatively, to match any float-like numeric, use:
# m/^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/
#flatten to string and match dash or plus and one or more digits
if ( $str =~ /^(\-|\+)?\d+?$/ ) {
return 1;
}
return 0;
}
# Calculates the number of physical cores considering HyperThreading
sub cpu_cores {
if ( $^O eq 'linux' ) {
my $cntCPU =
`awk -F: '/^core id/ && !P[\$2] { CORES++; P[\$2]=1 }; /^physical id/ && !N[\$2] { CPUs++; N[\$2]=1 }; END { print CPUs*CORES }' /proc/cpuinfo`;
chomp $cntCPU;
return ( $cntCPU == 0 ? `nproc` : $cntCPU );
}
if ( $^O eq 'freebsd' ) {
my $cntCPU = `sysctl -n kern.smp.cores`;
chomp $cntCPU;
return $cntCPU + 0;
}
return 0;
}
# Calculates the parameter passed in bytes, then rounds it to one decimal place
sub hr_bytes {
my $num = shift;
return "0B" unless defined($num);
return "0B" if $num eq "NULL";
return "0B" if $num eq "";
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";
}
}
sub hr_raw {
my $num = shift;
return "0" unless defined($num);
return "0" if $num eq "NULL";
if ( $num =~ /^(\d+)G$/ ) {
return $1 * 1024 * 1024 * 1024;
}
if ( $num =~ /^(\d+)M$/ ) {
return $1 * 1024 * 1024;
}
if ( $num =~ /^(\d+)K$/ ) {
return $1 * 1024;
}
if ( $num =~ /^(\d+)$/ ) {
return $1;
}
return $num;
}
# Calculates the parameter passed in bytes, then rounds it to the nearest integer
sub hr_bytes_rnd {
my $num = shift;
return "0B" unless defined($num);
return "0B" if $num eq "NULL";
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;
$total = 0 if $total eq "NULL";
return 100, 00 if $total == 0;
return sprintf( "%.2f", ( $value * 100 / $total ) );
}
# Calculates uptime to display in a human-readable 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, $xargsflags );
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' : '';
$xargsflags = ( $os =~ /Darwin|SunOS/ ) ? '' : '-r';
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 ) {
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 -m 3 -silent '$url' 2>/dev/null | grep 'my \$tunerversion'| cut -d\\\" -f2";
$update =
`$httpcli -m 3 -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 1 -T 3 -O - '$url' 2>$devnull| grep 'my \$tunerversion'| cut -d\\\" -f2";
$update =
`$httpcli -e timestamping=off -t 1 -T 3 -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";
infoprint
"Using --pass and --password option is insecure during MySQLTuner execution (password disclosure)"
if ( defined( $opt{'pass'} ) );
}
# 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;
}
my $update;
my $fullpath = "";
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.";
$fullpath = dirname(__FILE__) . "/" . $script;
debugprint "FullPath: $fullpath";
debugprint
"$httpcli --connect-timeout 3 '$url$script' 2>$devnull > $fullpath";
$update =
`$httpcli --connect-timeout 3 '$url$script' 2>$devnull > $fullpath`;
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 1 -T 3 -O $script '$url$script'";
$update =
`$httpcli -qe timestamping=off -t 1 -T 3 -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";
}
infoprint "Stopping program: MySQLTuner script must be updated first.";
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'} );
if ( !-e $mysqladmincmd ) {
$mysqladmincmd = which( "mariadb-admin", $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/mariadb-admin in your \$PATH. Is MySQL installed?";
#exit 1;
}
if ( $opt{mysqlcmd} ) {
$mysqlcmd = $opt{mysqlcmd};
}
else {
$mysqlcmd = which( "mysql", $ENV{'PATH'} );
if ( !-e $mysqlcmd ) {
$mysqlcmd = which( "mariadb", $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/mariadb 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";
$opt{port} = ( $opt{port} eq 0 ) ? 3306 : $opt{port};
# Are we being asked to connect via a socket?
if ( $opt{socket} ne 0 ) {
$remotestring = " -S $opt{socket} -P $opt{port}";
}
if ( $opt{protocol} ne '' ) {
$remotestring = " --protocol=$opt{protocol}";
}
# Are we being asked to connect to a remote server?
if ( $opt{host} ne 0 ) {
chomp( $opt{host} );
# If we're doing a remote connection, but forcemem wasn't specified, we need to exit
if ( $opt{'forcemem'} eq 0 && is_remote eq 1 ) {
badprint "The --forcemem option is required for remote connections";
badprint
"Assuming RAM memory is 1Gb for simplify remote connection usage";
$opt{'forcemem'} = 1024;
#exit 1;
}
if ( $opt{'forceswap'} eq 0 && is_remote eq 1 ) {
badprint
"The --forceswap option is required for remote connections";
badprint
"Assuming Swap size is 1Gb for simplify remote connection usage";
$opt{'forceswap'} = 1024;
#exit 1;
}
infoprint "Performing tests on $opt{host}:$opt{port}";
$remotestring = " -h $opt{host} -P $opt{port}";
$doremote = is_remote();
}
else {
$opt{host} = '127.0.0.1';
}
if ( $opt{'ssl-ca'} ne 0 ) {
if ( -e -r -f $opt{'ssl-ca'} ) {
$remotestring .= " --ssl-ca=$opt{'ssl-ca'}";
infoprint
"Will connect using ssl public key passed on the command line";
return 1;
}
else {
badprint
"Attempted to use passed ssl public key, but it was not found or could not be read";
exit 1;
}
}
# Did we already get a username with or without password on the command line?
if ( $opt{user} ne 0 ) {
$mysqllogin =
"-u $opt{user} "
. ( ( $opt{pass} ne 0 ) ? "-p'$opt{pass}' " : " " )
. $remotestring;
my $loginstatus =
`$mysqlcmd -Nrs -e 'select "mysqld is alive";' $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
and $opt{'defaults-file'} eq '' )
{
# 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 '' 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;
}
}
elsif ( $opt{'defaults-extra-file'} ne ''
and -r "$opt{'defaults-extra-file'}" )
{
# defaults-extra-file
debugprint "defaults extra file detected: $opt{'defaults-extra-file'}";
my $mysqlclidefaults = `$mysqlcmd --print-defaults`;
debugprint
"MySQL Client Extra Default File: $opt{'defaults-extra-file'}";
$mysqllogin = "--defaults-extra-file=" . $opt{'defaults-extra-file'};
my $loginstatus = `$mysqladmincmd $mysqllogin ping 2>&1`;
if ( $loginstatus =~ /mysqld is alive/ ) {