-
Notifications
You must be signed in to change notification settings - Fork 6.2k
Expand file tree
/
Copy pathmain.go
More file actions
1230 lines (1121 loc) · 42.5 KB
/
main.go
File metadata and controls
1230 lines (1121 loc) · 42.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2015 PingCAP, Inc.
//
// 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.
package main
import (
"context"
"flag"
"fmt"
"io/fs"
"os"
"runtime"
"strconv"
"strings"
"sync/atomic"
"syscall"
"time"
"github.com/grafana/pyroscope-go"
"github.com/opentracing/opentracing-go"
"github.com/pingcap/errors"
"github.com/pingcap/failpoint"
"github.com/pingcap/log"
"github.com/pingcap/tidb/pkg/bindinfo"
"github.com/pingcap/tidb/pkg/config"
"github.com/pingcap/tidb/pkg/config/deploymode"
"github.com/pingcap/tidb/pkg/config/kerneltype"
"github.com/pingcap/tidb/pkg/ddl"
"github.com/pingcap/tidb/pkg/domain"
"github.com/pingcap/tidb/pkg/executor"
"github.com/pingcap/tidb/pkg/executor/mppcoordmanager"
"github.com/pingcap/tidb/pkg/extension"
_ "github.com/pingcap/tidb/pkg/extension/_import"
"github.com/pingcap/tidb/pkg/keyspace"
"github.com/pingcap/tidb/pkg/kv"
"github.com/pingcap/tidb/pkg/metrics"
"github.com/pingcap/tidb/pkg/parser/mysql"
"github.com/pingcap/tidb/pkg/parser/terror"
parsertypes "github.com/pingcap/tidb/pkg/parser/types"
plannercore "github.com/pingcap/tidb/pkg/planner/core"
"github.com/pingcap/tidb/pkg/plugin"
"github.com/pingcap/tidb/pkg/privilege/privileges"
"github.com/pingcap/tidb/pkg/resourcemanager"
"github.com/pingcap/tidb/pkg/server"
"github.com/pingcap/tidb/pkg/session"
"github.com/pingcap/tidb/pkg/session/txninfo"
"github.com/pingcap/tidb/pkg/sessionctx/vardef"
"github.com/pingcap/tidb/pkg/sessionctx/variable"
"github.com/pingcap/tidb/pkg/standby"
"github.com/pingcap/tidb/pkg/statistics"
kvstore "github.com/pingcap/tidb/pkg/store"
"github.com/pingcap/tidb/pkg/store/copr"
"github.com/pingcap/tidb/pkg/store/driver"
"github.com/pingcap/tidb/pkg/store/mockstore"
"github.com/pingcap/tidb/pkg/util"
"github.com/pingcap/tidb/pkg/util/cgmon"
"github.com/pingcap/tidb/pkg/util/chunk"
"github.com/pingcap/tidb/pkg/util/cpuprofile"
"github.com/pingcap/tidb/pkg/util/deadlockhistory"
"github.com/pingcap/tidb/pkg/util/disk"
"github.com/pingcap/tidb/pkg/util/domainutil"
"github.com/pingcap/tidb/pkg/util/intest"
"github.com/pingcap/tidb/pkg/util/kvcache"
"github.com/pingcap/tidb/pkg/util/logutil"
"github.com/pingcap/tidb/pkg/util/memory"
"github.com/pingcap/tidb/pkg/util/metricsutil"
"github.com/pingcap/tidb/pkg/util/naming"
"github.com/pingcap/tidb/pkg/util/printer"
"github.com/pingcap/tidb/pkg/util/redact"
"github.com/pingcap/tidb/pkg/util/sem"
semv2 "github.com/pingcap/tidb/pkg/util/sem/v2"
"github.com/pingcap/tidb/pkg/util/signal"
stmtsummaryv2 "github.com/pingcap/tidb/pkg/util/stmtsummary/v2"
"github.com/pingcap/tidb/pkg/util/sys/linux"
storageSys "github.com/pingcap/tidb/pkg/util/sys/storage"
"github.com/pingcap/tidb/pkg/util/systimemon"
"github.com/pingcap/tidb/pkg/util/tiflashcompute"
"github.com/pingcap/tidb/pkg/util/topsql"
"github.com/pingcap/tidb/pkg/util/versioninfo"
repository "github.com/pingcap/tidb/pkg/util/workloadrepo"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/push"
"github.com/tikv/client-go/v2/tikv"
"github.com/tikv/client-go/v2/txnkv/transaction"
"go.uber.org/automaxprocs/maxprocs"
"go.uber.org/zap"
)
// Flag Names
const (
nmVersion = "V"
nmConfig = "config"
nmConfigCheck = "config-check"
nmConfigStrict = "config-strict"
nmStore = "store"
nmStorePath = "path"
nmHost = "host"
nmAdvertiseAddress = "advertise-address"
nmPort = "P"
nmCors = "cors"
nmSocket = "socket"
nmRunDDL = "run-ddl"
nmLogLevel = "L"
nmLogFile = "log-file"
nmLogSlowQuery = "log-slow-query"
nmLogGeneral = "log-general"
nmReportStatus = "report-status"
nmStatusHost = "status-host"
nmStatusPort = "status"
nmMetricsAddr = "metrics-addr"
nmMetricsInterval = "metrics-interval"
nmDdlLease = "lease"
nmTokenLimit = "token-limit"
nmPluginDir = "plugin-dir"
nmPluginLoad = "plugin-load"
nmRepairMode = "repair-mode"
nmRepairList = "repair-list"
nmTempDir = "temp-dir"
nmRedact = "redact"
nmProxyProtocolNetworks = "proxy-protocol-networks"
nmProxyProtocolHeaderTimeout = "proxy-protocol-header-timeout"
nmProxyProtocolFallbackable = "proxy-protocol-fallbackable"
nmAffinityCPU = "affinity-cpus"
nmInitializeSecure = "initialize-secure"
nmInitializeInsecure = "initialize-insecure"
nmInitializeSQLFile = "initialize-sql-file"
nmDisconnectOnExpiredPassword = "disconnect-on-expired-password"
nmKeyspaceName = "keyspace-name"
nmTiDBServiceScope = "tidb-service-scope"
nmStandby = "standby"
nmActivationTimeout = "activation-timeout"
nmMaxIdleSeconds = "max-idle-seconds"
)
const (
exitCodeOK = 0
exitCodeErr = 1
exitCodeInt = 128 + int(syscall.SIGINT)
)
var (
version *bool
configPath *string
configCheck *bool
configStrict *bool
// Base
store *string
storePath *string
host *string
advertiseAddress *string
port *string
cors *string
socket *string
enableBinlog *bool
runDDL *bool
ddlLease *string
tokenLimit *int
pluginDir *string
pluginLoad *string
affinityCPU *string
repairMode *bool
repairList *string
tempDir *string
// Log
logLevel *string
logFile *string
logSlowQuery *string
logGeneral *string
// Status
reportStatus *bool
statusHost *string
statusPort *string
metricsAddr *string
metricsInterval *uint
// subcommand collect-log
redactFlag *bool
// PROXY Protocol
proxyProtocolNetworks *string
proxyProtocolHeaderTimeout *uint
proxyProtocolFallbackable *bool
// Bootstrap and security
initializeSecure *bool
initializeInsecure *bool
initializeSQLFile *string
disconnectOnExpiredPassword *bool
keyspaceName *string
serviceScope *string
help *bool
// Standby
standbyMode *bool
activationTimeout *uint
maxIdleSeconds *uint
)
func initFlagSet() *flag.FlagSet {
fset := flag.NewFlagSet(os.Args[0], flag.ExitOnError)
version = flagBoolean(fset, nmVersion, false, "print version information and exit")
configPath = fset.String(nmConfig, "", "config file path")
configCheck = flagBoolean(fset, nmConfigCheck, false, "check config file validity and exit")
configStrict = flagBoolean(fset, nmConfigStrict, false, "enforce config file validity")
// Base
store = fset.String(nmStore, string(config.StoreTypeUniStore), fmt.Sprintf("registered store name, %v", config.StoreTypeList()))
storePath = fset.String(nmStorePath, "/tmp/tidb", "tidb storage path")
host = fset.String(nmHost, "0.0.0.0", "tidb server host")
advertiseAddress = fset.String(nmAdvertiseAddress, "", "tidb server advertise IP")
port = fset.String(nmPort, "4000", "tidb server port")
cors = fset.String(nmCors, "", "tidb server allow cors origin")
socket = fset.String(nmSocket, "/tmp/tidb-{Port}.sock", "The socket file to use for connection.")
runDDL = flagBoolean(fset, nmRunDDL, true, "run ddl worker on this tidb-server")
ddlLease = fset.String(nmDdlLease, "45s", "schema lease duration, very dangerous to change only if you know what you do")
tokenLimit = fset.Int(nmTokenLimit, 1000, "the limit of concurrent executed sessions")
pluginDir = fset.String(nmPluginDir, "/data/deploy/plugin", "the folder that hold plugin")
pluginLoad = fset.String(nmPluginLoad, "", "wait load plugin name(separated by comma)")
affinityCPU = fset.String(nmAffinityCPU, "", "affinity cpu (cpu-no. separated by comma, e.g. 1,2,3)")
repairMode = flagBoolean(fset, nmRepairMode, false, "enable admin repair mode")
repairList = fset.String(nmRepairList, "", "admin repair table list")
tempDir = fset.String(nmTempDir, config.DefTempDir, "tidb temporary directory")
// Log
logLevel = fset.String(nmLogLevel, "info", "log level: info, debug, warn, error, fatal")
logFile = fset.String(nmLogFile, "", "log file path")
logSlowQuery = fset.String(nmLogSlowQuery, "", "slow query file path")
logGeneral = fset.String(nmLogGeneral, "", "general log file path")
// Status
reportStatus = flagBoolean(fset, nmReportStatus, true, "If enable status report HTTP service.")
statusHost = fset.String(nmStatusHost, "0.0.0.0", "tidb server status host")
statusPort = fset.String(nmStatusPort, "10080", "tidb server status port")
metricsAddr = fset.String(nmMetricsAddr, "", "prometheus pushgateway address, leaves it empty will disable prometheus push.")
metricsInterval = fset.Uint(nmMetricsInterval, 15, "prometheus client push interval in second, set \"0\" to disable prometheus push.")
// subcommand collect-log
redactFlag = flagBoolean(fset, nmRedact, false, "remove sensitive words from marked tidb logs when using collect-log subcommand, e.g. ./tidb-server --redact=xxx collect-log <input> <output>")
// PROXY Protocol
proxyProtocolNetworks = fset.String(nmProxyProtocolNetworks, "", "proxy protocol networks allowed IP or *, empty mean disable proxy protocol support")
proxyProtocolHeaderTimeout = fset.Uint(nmProxyProtocolHeaderTimeout, 5, "proxy protocol header read timeout, unit is second. (Deprecated: as proxy protocol using lazy mode, header read timeout no longer used)")
proxyProtocolFallbackable = flagBoolean(fset, nmProxyProtocolFallbackable, false, "enable proxy protocol fallback mode. If it is enabled, connection will return the client IP address when the client does not send PROXY Protocol Header and it will not return any error. (Note: This feature it does NOT follow the PROXY Protocol SPEC)")
// Bootstrap and security
initializeSecure = flagBoolean(fset, nmInitializeSecure, false, "bootstrap tidb-server in secure mode")
initializeInsecure = flagBoolean(fset, nmInitializeInsecure, true, "bootstrap tidb-server in insecure mode")
initializeSQLFile = fset.String(nmInitializeSQLFile, "", "SQL file to execute on first bootstrap")
disconnectOnExpiredPassword = flagBoolean(fset, nmDisconnectOnExpiredPassword, true, "the server disconnects the client when the password is expired")
keyspaceName = fset.String(nmKeyspaceName, "", "keyspace name.")
serviceScope = fset.String(nmTiDBServiceScope, "", "tidb service scope")
help = fset.Bool("help", false, "show the usage")
// Standby
standbyMode = flagBoolean(fset, nmStandby, false, "start tidb-server as standby")
activationTimeout = fset.Uint(nmActivationTimeout, 0, "max time in second allowed for tidb to activate from standby, 0 means no limit")
maxIdleSeconds = fset.Uint(nmMaxIdleSeconds, 0, "max idle seconds for a connection, 0 means no limit")
session.RegisterMockUpgradeFlag(fset)
// Ignore errors; CommandLine is set for ExitOnError.
// nolint:errcheck
fset.Parse(os.Args[1:])
if *help {
fset.Usage()
os.Exit(0)
}
return fset
}
func initDeployMode(cfg *config.Config) error {
return deploymode.Set(cfg.DeployMode)
}
func main() {
fset := initFlagSet()
if args := fset.Args(); len(args) != 0 {
if args[0] == "collect-log" && len(args) > 1 {
output := "-"
if len(args) > 2 {
output = args[2]
}
terror.MustNil(redact.DeRedactFile(*redactFlag, args[1], output))
return
}
}
config.InitializeConfig(*configPath, *configCheck, *configStrict, overrideConfig, fset)
if kerneltype.IsNextGen() {
terror.MustNil(initDeployMode(config.GetGlobalConfig()))
}
if *version {
mustInitVersions()
fmt.Println(printer.GetTiDBInfo())
os.Exit(0)
}
// we cannot add this check inside config.Valid(), as previous '-V' also relies
// on initialized global config.
if kerneltype.IsNextGen() && len(config.GetGlobalConfig().KeyspaceName) == 0 && !config.GetGlobalConfig().Standby.StandByMode {
fmt.Fprintln(os.Stderr, "invalid config: keyspace name or standby mode is required for nextgen TiDB")
os.Exit(0)
} else if kerneltype.IsClassic() && (len(config.GetGlobalConfig().KeyspaceName) > 0 || config.GetGlobalConfig().Standby.StandByMode) {
fmt.Fprintln(os.Stderr, "invalid config: keyspace name or standby mode is not supported for classic TiDB")
os.Exit(0)
}
var standbyController server.StandbyController
if config.GetGlobalConfig().Standby.StandByMode {
standbyController = standby.NewLoadKeyspaceController()
}
var err error
// If running standby mode, wait for activate request.
if standbyController != nil {
standbyController.WaitForActivate()
// EndStandby only execute once. If server is created
// successfully, the defer has no effect. If panics
// before server is created, the defer makes sure to
// notify the activate caller.
defer standbyController.EndStandby(err)
// need to validate config again in case of config change via standby
terror.MustNil(config.GetGlobalConfig().Valid())
}
signal.SetupUSR1Handler()
err = registerStores()
terror.MustNil(err)
err = metricsutil.RegisterMetrics()
terror.MustNil(err)
if vardef.EnableTmpStorageOnOOM.Load() {
config.GetGlobalConfig().UpdateTempStoragePath()
err = disk.InitializeTempDir()
terror.MustNil(err)
err = checkTempStorageQuota()
terror.MustNil(err)
}
err = setupLog()
terror.MustNil(err)
err = memory.InitMemoryHook()
terror.MustNil(err)
_, err = setupExtensions()
terror.MustNil(err)
setupStmtSummary()
err = cpuprofile.StartCPUProfiler()
terror.MustNil(err)
if config.GetGlobalConfig().DisaggregatedTiFlash && config.GetGlobalConfig().UseAutoScaler {
err = tiflashcompute.InitGlobalTopoFetcher(
config.GetGlobalConfig().TiFlashComputeAutoScalerType,
config.GetGlobalConfig().TiFlashComputeAutoScalerAddr,
config.GetGlobalConfig().AutoScalerClusterID,
config.GetGlobalConfig().IsTiFlashComputeFixedPool)
terror.MustNil(err)
}
// Enable failpoints in tikv/client-go if the test API is enabled.
// It appears in the main function to be set before any use of client-go to prevent data race.
if _, err := failpoint.Status("github.com/pingcap/tidb/pkg/server/enableTestAPI"); err == nil {
warnMsg := "tikv/client-go failpoint is enabled, this should NOT happen in the production environment"
logutil.BgLogger().Warn(warnMsg)
tikv.EnableFailpoints()
}
// UniStore is a mock store for tests. It uses store addresses like "store1" which are not a valid
// host:port for gRPC. client-go's store liveness check uses gRPC health check on the store address,
// which may mistakenly mark the UniStore as unreachable and make tests hang.
// Force the liveness check to always return reachable for UniStore.
if config.GetGlobalConfig().Store == config.StoreTypeUniStore {
tikv.EnableFailpoints()
if err := failpoint.Enable("tikvclient/injectLiveness", `return("reachable")`); err != nil {
logutil.BgLogger().Warn("failed to enable tikvclient/injectLiveness for unistore", zap.Error(err))
}
}
if intest.EnableInternalCheck {
logutil.BgLogger().Warn("internal check is enabled, this should NOT happen in the production environment")
}
setGlobalVars()
setupSEM()
err = setCPUAffinity()
terror.MustNil(err)
cgmon.StartCgroupMonitor()
err = setupTracing() // Should before createServer and after setup config.
terror.MustNil(err)
printInfo()
setupMetrics()
keyspaceName := keyspace.GetKeyspaceNameBySettings()
executor.Start()
resourcemanager.InstanceResourceManager.Start()
storage, dom, err := createStoreDDLOwnerMgrAndDomain(keyspaceName)
terror.MustNil(err)
repository.SetupRepository(dom)
svr := createServer(storage, dom)
if standbyController != nil {
standbyController.EndStandby(nil)
svr.StandbyController = standbyController
svr.StandbyController.OnServerCreated(svr)
}
exited := make(chan struct{})
exitCode := exitCodeOK
signal.SetupSignalHandler(func(sig os.Signal) {
svr.Close()
resourcemanager.InstanceResourceManager.Stop()
cleanup(svr, storage, dom)
cpuprofile.StopCPUProfiler()
executor.Stop()
exitCode = exitCodeForSignal(sig)
close(exited)
})
topsql.SetupTopProfiling(keyspace.GetKeyspaceNameBytesBySettings(), svr, dom)
terror.MustNil(svr.Run(dom))
<-exited
if err := syncLog(); err != nil {
// Log sync failure means shutdown did not finish cleanly, so keep
// reporting it as a generic non-zero exit instead of a successful exit.
exitCode = exitCodeErr
}
if exitCode != exitCodeOK {
os.Exit(exitCode)
}
}
func exitCodeForSignal(sig os.Signal) int {
// Standby force shutdown uses SIGINT. Return 128+SIGINT so deployment scripts
// can identify this force-shutdown path.
if sig == syscall.SIGINT {
return exitCodeInt
}
return exitCodeOK
}
func syncLog() error {
if err := log.Sync(); err != nil {
// Don't complain about /dev/stdout as Fsync will return EINVAL.
if pathErr, ok := err.(*fs.PathError); ok {
if pathErr.Path == "/dev/stdout" {
return nil
}
}
fmt.Fprintln(os.Stderr, "sync log err:", err)
return err
}
return nil
}
func checkTempStorageQuota() error {
// check capacity and the quota when EnableTmpStorageOnOOM is enabled
c := config.GetGlobalConfig()
if c.TempStorageQuota >= 0 {
capacityByte, err := storageSys.GetTargetDirectoryCapacity(c.TempStoragePath)
if err != nil {
return err
} else if capacityByte < uint64(c.TempStorageQuota) {
return fmt.Errorf("value of [tmp-storage-quota](%d byte) exceeds the capacity(%d byte) of the [%s] directory", c.TempStorageQuota, capacityByte, c.TempStoragePath)
}
}
return nil
}
func setCPUAffinity() error {
if affinityCPU == nil || len(*affinityCPU) == 0 {
return nil
}
var cpu []int
for _, af := range strings.Split(*affinityCPU, ",") {
af = strings.TrimSpace(af)
if len(af) > 0 {
c, err := strconv.Atoi(af)
if err != nil {
fmt.Fprintf(os.Stderr, "wrong affinity cpu config: %s", *affinityCPU)
return err
}
cpu = append(cpu, c)
}
}
err := linux.SetAffinity(cpu)
if err != nil {
fmt.Fprintf(os.Stderr, "set cpu affinity failure: %v", err)
return err
}
if len(cpu) < runtime.GOMAXPROCS(0) {
log.Info("cpu number less than maxprocs", zap.Int("cpu number ", len(cpu)), zap.Int("maxprocs", runtime.GOMAXPROCS(0)))
runtime.GOMAXPROCS(len(cpu))
}
return nil
}
func registerStores() error {
err := kvstore.Register(config.StoreTypeTiKV, &driver.TiKVDriver{})
if err != nil {
return err
}
err = kvstore.Register(config.StoreTypeMockTiKV, mockstore.MockTiKVDriver{})
if err != nil {
return err
}
err = kvstore.Register(config.StoreTypeUniStore, mockstore.EmbedUnistoreDriver{})
return err
}
func createStoreDDLOwnerMgrAndDomain(keyspaceName string) (kv.Storage, *domain.Domain, error) {
if config.GetGlobalConfig().Store == config.StoreTypeUniStore {
kv.StandAloneTiDB = true
}
storage := kvstore.MustInitStorage(keyspaceName)
if tikvStore, ok := storage.(kv.StorageWithPD); ok {
pdhttpCli := tikvStore.GetPDHTTPClient()
// unistore also implements kv.StorageWithPD, but it does not have PD client.
if pdhttpCli != nil {
pdStatus, err := pdhttpCli.GetStatus(context.Background())
if err != nil {
return nil, nil, err
}
if !kerneltype.IsMatch(pdStatus.KernelType) {
log.Error("kernel type mismatch", zap.String("pd", pdStatus.KernelType),
zap.String("tidb", kerneltype.Name()))
return nil, nil, errors.New("kernel type mismatch")
}
}
}
copr.GlobalMPPFailedStoreProber.Run()
mppcoordmanager.InstanceMPPCoordinatorManager.Run()
// Bootstrap a session to load information schema.
err := ddl.StartOwnerManager(context.Background(), storage)
if err != nil {
return nil, nil, err
}
dom, err := session.BootstrapSession(storage)
if err != nil {
return nil, nil, err
}
return storage, dom, nil
}
// Prometheus push.
const zeroDuration = time.Duration(0)
// pushMetric pushes metrics in background.
func pushMetric(addr string, interval time.Duration) {
if interval == zeroDuration || len(addr) == 0 {
log.Info("disable Prometheus push client")
return
}
log.Info("start prometheus push client", zap.String("server addr", addr), zap.String("interval", interval.String()))
go prometheusPushClient(addr, interval)
}
// prometheusPushClient pushes metrics to Prometheus Pushgateway.
func prometheusPushClient(addr string, interval time.Duration) {
// TODO: TiDB do not have uniq name, so we use host+port to compose a name.
job := "tidb"
pusher := push.New(addr, job)
pusher = pusher.Gatherer(prometheus.DefaultGatherer)
pusher = pusher.Grouping("instance", instanceName())
for {
err := pusher.Push()
if err != nil {
log.Error("could not push metrics to prometheus pushgateway", zap.String("err", err.Error()))
}
time.Sleep(interval)
}
}
func instanceName() string {
cfg := config.GetGlobalConfig()
hostname, err := os.Hostname()
if err != nil {
return "unknown"
}
return fmt.Sprintf("%s_%d", hostname, cfg.Port)
}
// parseDuration parses lease argument string.
func parseDuration(lease string) time.Duration {
dur, err := time.ParseDuration(lease)
if err != nil {
dur, err = time.ParseDuration(lease + "s")
}
if err != nil || dur < 0 {
log.Fatal("invalid lease duration", zap.String("lease", lease))
}
return dur
}
func flagBoolean(fset *flag.FlagSet, name string, defaultVal bool, usage string) *bool {
if !defaultVal {
// Fix #4125, golang do not print default false value in usage, so we append it.
usage = fmt.Sprintf("%s (default false)", usage)
return fset.Bool(name, defaultVal, usage)
}
return fset.Bool(name, defaultVal, usage)
}
// overrideConfig considers command arguments and overrides some config items in the Config.
func overrideConfig(cfg *config.Config, fset *flag.FlagSet) {
actualFlags := make(map[string]bool)
fset.Visit(func(f *flag.Flag) {
actualFlags[f.Name] = true
})
// Base
if actualFlags[nmHost] {
cfg.Host = *host
}
if actualFlags[nmAdvertiseAddress] {
var err error
if len(strings.Split(*advertiseAddress, " ")) > 1 {
err = errors.Errorf("Only support one advertise-address")
}
terror.MustNil(err)
cfg.AdvertiseAddress = *advertiseAddress
}
if len(cfg.AdvertiseAddress) == 0 && cfg.Host == "0.0.0.0" {
cfg.AdvertiseAddress = util.GetLocalIP()
}
if len(cfg.AdvertiseAddress) == 0 {
cfg.AdvertiseAddress = cfg.Host
}
var err error
if actualFlags[nmPort] {
var p int
p, err = strconv.Atoi(*port)
terror.MustNil(err)
cfg.Port = uint(p)
}
if actualFlags[nmCors] {
cfg.Cors = *cors
}
if actualFlags[nmStore] {
cfg.Store = config.StoreType(*store)
}
if actualFlags[nmStorePath] {
cfg.Path = *storePath
}
if actualFlags[nmSocket] {
cfg.Socket = *socket
}
if actualFlags[nmRunDDL] {
cfg.Instance.TiDBEnableDDL.Store(*runDDL)
}
if actualFlags[nmDdlLease] {
cfg.Lease = *ddlLease
}
if actualFlags[nmTokenLimit] {
cfg.TokenLimit = uint(*tokenLimit)
}
if actualFlags[nmPluginLoad] {
cfg.Instance.PluginLoad = *pluginLoad
}
if actualFlags[nmPluginDir] {
cfg.Instance.PluginDir = *pluginDir
}
if actualFlags[nmRepairMode] {
cfg.RepairMode = *repairMode
}
if actualFlags[nmRepairList] {
if cfg.RepairMode {
cfg.RepairTableList = stringToList(*repairList)
}
}
if actualFlags[nmTempDir] {
cfg.TempDir = *tempDir
}
// Log
if actualFlags[nmLogLevel] {
cfg.Log.Level = *logLevel
}
if actualFlags[nmLogFile] {
cfg.Log.File.Filename = *logFile
}
if actualFlags[nmLogSlowQuery] {
cfg.Log.SlowQueryFile = *logSlowQuery
}
if actualFlags[nmLogGeneral] {
cfg.Log.GeneralLogFile = *logGeneral
}
// Status
if actualFlags[nmReportStatus] {
cfg.Status.ReportStatus = *reportStatus
}
if actualFlags[nmStatusHost] {
cfg.Status.StatusHost = *statusHost
}
if actualFlags[nmStatusPort] {
var p int
p, err = strconv.Atoi(*statusPort)
terror.MustNil(err)
cfg.Status.StatusPort = uint(p)
}
if actualFlags[nmMetricsAddr] {
cfg.Status.MetricsAddr = *metricsAddr
}
if actualFlags[nmMetricsInterval] {
cfg.Status.MetricsInterval = *metricsInterval
}
// PROXY Protocol
if actualFlags[nmProxyProtocolNetworks] {
cfg.ProxyProtocol.Networks = *proxyProtocolNetworks
}
if actualFlags[nmProxyProtocolHeaderTimeout] {
cfg.ProxyProtocol.HeaderTimeout = *proxyProtocolHeaderTimeout
}
if actualFlags[nmProxyProtocolFallbackable] {
cfg.ProxyProtocol.Fallbackable = *proxyProtocolFallbackable
}
// Sanity check: can't specify both options
if actualFlags[nmInitializeSecure] && actualFlags[nmInitializeInsecure] {
err = fmt.Errorf("the options -initialize-insecure and -initialize-secure are mutually exclusive")
terror.MustNil(err)
}
// The option --initialize-secure=true ensures that a secure bootstrap is used.
if actualFlags[nmInitializeSecure] {
cfg.Security.SecureBootstrap = *initializeSecure
}
// The option --initialize-insecure=true/false was used.
// Store the inverted value of this to the secure bootstrap cfg item
if actualFlags[nmInitializeInsecure] {
cfg.Security.SecureBootstrap = !*initializeInsecure
}
if actualFlags[nmDisconnectOnExpiredPassword] {
cfg.Security.DisconnectOnExpiredPassword = *disconnectOnExpiredPassword
}
// Secure bootstrap initializes with Socket authentication
// which is not supported on windows. Only the insecure bootstrap
// method is supported.
if runtime.GOOS == "windows" && cfg.Security.SecureBootstrap {
err = fmt.Errorf("the option -initialize-secure is not supported on Windows")
terror.MustNil(err)
}
// Initialize SQL File is used to run a set of SQL statements after first bootstrap.
// It is important in the use case that you want to set GLOBAL variables, which
// are persisted to the cluster and not read from a config file.
if actualFlags[nmInitializeSQLFile] {
if _, err := os.Stat(*initializeSQLFile); err != nil {
err = fmt.Errorf("can not access -initialize-sql-file %s", *initializeSQLFile)
terror.MustNil(err)
}
cfg.InitializeSQLFile = *initializeSQLFile
}
if actualFlags[nmKeyspaceName] {
cfg.KeyspaceName = *keyspaceName
}
if actualFlags[nmTiDBServiceScope] {
err = naming.Check(*serviceScope)
terror.MustNil(err)
cfg.Instance.TiDBServiceScope = *serviceScope
}
if actualFlags[nmStandby] {
cfg.Standby.StandByMode = *standbyMode
}
if actualFlags[nmActivationTimeout] {
cfg.Standby.ActivationTimeout = *activationTimeout
}
if actualFlags[nmMaxIdleSeconds] {
cfg.Standby.MaxIdleSeconds = *maxIdleSeconds
}
}
func validateVersionConfigPolicy(cfg *config.Config) error {
// allow users to set version info is a bad feature, we forbid it in next-gen.
if kerneltype.IsNextGen() && (len(cfg.TiDBEdition) > 0 || len(cfg.TiDBReleaseVersion) > 0 || len(cfg.ServerVersion) > 0) {
return errors.New("config options tidb-edition, tidb-release-version and server-version are not allowed to set in nextgen kernel")
}
return nil
}
func deriveRuntimeVersionsFromBuildInfo(releaseVersion string) (normalizedReleaseVersion string, serverVersion string, err error) {
normalizedReleaseVersion = mysql.NormalizeTiDBReleaseVersionForNextGen(releaseVersion)
serverVersion, err = mysql.BuildTiDBXServerVersion(normalizedReleaseVersion)
if err != nil {
return "", "", errors.Annotate(err, "invalid tidb release version for nextgen kernel")
}
return normalizedReleaseVersion, serverVersion, nil
}
func initVersions(cfg *config.Config) error {
if err := validateVersionConfigPolicy(cfg); err != nil {
return err
}
if kerneltype.IsNextGen() {
normalizedReleaseVersion, serverVersion, err := deriveRuntimeVersionsFromBuildInfo(mysql.TiDBReleaseVersion)
if err != nil {
return err
}
mysql.TiDBReleaseVersion = normalizedReleaseVersion
mysql.ServerVersion = serverVersion
return nil
}
if len(cfg.TiDBEdition) > 0 {
versioninfo.TiDBEdition = cfg.TiDBEdition
}
if len(cfg.TiDBReleaseVersion) > 0 {
mysql.TiDBReleaseVersion = cfg.TiDBReleaseVersion
}
if len(cfg.ServerVersion) > 0 {
mysql.ServerVersion = cfg.ServerVersion
}
return nil
}
func mustInitVersions() {
cfg := config.GetGlobalConfig()
terror.MustNil(initVersions(cfg))
}
func setGlobalVars() {
cfg := config.GetGlobalConfig()
// config.DeprecatedOptions records the config options that should be moved to [instance] section.
for _, deprecatedOption := range config.DeprecatedOptions {
for oldName := range deprecatedOption.NameMappings {
switch deprecatedOption.SectionName {
case "":
switch oldName {
case "check-mb4-value-in-utf8":
cfg.Instance.CheckMb4ValueInUTF8.Store(cfg.CheckMb4ValueInUTF8.Load())
case "enable-collect-execution-info":
cfg.Instance.EnableCollectExecutionInfo.Store(cfg.EnableCollectExecutionInfo)
case "max-server-connections":
cfg.Instance.MaxConnections = cfg.MaxServerConnections
case "run-ddl":
cfg.Instance.TiDBEnableDDL.Store(cfg.RunDDL)
}
case "log":
switch oldName {
case "enable-slow-log":
cfg.Instance.EnableSlowLog.Store(cfg.Log.EnableSlowLog.Load())
case "slow-threshold":
cfg.Instance.SlowThreshold = cfg.Log.SlowThreshold
case "record-plan-in-slow-log":
cfg.Instance.RecordPlanInSlowLog = cfg.Log.RecordPlanInSlowLog
}
case "performance":
if oldName == "force-priority" {
cfg.Instance.ForcePriority = cfg.Performance.ForcePriority
}
case "plugin":
switch oldName {
case "load":
cfg.Instance.PluginLoad = cfg.Plugin.Load
case "dir":
cfg.Instance.PluginDir = cfg.Plugin.Dir
}
default:
}
}
}
// Disable automaxprocs log
nopLog := func(string, ...any) {}
_, err := maxprocs.Set(maxprocs.Logger(nopLog))
terror.MustNil(err)
// We should respect to user's settings in config file.
// The default value of MaxProcs is 0, runtime.GOMAXPROCS(0) is no-op.
runtime.GOMAXPROCS(int(cfg.Performance.MaxProcs))
util.SetGOGC(cfg.Performance.GOGC)
schemaLeaseDuration := parseDuration(cfg.Lease)
if schemaLeaseDuration <= 0 {
// previous version allow set schema lease to 0, and mainly used on
// uni-store and for test, to be compatible we set it to default value here.
log.Warn("schema lease is invalid, use default value",
zap.String("lease", schemaLeaseDuration.String()))
schemaLeaseDuration = config.DefSchemaLease
}
vardef.SetSchemaLease(schemaLeaseDuration)
statsLeaseDuration := parseDuration(cfg.Performance.StatsLease)
vardef.SetStatsLease(statsLeaseDuration)
planReplayerGCLease := parseDuration(cfg.Performance.PlanReplayerGCLease)
vardef.SetPlanReplayerGCLease(planReplayerGCLease)
bindinfo.Lease = parseDuration(cfg.Performance.BindInfoLease)
statistics.RatioOfPseudoEstimate.Store(cfg.Performance.PseudoEstimateRatio)
if cfg.SplitTable {
atomic.StoreUint32(&ddl.EnableSplitTableRegion, 1)
}
plannercore.AllowCartesianProduct.Store(cfg.Performance.CrossJoin)
privileges.SkipWithGrant = cfg.Security.SkipGrantTable
if cfg.Performance.TxnTotalSizeLimit == config.DefTxnTotalSizeLimit {
// practically deprecate the config, let the new session memory tracker take charge of it.
kv.TxnTotalSizeLimit.Store(config.SuperLargeTxnSize)
} else {
kv.TxnTotalSizeLimit.Store(cfg.Performance.TxnTotalSizeLimit)
}
if cfg.Performance.TxnEntrySizeLimit > config.MaxTxnEntrySizeLimit {
log.Fatal("cannot set txn entry size limit larger than 120M")
}
kv.TxnEntrySizeLimit.Store(cfg.Performance.TxnEntrySizeLimit)
priority := mysql.Str2Priority(cfg.Instance.ForcePriority)
vardef.ForcePriority = int32(priority)
vardef.ProcessGeneralLog.Store(cfg.Instance.TiDBGeneralLog)
vardef.EnablePProfSQLCPU.Store(cfg.Instance.EnablePProfSQLCPU)
vardef.EnableRCReadCheckTS.Store(cfg.Instance.TiDBRCReadCheckTS)
vardef.IsSandBoxModeEnabled.Store(!cfg.Security.DisconnectOnExpiredPassword)
atomic.StoreUint32(&vardef.DDLSlowOprThreshold, cfg.Instance.DDLSlowOprThreshold)
atomic.StoreUint64(&vardef.ExpensiveQueryTimeThreshold, cfg.Instance.ExpensiveQueryTimeThreshold)
atomic.StoreUint64(&vardef.ExpensiveTxnTimeThreshold, cfg.Instance.ExpensiveTxnTimeThreshold)
terror.MustNil(initVersions(cfg))
variable.SetSysVar(vardef.Version, mysql.ServerVersion)
if len(cfg.TiDBEdition) > 0 {
variable.SetSysVar(vardef.VersionComment, "TiDB Server (Apache License 2.0) "+versioninfo.TiDBEdition+" Edition, MySQL 8.0 compatible")
}
if len(cfg.VersionComment) > 0 {
variable.SetSysVar(vardef.VersionComment, cfg.VersionComment)
}
// set instance variables
setInstanceVar := func(name string, value string) {
if value == "" || value == "0" {
return
}
old := variable.GetSysVar(name)
tmp := *old
tmp.Value = value
tmp.IsInitedFromConfig = true
variable.RegisterSysVar(&tmp)
}
{
setInstanceVar(vardef.TiDBStmtSummaryMaxStmtCount, strconv.FormatUint(cfg.Instance.StmtSummaryMaxStmtCount, 10))
setInstanceVar(vardef.TiDBServerMemoryLimit, cfg.Instance.ServerMemoryLimit)
setInstanceVar(vardef.TiDBMemArbitratorMode, cfg.Instance.MemArbitratorMode)
setInstanceVar(vardef.TiDBMemArbitratorSoftLimit, cfg.Instance.MemArbitratorSoftLimit)
setInstanceVar(vardef.TiDBServerMemoryLimitGCTrigger, cfg.Instance.ServerMemoryLimitGCTrigger)
setInstanceVar(vardef.TiDBInstancePlanCacheMaxMemSize, cfg.Instance.InstancePlanCacheMaxMemSize)
setInstanceVar(vardef.TiDBStatsCacheMemQuota, strconv.FormatUint(cfg.Instance.StatsCacheMemQuota, 10))
setInstanceVar(vardef.TiDBMemQuotaBindingCache, strconv.FormatUint(cfg.Instance.MemQuotaBindingCache, 10))
setInstanceVar(vardef.TiDBSchemaCacheSize, cfg.Instance.SchemaCacheSize)
}
variable.SetSysVar(vardef.TiDBForcePriority, mysql.Priority2Str[priority])
variable.SetSysVar(vardef.TiDBOptDistinctAggPushDown, variable.BoolToOnOff(cfg.Performance.DistinctAggPushDown))
variable.SetSysVar(vardef.TiDBOptProjectionPushDown, variable.BoolToOnOff(cfg.Performance.ProjectionPushDown))
variable.SetSysVar(vardef.Port, fmt.Sprintf("%d", cfg.Port))
cfg.Socket = strings.Replace(cfg.Socket, "{Port}", fmt.Sprintf("%d", cfg.Port), 1)
variable.SetSysVar(vardef.Socket, cfg.Socket)
variable.SetSysVar(vardef.DataDir, cfg.Path)
variable.SetSysVar(vardef.TiDBSlowQueryFile, cfg.Log.SlowQueryFile)
variable.SetSysVar(vardef.TiDBIsolationReadEngines, strings.Join(cfg.IsolationRead.Engines, ","))
variable.SetSysVar(vardef.TiDBEnforceMPPExecution, variable.BoolToOnOff(config.GetGlobalConfig().Performance.EnforceMPP))
vardef.MemoryUsageAlarmRatio.Store(cfg.Instance.MemoryUsageAlarmRatio)
variable.SetSysVar(vardef.TiDBConstraintCheckInPlacePessimistic, variable.BoolToOnOff(cfg.PessimisticTxn.ConstraintCheckInPlacePessimistic))
if hostname, err := os.Hostname(); err == nil {
variable.SetSysVar(vardef.Hostname, hostname)
}
vardef.GlobalLogMaxDays.Store(int32(config.GetGlobalConfig().Log.File.MaxDays))
// For CI environment we default enable prepare-plan-cache.
if config.CheckTableBeforeDrop { // only for test
variable.SetSysVar(vardef.TiDBEnablePrepPlanCache, variable.BoolToOnOff(true))
}
// use server-memory-quota as max-plan-cache-memory
plannercore.PreparedPlanCacheMaxMemory.Store(cfg.Performance.ServerMemoryQuota)
total, err := memory.MemTotal()
terror.MustNil(err)
// if server-memory-quota is larger than max-system-memory or not set, use max-system-memory as max-plan-cache-memory
if plannercore.PreparedPlanCacheMaxMemory.Load() > total || plannercore.PreparedPlanCacheMaxMemory.Load() <= 0 {
plannercore.PreparedPlanCacheMaxMemory.Store(total)
}
atomic.StoreUint64(&transaction.CommitMaxBackoff, uint64(parseDuration(cfg.TiKVClient.CommitTimeout).Seconds()*1000))
tikv.SetRegionCacheTTLSec(int64(cfg.TiKVClient.RegionCacheTTL))
domainutil.RepairInfo.SetRepairMode(cfg.RepairMode)
domainutil.RepairInfo.SetRepairTableList(cfg.RepairTableList)
executor.GlobalDiskUsageTracker.SetBytesLimit(cfg.TempStorageQuota)