-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
Copy pathmysqld.go
1636 lines (1500 loc) · 52 KB
/
mysqld.go
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
/*
Copyright 2019 The Vitess Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
Commands for controlling an external mysql process.
Some commands are issued as exec'd tools, some are handled by connecting via
the mysql protocol.
*/
package mysqlctl
import (
"bufio"
"bytes"
"context"
"errors"
"fmt"
"io"
"os"
"os/exec"
"path"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"syscall"
"time"
"github.com/spf13/pflag"
"vitess.io/vitess/config"
"vitess.io/vitess/go/mysql"
"vitess.io/vitess/go/mysql/sqlerror"
"vitess.io/vitess/go/protoutil"
"vitess.io/vitess/go/sqltypes"
"vitess.io/vitess/go/vt/dbconfigs"
"vitess.io/vitess/go/vt/dbconnpool"
vtenv "vitess.io/vitess/go/vt/env"
"vitess.io/vitess/go/vt/hook"
"vitess.io/vitess/go/vt/log"
"vitess.io/vitess/go/vt/mysqlctl/mysqlctlclient"
mysqlctlpb "vitess.io/vitess/go/vt/proto/mysqlctl"
vtrpcpb "vitess.io/vitess/go/vt/proto/vtrpc"
"vitess.io/vitess/go/vt/servenv"
"vitess.io/vitess/go/vt/vterrors"
)
// The string we expect before the MySQL version number
// in strings containing MySQL version information.
const versionStringPrefix = "Ver "
// How many bytes from MySQL error log to sample for error messages
const maxLogFileSampleSize = 4096
// DbaGrantWaitTime is the amount of time to wait for the grants to have applied
const DbaGrantWaitTime = 10 * time.Second
var (
// DisableActiveReparents is a flag to disable active
// reparents for safety reasons. It is used in three places:
// 1. in this file to skip registering the commands.
// 2. in vtctld so it can be exported to the UI (different
// package, that's why it's exported). That way we can disable
// menu items there, using features.
DisableActiveReparents bool
dbaPoolSize = 20
// DbaIdleTimeout is how often we will refresh the DBA connpool connections
DbaIdleTimeout = time.Minute
appPoolSize = 40
appIdleTimeout = time.Minute
// PoolDynamicHostnameResolution is whether we should retry DNS resolution of hostname targets
// and reconnect if necessary
PoolDynamicHostnameResolution time.Duration
mycnfTemplateFile string
socketFile string
replicationConnectRetry = 10 * time.Second
versionRegex = regexp.MustCompile(fmt.Sprintf(`%s([0-9]+)\.([0-9]+)\.([0-9]+)`, versionStringPrefix))
// versionSQLQuery will return a version string directly from
// a MySQL server that is compatible with what we expect from
// mysqld --version and matches the versionRegex. Example
// result: Ver 8.0.35 MySQL Community Server - GPL
versionSQLQuery = fmt.Sprintf("select concat('%s', @@global.version, ' ', @@global.version_comment) as version",
versionStringPrefix)
binlogEntryCommittedTimestampRegex = regexp.MustCompile("original_committed_timestamp=([0-9]+)")
binlogEntryTimestampGTIDRegexp = regexp.MustCompile(`^#(.+) server id.*\bGTID\b`)
)
// Mysqld is the object that represents a mysqld daemon running on this server.
type Mysqld struct {
dbcfgs *dbconfigs.DBConfigs
dbaPool *dbconnpool.ConnectionPool
appPool *dbconnpool.ConnectionPool
capabilities capabilitySet
// mutex protects the fields below.
mutex sync.Mutex
onTermFuncs []func()
cancelWaitCmd chan struct{}
semiSyncType mysql.SemiSyncType
}
func init() {
for _, cmd := range []string{"mysqlctl", "mysqlctld", "vtcombo", "vttablet", "vttestserver"} {
servenv.OnParseFor(cmd, registerMySQLDFlags)
}
for _, cmd := range []string{"vtctld", "vtctldclient"} {
servenv.OnParseFor(cmd, registerReparentFlags)
}
for _, cmd := range []string{"vtcombo", "vttablet", "vttestserver"} {
servenv.OnParseFor(cmd, registerDeprecatedReparentFlags)
}
for _, cmd := range []string{"mysqlctl", "mysqlctld", "vtcombo", "vttablet", "vttestserver"} {
servenv.OnParseFor(cmd, registerPoolFlags)
}
}
func registerMySQLDFlags(fs *pflag.FlagSet) {
fs.DurationVar(&PoolDynamicHostnameResolution, "pool_hostname_resolve_interval", PoolDynamicHostnameResolution, "if set force an update to all hostnames and reconnect if changed, defaults to 0 (disabled)")
fs.StringVar(&mycnfTemplateFile, "mysqlctl_mycnf_template", mycnfTemplateFile, "template file to use for generating the my.cnf file during server init")
fs.StringVar(&socketFile, "mysqlctl_socket", socketFile, "socket file to use for remote mysqlctl actions (empty for local actions)")
fs.DurationVar(&replicationConnectRetry, "replication_connect_retry", replicationConnectRetry, "how long to wait in between replica reconnect attempts. Only precise to the second.")
}
func registerReparentFlags(fs *pflag.FlagSet) {
fs.BoolVar(&DisableActiveReparents, "disable_active_reparents", DisableActiveReparents, "if set, do not allow active reparents. Use this to protect a cluster using external reparents.")
}
func registerDeprecatedReparentFlags(fs *pflag.FlagSet) {
fs.BoolVar(&DisableActiveReparents, "disable_active_reparents", DisableActiveReparents, "if set, do not allow active reparents. Use this to protect a cluster using external reparents.")
fs.MarkDeprecated("disable_active_reparents", "Use --unmanaged flag instead for unmanaged tablets.")
}
func registerPoolFlags(fs *pflag.FlagSet) {
fs.IntVar(&dbaPoolSize, "dba_pool_size", dbaPoolSize, "Size of the connection pool for dba connections")
fs.DurationVar(&DbaIdleTimeout, "dba_idle_timeout", DbaIdleTimeout, "Idle timeout for dba connections")
fs.DurationVar(&appIdleTimeout, "app_idle_timeout", appIdleTimeout, "Idle timeout for app connections")
fs.IntVar(&appPoolSize, "app_pool_size", appPoolSize, "Size of the connection pool for app connections")
}
// NewMysqld creates a Mysqld object based on the provided configuration
// and connection parameters.
func NewMysqld(dbcfgs *dbconfigs.DBConfigs) *Mysqld {
result := &Mysqld{
dbcfgs: dbcfgs,
}
// Create and open the connection pool for dba access.
result.dbaPool = dbconnpool.NewConnectionPool("DbaConnPool", nil, dbaPoolSize, DbaIdleTimeout, 0, PoolDynamicHostnameResolution)
result.dbaPool.Open(dbcfgs.DbaWithDB())
// Create and open the connection pool for app access.
result.appPool = dbconnpool.NewConnectionPool("AppConnPool", nil, appPoolSize, appIdleTimeout, 0, PoolDynamicHostnameResolution)
result.appPool.Open(dbcfgs.AppWithDB())
/*
If we have an external unmanaged tablet, we can't do the flavor
detection here. We also won't need it, since mysqlctl itself is the only
one that needs capabilities and the flavor.
*/
if dbconfigs.GlobalDBConfigs.HasGlobalSettings() {
log.Info("mysqld is unmanaged or remote. Skipping flavor detection")
return result
}
/*
If we have a socketFile here, it means we're not running inside mysqlctl.
This means we don't need the flavor and capability detection, since mysqlctl
itself is the only one that needs this.
*/
if socketFile != "" {
log.Info("mysqld is remote. Skipping flavor detection")
return result
}
version, err := GetVersionString()
if err != nil {
failVersionDetection(err)
}
f, v, err := ParseVersionString(version)
if err != nil {
failVersionDetection(err)
}
log.Infof("Using flavor: %v, version: %v", f, v)
result.capabilities = newCapabilitySet(f, v)
return result
}
// GetVersionString runs mysqld --version and returns its output as a string
func GetVersionString() (string, error) {
noSocketFile()
mysqlRoot, err := vtenv.VtMysqlRoot()
if err != nil {
return "", err
}
mysqldPath, err := binaryPath(mysqlRoot, "mysqld")
if err != nil {
return "", err
}
_, version, err := execCmd(mysqldPath, []string{"--version"}, nil, mysqlRoot, nil)
if err != nil {
return "", err
}
return version, nil
}
// ParseVersionString parses the output of mysqld --version into a flavor and version
func ParseVersionString(version string) (flavor MySQLFlavor, ver ServerVersion, err error) {
if strings.Contains(version, "Percona") {
flavor = FlavorPercona
} else if strings.Contains(version, "MariaDB") {
flavor = FlavorMariaDB
} else {
// OS distributed MySQL releases have a version string like:
// mysqld Ver 5.7.27-0ubuntu0.19.04.1 for Linux on x86_64 ((Ubuntu))
flavor = FlavorMySQL
}
v := versionRegex.FindStringSubmatch(version)
if len(v) != 4 {
return flavor, ver, fmt.Errorf("could not parse server version from: %s", version)
}
ver.Major, err = strconv.Atoi(string(v[1]))
if err != nil {
return flavor, ver, fmt.Errorf("could not parse server version from: %s", version)
}
ver.Minor, err = strconv.Atoi(string(v[2]))
if err != nil {
return flavor, ver, fmt.Errorf("could not parse server version from: %s", version)
}
ver.Patch, err = strconv.Atoi(string(v[3]))
if err != nil {
return flavor, ver, fmt.Errorf("could not parse server version from: %s", version)
}
return
}
// RunMysqlUpgrade will run the mysql_upgrade program on the current
// install. Will be called only when mysqld is running with no
// network and no grant tables.
func (mysqld *Mysqld) RunMysqlUpgrade(ctx context.Context) error {
// Execute as remote action on mysqlctld if requested.
if socketFile != "" {
log.Infof("executing Mysqld.RunMysqlUpgrade() remotely via mysqlctld server: %v", socketFile)
client, err := mysqlctlclient.New(ctx, "unix", socketFile)
if err != nil {
return fmt.Errorf("can't dial mysqlctld: %v", err)
}
defer client.Close()
return client.RunMysqlUpgrade(ctx)
}
if mysqld.capabilities.hasMySQLUpgradeInServer() {
log.Warningf("MySQL version has built-in upgrade, skipping RunMySQLUpgrade")
return nil
}
// Since we started mysql with --skip-grant-tables, we should
// be able to run mysql_upgrade without any valid user or
// password. However, mysql_upgrade executes a 'flush
// privileges' right in the middle, and then subsequent
// commands fail if we don't use valid credentials. So let's
// use dba credentials.
params, err := mysqld.dbcfgs.DbaConnector().MysqlParams()
if err != nil {
return err
}
defaultsFile, err := mysqld.defaultsExtraFile(params)
if err != nil {
return err
}
defer os.Remove(defaultsFile)
// Run the program, if it fails, we fail. Note in this
// moment, mysqld is running with no grant tables on the local
// socket only, so this doesn't need any user or password.
args := []string{
// --defaults-file=* must be the first arg.
"--defaults-file=" + defaultsFile,
"--force", // Don't complain if it's already been upgraded.
}
// Find mysql_upgrade. If not there, we do nothing.
vtMysqlRoot, err := vtenv.VtMysqlRoot()
if err != nil {
log.Warningf("VT_MYSQL_ROOT not set, skipping mysql_upgrade step: %v", err)
return nil
}
name, err := binaryPath(vtMysqlRoot, "mysql_upgrade")
if err != nil {
log.Warningf("mysql_upgrade binary not present, skipping it: %v", err)
return nil
}
env, err := buildLdPaths()
if err != nil {
log.Warningf("skipping mysql_upgrade step: %v", err)
return nil
}
_, _, err = execCmd(name, args, env, "", nil)
return err
}
// Start will start the mysql daemon, either by running the
// 'mysqld_start' hook, or by running mysqld_safe in the background.
// If a mysqlctld address is provided in a flag, Start will run
// remotely. When waiting for mysqld to start, we will use
// the dba user.
func (mysqld *Mysqld) Start(ctx context.Context, cnf *Mycnf, mysqldArgs ...string) error {
// Execute as remote action on mysqlctld if requested.
if socketFile != "" {
log.Infof("executing Mysqld.Start() remotely via mysqlctld server: %v", socketFile)
client, err := mysqlctlclient.New(ctx, "unix", socketFile)
if err != nil {
return fmt.Errorf("can't dial mysqlctld: %v", err)
}
defer client.Close()
return client.Start(ctx, mysqldArgs...)
}
if err := mysqld.startNoWait(cnf, mysqldArgs...); err != nil {
return err
}
return mysqld.Wait(ctx, cnf)
}
// startNoWait is the internal version of Start, and it doesn't wait.
func (mysqld *Mysqld) startNoWait(cnf *Mycnf, mysqldArgs ...string) error {
var name string
ts := fmt.Sprintf("Mysqld.Start(%v)", time.Now().Unix())
// try the mysqld start hook, if any
switch hr := hook.NewHook("mysqld_start", mysqldArgs).Execute(); hr.ExitStatus {
case hook.HOOK_SUCCESS:
// hook exists and worked, we can keep going
name = "mysqld_start hook" // nolint
case hook.HOOK_DOES_NOT_EXIST:
// hook doesn't exist, run mysqld_safe ourselves
log.Infof("%v: No mysqld_start hook, running mysqld_safe directly", ts)
vtMysqlRoot, err := vtenv.VtMysqlRoot()
if err != nil {
return err
}
name, err = binaryPath(vtMysqlRoot, "mysqld_safe")
if err != nil {
// The movement to use systemd means that mysqld_safe is not always provided.
// This should not be considered an issue do not generate a warning.
log.Infof("%v: trying to launch mysqld instead", err)
name, err = binaryPath(vtMysqlRoot, "mysqld")
// If this also fails, return an error.
if err != nil {
return err
}
// If we're here, and the lockfile still exists for the socket, we have
// to clean that up since we know at this point we need to start MySQL.
// Having this stray lock file present means MySQL fails to start. This
// only happens when running without mysqld_safe.
if err := cleanupLockfile(cnf.SocketFile, ts); err != nil {
return err
}
}
mysqlBaseDir, err := vtenv.VtMysqlBaseDir()
if err != nil {
return err
}
args := []string{
"--defaults-file=" + cnf.Path,
"--basedir=" + mysqlBaseDir,
}
args = append(args, mysqldArgs...)
env, err := buildLdPaths()
if err != nil {
return err
}
cmd := exec.Command(name, args...)
cmd.Dir = vtMysqlRoot
cmd.Env = env
log.Infof("%v %#v", ts, cmd)
stderr, err := cmd.StderrPipe()
if err != nil {
return err
}
stdout, err := cmd.StdoutPipe()
if err != nil {
return err
}
go func() {
scanner := bufio.NewScanner(stderr)
for scanner.Scan() {
log.Infof("%v stderr: %v", ts, scanner.Text())
}
}()
go func() {
scanner := bufio.NewScanner(stdout)
for scanner.Scan() {
log.Infof("%v stdout: %v", ts, scanner.Text())
}
}()
err = cmd.Start()
if err != nil {
return vterrors.Wrapf(err, "failed to start mysqld")
}
mysqld.mutex.Lock()
mysqld.cancelWaitCmd = make(chan struct{})
go func(cancel <-chan struct{}) {
// Wait regardless of cancel, so we don't generate defunct processes.
err := cmd.Wait()
log.Infof("%v exit: %v", ts, err)
// The process exited. Trigger OnTerm callbacks, unless we were canceled.
select {
case <-cancel:
default:
mysqld.mutex.Lock()
for _, callback := range mysqld.onTermFuncs {
go callback()
}
mysqld.mutex.Unlock()
}
}(mysqld.cancelWaitCmd)
mysqld.mutex.Unlock()
default:
// hook failed, we report error
return fmt.Errorf("mysqld_start hook failed: %v", hr.String())
}
return nil
}
func cleanupLockfile(socket string, ts string) error {
lockPath := fmt.Sprintf("%s.lock", socket)
pid, err := os.ReadFile(lockPath)
if errors.Is(err, os.ErrNotExist) {
log.Infof("%v: no stale lock file at %s", ts, lockPath)
// If there's no lock file, we can early return here, nothing
// to clean up then.
return nil
} else if err != nil {
log.Errorf("%v: error checking if lock file exists: %v", ts, err)
// Any other errors here are unexpected.
return err
}
p, err := strconv.Atoi(string(bytes.TrimSpace(pid)))
if err != nil {
log.Errorf("%v: error parsing pid from lock file: %v", ts, err)
return err
}
if os.Getpid() == p {
log.Infof("%v: lock file at %s is ours, removing it", ts, lockPath)
return os.Remove(lockPath)
}
proc, err := os.FindProcess(p)
if err != nil {
log.Errorf("%v: error finding process: %v", ts, err)
return err
}
err = proc.Signal(syscall.Signal(0))
if err == nil {
// If the process still exists, it's not safe to
// remove the lock file, so we have to keep it around.
cmdline, err := os.ReadFile(fmt.Sprintf("/proc/%d/cmdline", p))
if err == nil {
name := string(bytes.ReplaceAll(cmdline, []byte{0}, []byte(" ")))
log.Errorf("%v: not removing socket lock file: %v with pid %v for %q", ts, lockPath, p, name)
} else {
log.Errorf("%v: not removing socket lock file: %v with pid %v (failed to read process name: %v)", ts, lockPath, p, err)
}
return fmt.Errorf("process %v is still running", p)
}
if !errors.Is(err, os.ErrProcessDone) {
// Any errors except for the process being done
// is unexpected here.
log.Errorf("%v: error checking process %v: %v", ts, p, err)
return err
}
// All good, process is gone and we can safely clean up the lock file.
log.Infof("%v: removing stale socket lock file: %v", ts, lockPath)
return os.Remove(lockPath)
}
// Wait returns nil when mysqld is up and accepting connections. It
// will use the dba credentials to try to connect. Use wait() with
// different credentials if needed.
func (mysqld *Mysqld) Wait(ctx context.Context, cnf *Mycnf) error {
params, err := mysqld.dbcfgs.DbaConnector().MysqlParams()
if err != nil {
return err
}
return mysqld.wait(ctx, cnf, params)
}
// WaitForDBAGrants waits for the grants to have applied for all the users.
func (mysqld *Mysqld) WaitForDBAGrants(ctx context.Context, waitTime time.Duration) (err error) {
if waitTime == 0 {
return nil
}
params, err := mysqld.dbcfgs.DbaConnector().MysqlParams()
if err != nil {
return err
}
timer := time.NewTimer(waitTime)
ctx, cancel := context.WithTimeout(ctx, waitTime)
defer cancel()
for {
conn, connErr := mysql.Connect(ctx, params)
if connErr == nil {
res, fetchErr := conn.ExecuteFetch("SHOW GRANTS", 1000, false)
conn.Close()
if fetchErr != nil {
log.Errorf("Error running SHOW GRANTS - %v", fetchErr)
}
if fetchErr == nil && res != nil && len(res.Rows) > 0 && len(res.Rows[0]) > 0 {
privileges := res.Rows[0][0].ToString()
// In MySQL 8.0, all the privileges are listed out explicitly, so we can search for SUPER in the output.
// In MySQL 5.7, all the privileges are not listed explicitly, instead ALL PRIVILEGES is written, so we search for that too.
if strings.Contains(privileges, "SUPER") || strings.Contains(privileges, "ALL PRIVILEGES") {
return nil
}
}
}
select {
case <-timer.C:
return fmt.Errorf("timed out after %v waiting for the dba user to have the required permissions", waitTime)
default:
time.Sleep(100 * time.Millisecond)
}
}
}
// wait is the internal version of Wait, that takes credentials.
func (mysqld *Mysqld) wait(ctx context.Context, cnf *Mycnf, params *mysql.ConnParams) error {
log.Infof("Waiting for mysqld socket file (%v) to be ready...", cnf.SocketFile)
for {
select {
case <-ctx.Done():
return errors.New("deadline exceeded waiting for mysqld socket file to appear: " + cnf.SocketFile)
default:
}
_, statErr := os.Stat(cnf.SocketFile)
if statErr == nil {
// Make sure the socket file isn't stale.
conn, connErr := mysql.Connect(ctx, params)
if connErr == nil {
conn.Close()
return nil
}
log.Infof("mysqld socket file exists, but can't connect: %v", connErr)
} else if !os.IsNotExist(statErr) {
return fmt.Errorf("can't stat mysqld socket file: %v", statErr)
}
time.Sleep(1000 * time.Millisecond)
}
}
// Shutdown will stop the mysqld daemon that is running in the background.
//
// waitForMysqld: should the function block until mysqld has stopped?
// This can actually take a *long* time if the buffer cache needs to be fully
// flushed - on the order of 20-30 minutes.
//
// If a mysqlctld address is provided in a flag, Shutdown will run remotely.
func (mysqld *Mysqld) Shutdown(ctx context.Context, cnf *Mycnf, waitForMysqld bool, shutdownTimeout time.Duration) error {
log.Infof("Mysqld.Shutdown")
// Execute as remote action on mysqlctld if requested.
if socketFile != "" {
log.Infof("executing Mysqld.Shutdown() remotely via mysqlctld server: %v", socketFile)
client, err := mysqlctlclient.New(ctx, "unix", socketFile)
if err != nil {
return fmt.Errorf("can't dial mysqlctld: %v", err)
}
defer client.Close()
return client.Shutdown(ctx, waitForMysqld)
}
// We're shutting down on purpose. We no longer want to be notified when
// mysqld terminates.
mysqld.mutex.Lock()
if mysqld.cancelWaitCmd != nil {
close(mysqld.cancelWaitCmd)
mysqld.cancelWaitCmd = nil
}
mysqld.mutex.Unlock()
// possibly mysql is already shutdown, check for a few files first
_, socketPathErr := os.Stat(cnf.SocketFile)
_, pidPathErr := os.Stat(cnf.PidFile)
if os.IsNotExist(socketPathErr) && os.IsNotExist(pidPathErr) {
log.Warningf("assuming mysqld already shut down - no socket, no pid file found")
return nil
}
// try the mysqld shutdown hook, if any
h := hook.NewSimpleHook("mysqld_shutdown")
hr := h.ExecuteContext(ctx)
switch hr.ExitStatus {
case hook.HOOK_SUCCESS:
// hook exists and worked, we can keep going
case hook.HOOK_DOES_NOT_EXIST:
// hook doesn't exist, try mysqladmin
log.Infof("No mysqld_shutdown hook, running mysqladmin directly")
dir, err := vtenv.VtMysqlRoot()
if err != nil {
return err
}
name, err := binaryPath(dir, "mysqladmin")
if err != nil {
return err
}
params, err := mysqld.dbcfgs.DbaConnector().MysqlParams()
if err != nil {
return err
}
cnf, err := mysqld.defaultsExtraFile(params)
if err != nil {
return err
}
defer os.Remove(cnf)
args := []string{
"--defaults-extra-file=" + cnf,
fmt.Sprintf("--shutdown-timeout=%d", int(shutdownTimeout.Seconds())),
"--connect-timeout=30",
"--wait=10",
"shutdown",
}
env, err := buildLdPaths()
if err != nil {
return err
}
if _, _, err = execCmd(name, args, env, dir, nil); err != nil {
return err
}
default:
// hook failed, we report error
return fmt.Errorf("mysqld_shutdown hook failed: %v", hr.String())
}
// Wait for mysqld to really stop. Use the socket and pid files as a
// proxy for that since we can't call wait() in a process we
// didn't start.
if waitForMysqld {
log.Infof("Mysqld.Shutdown: waiting for socket file (%v) and pid file (%v) to disappear",
cnf.SocketFile, cnf.PidFile)
for {
select {
case <-ctx.Done():
return errors.New("gave up waiting for mysqld to stop")
default:
}
_, socketPathErr = os.Stat(cnf.SocketFile)
_, pidPathErr = os.Stat(cnf.PidFile)
if os.IsNotExist(socketPathErr) && os.IsNotExist(pidPathErr) {
return nil
}
time.Sleep(100 * time.Millisecond)
}
}
return nil
}
// execCmd searches the PATH for a command and runs it, logging the output.
// If input is not nil, pipe it to the command's stdin.
func execCmd(name string, args, env []string, dir string, input io.Reader) (cmd *exec.Cmd, output string, err error) {
cmdPath, _ := exec.LookPath(name)
cmd = exec.Command(cmdPath, args...)
cmd.Env = env
cmd.Dir = dir
if input != nil {
cmd.Stdin = input
}
out, err := cmd.CombinedOutput()
output = string(out)
if err != nil {
log.Errorf("execCmd: %v failed: %v", name, err)
err = fmt.Errorf("%v: %w, output: %v", name, err, output)
}
return cmd, output, err
}
// binaryPath does a limited path lookup for a command,
// searching only within sbin and bin in the given root.
func binaryPath(root, binary string) (string, error) {
noSocketFile()
subdirs := []string{"sbin", "bin", "libexec", "scripts"}
for _, subdir := range subdirs {
binPath := path.Join(root, subdir, binary)
if _, err := os.Stat(binPath); err == nil {
return binPath, nil
}
}
return "", fmt.Errorf("%s not found in any of %s/{%s}",
binary, root, strings.Join(subdirs, ","))
}
// InitConfig will create the default directory structure for the mysqld process,
// generate / configure a my.cnf file.
func (mysqld *Mysqld) InitConfig(cnf *Mycnf) error {
log.Infof("mysqlctl.InitConfig")
err := mysqld.createDirs(cnf)
if err != nil {
log.Errorf("%s", err.Error())
return err
}
// Set up config files.
if err = mysqld.initConfig(cnf, cnf.Path); err != nil {
log.Errorf("failed creating %v: %v", cnf.Path, err)
return err
}
return nil
}
// Init will create the default directory structure for the mysqld process,
// generate / configure a my.cnf file install a skeleton database,
// and apply the provided initial SQL file.
func (mysqld *Mysqld) Init(ctx context.Context, cnf *Mycnf, initDBSQLFile string) error {
log.Infof("mysqlctl.Init running with contents previously embedded from %s", initDBSQLFile)
err := mysqld.InitConfig(cnf)
if err != nil {
log.Errorf("%s", err.Error())
return err
}
// Install data dir.
if err = mysqld.installDataDir(cnf); err != nil {
return err
}
// Start mysqld. We do not use Start, as we have to wait using
// the root user.
if err = mysqld.startNoWait(cnf); err != nil {
log.Errorf("failed starting mysqld: %v\n%v", err, readTailOfMysqldErrorLog(cnf.ErrorLogPath))
return err
}
// Wait for mysqld to be ready, using root credentials, as no
// user is created yet.
params := &mysql.ConnParams{
Uname: "root",
UnixSocket: cnf.SocketFile,
}
if err = mysqld.wait(ctx, cnf, params); err != nil {
log.Errorf("failed starting mysqld in time: %v\n%v", err, readTailOfMysqldErrorLog(cnf.ErrorLogPath))
return err
}
if initDBSQLFile == "" { // default to built-in
if err := mysqld.executeMysqlScript(ctx, params, config.DefaultInitDB); err != nil {
return fmt.Errorf("failed to initialize mysqld: %v", err)
}
return nil
}
// else, user specified an init db file
sqlFile, err := os.Open(initDBSQLFile)
if err != nil {
return fmt.Errorf("can't open init_db_sql_file (%v): %v", initDBSQLFile, err)
}
defer sqlFile.Close()
script, err := io.ReadAll(sqlFile)
if err != nil {
return fmt.Errorf("can't read init_db_sql_file (%v): %v", initDBSQLFile, err)
}
if err := mysqld.executeMysqlScript(ctx, params, string(script)); err != nil {
return fmt.Errorf("can't run init_db_sql_file (%v): %v", initDBSQLFile, err)
}
return nil
}
// For debugging purposes show the last few lines of the MySQL error log.
// Return a suggestion (string) if the file is non regular or can not be opened.
// This helps prevent cases where the error log is symlinked to /dev/stderr etc,
// In which case the user can manually open the file.
func readTailOfMysqldErrorLog(fileName string) string {
fileInfo, err := os.Stat(fileName)
if err != nil {
return fmt.Sprintf("could not stat mysql error log (%v): %v", fileName, err)
}
if !fileInfo.Mode().IsRegular() {
return fmt.Sprintf("mysql error log file is not a regular file: %v", fileName)
}
file, err := os.Open(fileName)
if err != nil {
return fmt.Sprintf("could not open mysql error log (%v): %v", fileName, err)
}
defer file.Close()
startPos := int64(0)
if fileInfo.Size() > maxLogFileSampleSize {
startPos = fileInfo.Size() - maxLogFileSampleSize
}
// Show the last few KB of the MySQL error log.
buf := make([]byte, maxLogFileSampleSize)
flen, err := file.ReadAt(buf, startPos)
if err != nil && err != io.EOF {
return fmt.Sprintf("could not read mysql error log (%v): %v", fileName, err)
}
return fmt.Sprintf("tail of mysql error log (%v):\n%s", fileName, buf[:flen])
}
func (mysqld *Mysqld) installDataDir(cnf *Mycnf) error {
mysqlRoot, err := vtenv.VtMysqlRoot()
if err != nil {
return err
}
mysqldPath, err := binaryPath(mysqlRoot, "mysqld")
if err != nil {
return err
}
mysqlBaseDir, err := vtenv.VtMysqlBaseDir()
if err != nil {
return err
}
if mysqld.capabilities.hasInitializeInServer() {
log.Infof("Installing data dir with mysqld --initialize-insecure")
args := []string{
"--defaults-file=" + cnf.Path,
"--basedir=" + mysqlBaseDir,
"--initialize-insecure", // Use empty 'root'@'localhost' password.
}
if _, _, err = execCmd(mysqldPath, args, nil, mysqlRoot, nil); err != nil {
log.Errorf("mysqld --initialize-insecure failed: %v\n%v", err, readTailOfMysqldErrorLog(cnf.ErrorLogPath))
return err
}
return nil
}
log.Infof("Installing data dir with mysql_install_db")
args := []string{
"--defaults-file=" + cnf.Path,
"--basedir=" + mysqlBaseDir,
}
if mysqld.capabilities.hasMaria104InstallDb() {
args = append(args, "--auth-root-authentication-method=normal")
}
cmdPath, err := binaryPath(mysqlRoot, "mysql_install_db")
if err != nil {
return err
}
if _, _, err = execCmd(cmdPath, args, nil, mysqlRoot, nil); err != nil {
log.Errorf("mysql_install_db failed: %v\n%v", err, readTailOfMysqldErrorLog(cnf.ErrorLogPath))
return err
}
return nil
}
func (mysqld *Mysqld) initConfig(cnf *Mycnf, outFile string) error {
var err error
var configData string
env := make(map[string]string)
envVars := []string{"KEYSPACE", "SHARD", "TABLET_TYPE", "TABLET_ID", "TABLET_DIR", "MYSQL_PORT"}
for _, v := range envVars {
env[v] = os.Getenv(v)
}
switch hr := hook.NewHookWithEnv("make_mycnf", nil, env).Execute(); hr.ExitStatus {
case hook.HOOK_DOES_NOT_EXIST:
log.Infof("make_mycnf hook doesn't exist, reading template files")
configData, err = cnf.makeMycnf(mysqld.getMycnfTemplate())
case hook.HOOK_SUCCESS:
configData, err = cnf.fillMycnfTemplate(hr.Stdout)
default:
return fmt.Errorf("make_mycnf hook failed(%v): %v", hr.ExitStatus, hr.Stderr)
}
if err != nil {
return err
}
return os.WriteFile(outFile, []byte(configData), 0o664)
}
func (mysqld *Mysqld) getMycnfTemplate() string {
if mycnfTemplateFile != "" {
data, err := os.ReadFile(mycnfTemplateFile)
if err != nil {
log.Fatalf("template file specified by -mysqlctl_mycnf_template could not be read: %v", mycnfTemplateFile)
}
return string(data) // use only specified template
}
var myTemplateSource strings.Builder
myTemplateSource.WriteString("[mysqld]\n")
myTemplateSource.WriteString(config.MycnfDefault)
// database flavor + version specific file.
// {flavor}{major}{minor}.cnf
f := FlavorMariaDB
if mysqld.capabilities.isMySQLLike() {
f = FlavorMySQL
}
var versionConfig string
switch f {
case FlavorPercona, FlavorMySQL:
switch mysqld.capabilities.version.Major {
case 5:
if mysqld.capabilities.version.Minor == 7 {
versionConfig = config.MycnfMySQL57
} else {
log.Infof("this version of Vitess does not include built-in support for %v %v", mysqld.capabilities.flavor, mysqld.capabilities.version)
}
case 8:
if mysqld.capabilities.version.Minor >= 4 {
versionConfig = config.MycnfMySQL84
} else if mysqld.capabilities.version.Minor >= 1 || mysqld.capabilities.version.Patch >= 26 {
versionConfig = config.MycnfMySQL8026
} else {
versionConfig = config.MycnfMySQL80
}
default:
log.Infof("this version of Vitess does not include built-in support for %v %v", mysqld.capabilities.flavor, mysqld.capabilities.version)
}
case FlavorMariaDB:
switch mysqld.capabilities.version.Major {
case 10:
versionConfig = config.MycnfMariaDB10
default:
log.Infof("this version of Vitess does not include built-in support for %v %v", mysqld.capabilities.flavor, mysqld.capabilities.version)
}
}
myTemplateSource.WriteString(versionConfig)
if extraCnf := os.Getenv("EXTRA_MY_CNF"); extraCnf != "" {
parts := strings.Split(extraCnf, ":")
for _, path := range parts {
data, dataErr := os.ReadFile(path)
if dataErr != nil {
log.Infof("could not open config file for mycnf: %v", path)
continue
}
myTemplateSource.WriteString("## " + path + "\n")
myTemplateSource.Write(data)
}
}
return myTemplateSource.String()
}
// RefreshConfig attempts to recreate the my.cnf from templates, and log and
// swap in to place if it's updated. It keeps a copy of the last version in case fallback is required.
// Should be called from a stable replica, server_id is not regenerated.
func (mysqld *Mysqld) RefreshConfig(ctx context.Context, cnf *Mycnf) error {
// Execute as remote action on mysqlctld if requested.
if socketFile != "" {
log.Infof("executing Mysqld.RefreshConfig() remotely via mysqlctld server: %v", socketFile)
client, err := mysqlctlclient.New(ctx, "unix", socketFile)
if err != nil {
return fmt.Errorf("can't dial mysqlctld: %v", err)
}
defer client.Close()
return client.RefreshConfig(ctx)
}
log.Info("Checking for updates to my.cnf")
f, err := os.CreateTemp(path.Dir(cnf.Path), "my.cnf")
if err != nil {
return fmt.Errorf("could not create temp file: %v", err)
}
defer os.Remove(f.Name())
err = mysqld.initConfig(cnf, f.Name())
if err != nil {
return fmt.Errorf("could not initConfig in %v: %v", f.Name(), err)
}
existing, err := os.ReadFile(cnf.Path)
if err != nil {
return fmt.Errorf("could not read existing file %v: %v", cnf.Path, err)
}
updated, err := os.ReadFile(f.Name())