-
Notifications
You must be signed in to change notification settings - Fork 726
/
server.go
1533 lines (1352 loc) · 47.2 KB
/
server.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 2016 TiKV Project 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.
package server
import (
"bytes"
"context"
"fmt"
"math/rand"
"net/http"
"os"
"path"
"path/filepath"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/coreos/go-semver/semver"
"github.com/golang/protobuf/proto"
"github.com/gorilla/mux"
"github.com/pingcap/errors"
"github.com/pingcap/failpoint"
"github.com/pingcap/kvproto/pkg/diagnosticspb"
"github.com/pingcap/kvproto/pkg/metapb"
"github.com/pingcap/kvproto/pkg/pdpb"
"github.com/pingcap/log"
"github.com/pingcap/sysutil"
"github.com/tikv/pd/pkg/apiutil"
"github.com/tikv/pd/pkg/audit"
"github.com/tikv/pd/pkg/errs"
"github.com/tikv/pd/pkg/etcdutil"
"github.com/tikv/pd/pkg/grpcutil"
"github.com/tikv/pd/pkg/logutil"
"github.com/tikv/pd/pkg/syncutil"
"github.com/tikv/pd/pkg/systimemon"
"github.com/tikv/pd/pkg/typeutil"
"github.com/tikv/pd/server/cluster"
"github.com/tikv/pd/server/config"
"github.com/tikv/pd/server/core"
"github.com/tikv/pd/server/encryptionkm"
"github.com/tikv/pd/server/id"
"github.com/tikv/pd/server/member"
syncer "github.com/tikv/pd/server/region_syncer"
"github.com/tikv/pd/server/schedule"
"github.com/tikv/pd/server/schedule/hbstream"
"github.com/tikv/pd/server/schedule/placement"
"github.com/tikv/pd/server/storage"
"github.com/tikv/pd/server/storage/endpoint"
"github.com/tikv/pd/server/storage/kv"
"github.com/tikv/pd/server/tso"
"github.com/tikv/pd/server/versioninfo"
"github.com/urfave/negroni"
"go.etcd.io/etcd/clientv3"
"go.etcd.io/etcd/embed"
"go.etcd.io/etcd/pkg/types"
"go.uber.org/zap"
"google.golang.org/grpc"
)
const (
etcdTimeout = time.Second * 3
serverMetricsInterval = time.Minute
leaderTickInterval = 50 * time.Millisecond
// pdRootPath for all pd servers.
pdRootPath = "/pd"
pdAPIPrefix = "/pd/"
pdClusterIDPath = "/pd/cluster_id"
)
var (
// EnableZap enable the zap logger in embed etcd.
EnableZap = false
// EtcdStartTimeout the timeout of the startup etcd.
EtcdStartTimeout = time.Minute * 5
)
// Server is the pd server.
// nolint
type Server struct {
diagnosticspb.DiagnosticsServer
// Server state.
isServing int64
// Server start timestamp
startTimestamp int64
// Configs and initial fields.
cfg *config.Config
serviceMiddlewareCfg *config.ServiceMiddlewareConfig
etcdCfg *embed.Config
serviceMiddlewarePersistOptions *config.ServiceMiddlewarePersistOptions
persistOptions *config.PersistOptions
handler *Handler
ctx context.Context
serverLoopCtx context.Context
serverLoopCancel func()
serverLoopWg sync.WaitGroup
// for PD leader election.
member *member.Member
// etcd client
client *clientv3.Client
// http client
httpClient *http.Client
clusterID uint64 // pd cluster id.
rootPath string
// Server services.
// for id allocator, we can use one allocator for
// store, region and peer, because we just need
// a unique ID.
idAllocator id.Allocator
// for encryption
encryptionKeyManager *encryptionkm.KeyManager
// for storage operation.
storage storage.Storage
// for basicCluster operation.
basicCluster *core.BasicCluster
// for tso.
tsoAllocatorManager *tso.AllocatorManager
// for raft cluster
cluster *cluster.RaftCluster
// For async region heartbeat.
hbStreams *hbstream.HeartbeatStreams
// Zap logger
lg *zap.Logger
logProps *log.ZapProperties
// Add callback functions at different stages
startCallbacks []func()
closeCallbacks []func()
// serviceSafePointLock is a lock for UpdateServiceGCSafePoint
serviceSafePointLock syncutil.Mutex
// hot region history info storeage
hotRegionStorage *storage.HotRegionStorage
// Store as map[string]*grpc.ClientConn
clientConns sync.Map
// tsoDispatcher is used to dispatch different TSO requests to
// the corresponding forwarding TSO channel.
tsoDispatcher sync.Map /* Store as map[string]chan *tsoRequest */
serviceLabels map[string][]apiutil.AccessPath
apiServiceLabelMap map[apiutil.AccessPath]string
serviceAuditBackendLabels map[string]*audit.BackendLabels
auditBackends []audit.Backend
}
// HandlerBuilder builds a server HTTP handler.
type HandlerBuilder func(context.Context, *Server) (http.Handler, ServiceGroup, error)
// ServiceGroup used to register the service.
type ServiceGroup struct {
Name string
Version string
IsCore bool
PathPrefix string
}
const (
// CorePath the core group, is at REST path `/pd/api/v1`.
CorePath = "/pd/api/v1"
// ExtensionsPath the named groups are REST at `/pd/apis/{GROUP_NAME}/{Version}`.
ExtensionsPath = "/pd/apis"
)
func combineBuilderServerHTTPService(ctx context.Context, svr *Server, serviceBuilders ...HandlerBuilder) (map[string]http.Handler, error) {
userHandlers := make(map[string]http.Handler)
registerMap := make(map[string]struct{})
apiService := negroni.New()
recovery := negroni.NewRecovery()
apiService.Use(recovery)
router := mux.NewRouter()
for _, build := range serviceBuilders {
handler, info, err := build(ctx, svr)
if err != nil {
return nil, err
}
if !info.IsCore && len(info.PathPrefix) == 0 && (len(info.Name) == 0 || len(info.Version) == 0) {
return nil, errs.ErrAPIInformationInvalid.FastGenByArgs(info.Name, info.Version)
}
var pathPrefix string
if len(info.PathPrefix) != 0 {
pathPrefix = info.PathPrefix
} else if info.IsCore {
pathPrefix = CorePath
} else {
pathPrefix = path.Join(ExtensionsPath, info.Name, info.Version)
}
if _, ok := registerMap[pathPrefix]; ok {
return nil, errs.ErrServiceRegistered.FastGenByArgs(pathPrefix)
}
log.Info("register REST path", zap.String("path", pathPrefix))
registerMap[pathPrefix] = struct{}{}
if len(info.PathPrefix) != 0 {
// If PathPrefix is specified, register directly into userHandlers
userHandlers[pathPrefix] = handler
} else {
// If PathPrefix is not specified, register into apiService,
// and finally apiService is registered in userHandlers.
router.PathPrefix(pathPrefix).Handler(handler)
if info.IsCore {
// Deprecated
router.Path("/pd/health").Handler(handler)
// Deprecated
router.Path("/pd/ping").Handler(handler)
}
}
}
apiService.UseHandler(router)
userHandlers[pdAPIPrefix] = apiService
return userHandlers, nil
}
// CreateServer creates the UNINITIALIZED pd server with given configuration.
func CreateServer(ctx context.Context, cfg *config.Config, serviceBuilders ...HandlerBuilder) (*Server, error) {
log.Info("PD Config", zap.Reflect("config", cfg))
rand.Seed(time.Now().UnixNano())
serviceMiddlewareCfg := config.NewServiceMiddlewareConfig()
s := &Server{
cfg: cfg,
persistOptions: config.NewPersistOptions(cfg),
serviceMiddlewareCfg: serviceMiddlewareCfg,
serviceMiddlewarePersistOptions: config.NewServiceMiddlewarePersistOptions(serviceMiddlewareCfg),
member: &member.Member{},
ctx: ctx,
startTimestamp: time.Now().Unix(),
DiagnosticsServer: sysutil.NewDiagnosticsServer(cfg.Log.File.Filename),
}
s.handler = newHandler(s)
// create audit backend
s.auditBackends = []audit.Backend{
audit.NewLocalLogBackend(true),
audit.NewPrometheusHistogramBackend(serviceAuditHistogram, false),
}
s.serviceAuditBackendLabels = make(map[string]*audit.BackendLabels)
s.serviceLabels = make(map[string][]apiutil.AccessPath)
s.apiServiceLabelMap = make(map[apiutil.AccessPath]string)
// Adjust etcd config.
etcdCfg, err := s.cfg.GenEmbedEtcdConfig()
if err != nil {
return nil, err
}
if len(serviceBuilders) != 0 {
userHandlers, err := combineBuilderServerHTTPService(ctx, s, serviceBuilders...)
if err != nil {
return nil, err
}
etcdCfg.UserHandlers = userHandlers
}
etcdCfg.ServiceRegister = func(gs *grpc.Server) {
pdpb.RegisterPDServer(gs, &GrpcServer{Server: s})
diagnosticspb.RegisterDiagnosticsServer(gs, s)
}
s.etcdCfg = etcdCfg
if EnableZap {
// The etcd master version has removed embed.Config.SetupLogging.
// Now logger is set up automatically based on embed.Config.Logger,
// Use zap logger in the test, otherwise will panic.
// Reference: https://go.etcd.io/etcd/blob/master/embed/config_logging.go#L45
s.etcdCfg.Logger = "zap"
s.etcdCfg.LogOutputs = []string{"stdout"}
}
s.lg = cfg.GetZapLogger()
s.logProps = cfg.GetZapLogProperties()
return s, nil
}
func (s *Server) startEtcd(ctx context.Context) error {
newCtx, cancel := context.WithTimeout(ctx, EtcdStartTimeout)
defer cancel()
etcd, err := embed.StartEtcd(s.etcdCfg)
if err != nil {
return errs.ErrStartEtcd.Wrap(err).GenWithStackByCause()
}
// Check cluster ID
urlMap, err := types.NewURLsMap(s.cfg.InitialCluster)
if err != nil {
return errs.ErrEtcdURLMap.Wrap(err).GenWithStackByCause()
}
tlsConfig, err := s.cfg.Security.ToTLSConfig()
if err != nil {
return err
}
if err = etcdutil.CheckClusterID(etcd.Server.Cluster().ID(), urlMap, tlsConfig); err != nil {
return err
}
select {
// Wait etcd until it is ready to use
case <-etcd.Server.ReadyNotify():
case <-newCtx.Done():
return errs.ErrCancelStartEtcd.FastGenByArgs()
}
endpoints := []string{s.etcdCfg.ACUrls[0].String()}
log.Info("create etcd v3 client", zap.Strings("endpoints", endpoints), zap.Reflect("cert", s.cfg.Security))
lgc := zap.NewProductionConfig()
lgc.Encoding = log.ZapEncodingName
client, err := clientv3.New(clientv3.Config{
Endpoints: endpoints,
DialTimeout: etcdTimeout,
TLS: tlsConfig,
LogConfig: &lgc,
})
if err != nil {
return errs.ErrNewEtcdClient.Wrap(err).GenWithStackByCause()
}
etcdServerID := uint64(etcd.Server.ID())
// update advertise peer urls.
etcdMembers, err := etcdutil.ListEtcdMembers(client)
if err != nil {
return err
}
for _, m := range etcdMembers.Members {
if etcdServerID == m.ID {
etcdPeerURLs := strings.Join(m.PeerURLs, ",")
if s.cfg.AdvertisePeerUrls != etcdPeerURLs {
log.Info("update advertise peer urls", zap.String("from", s.cfg.AdvertisePeerUrls), zap.String("to", etcdPeerURLs))
s.cfg.AdvertisePeerUrls = etcdPeerURLs
}
}
}
s.client = client
s.httpClient = &http.Client{
Transport: &http.Transport{
DisableKeepAlives: true,
TLSClientConfig: tlsConfig,
},
}
failpoint.Inject("memberNil", func() {
time.Sleep(1500 * time.Millisecond)
})
s.member = member.NewMember(etcd, client, etcdServerID)
return nil
}
// AddStartCallback adds a callback in the startServer phase.
func (s *Server) AddStartCallback(callbacks ...func()) {
s.startCallbacks = append(s.startCallbacks, callbacks...)
}
func (s *Server) startServer(ctx context.Context) error {
var err error
if err = s.initClusterID(); err != nil {
return err
}
log.Info("init cluster id", zap.Uint64("cluster-id", s.clusterID))
// It may lose accuracy if use float64 to store uint64. So we store the
// cluster id in label.
metadataGauge.WithLabelValues(fmt.Sprintf("cluster%d", s.clusterID)).Set(0)
serverInfo.WithLabelValues(versioninfo.PDReleaseVersion, versioninfo.PDGitHash).Set(float64(time.Now().Unix()))
s.rootPath = path.Join(pdRootPath, strconv.FormatUint(s.clusterID, 10))
s.member.MemberInfo(s.cfg, s.Name(), s.rootPath)
s.member.SetMemberDeployPath(s.member.ID())
s.member.SetMemberBinaryVersion(s.member.ID(), versioninfo.PDReleaseVersion)
s.member.SetMemberGitHash(s.member.ID(), versioninfo.PDGitHash)
s.idAllocator = id.NewAllocator(s.client, s.rootPath, s.member.MemberValue())
s.tsoAllocatorManager = tso.NewAllocatorManager(
s.member, s.rootPath, s.cfg,
func() time.Duration { return s.persistOptions.GetMaxResetTSGap() })
// Set up the Global TSO Allocator here, it will be initialized once the PD campaigns leader successfully.
s.tsoAllocatorManager.SetUpAllocator(ctx, tso.GlobalDCLocation, s.member.GetLeadership())
if zone, exist := s.cfg.Labels[config.ZoneLabel]; exist && zone != "" && s.cfg.EnableLocalTSO {
if err = s.tsoAllocatorManager.SetLocalTSOConfig(zone); err != nil {
return err
}
}
s.encryptionKeyManager, err = encryptionkm.NewKeyManager(s.client, &s.cfg.Security.Encryption)
if err != nil {
return err
}
regionStorage, err := storage.NewStorageWithLevelDBBackend(ctx, filepath.Join(s.cfg.DataDir, "region-meta"), s.encryptionKeyManager)
if err != nil {
return err
}
defaultStorage := storage.NewStorageWithEtcdBackend(s.client, s.rootPath)
s.storage = storage.NewCoreStorage(defaultStorage, regionStorage)
s.basicCluster = core.NewBasicCluster()
s.cluster = cluster.NewRaftCluster(ctx, s.clusterID, syncer.NewRegionSyncer(s), s.client, s.httpClient)
s.hbStreams = hbstream.NewHeartbeatStreams(ctx, s.clusterID, s.cluster)
// initial hot_region_storage in here.
s.hotRegionStorage, err = storage.NewHotRegionsStorage(
ctx, filepath.Join(s.cfg.DataDir, "hot-region"), s.encryptionKeyManager, s.handler)
if err != nil {
return err
}
// Run callbacks
for _, cb := range s.startCallbacks {
cb()
}
// Server has started.
atomic.StoreInt64(&s.isServing, 1)
return nil
}
func (s *Server) initClusterID() error {
// Get any cluster key to parse the cluster ID.
resp, err := etcdutil.EtcdKVGet(s.client, pdClusterIDPath)
if err != nil {
return err
}
// If no key exist, generate a random cluster ID.
if len(resp.Kvs) == 0 {
s.clusterID, err = initOrGetClusterID(s.client, pdClusterIDPath)
return err
}
s.clusterID, err = typeutil.BytesToUint64(resp.Kvs[0].Value)
return err
}
// AddCloseCallback adds a callback in the Close phase.
func (s *Server) AddCloseCallback(callbacks ...func()) {
s.closeCallbacks = append(s.closeCallbacks, callbacks...)
}
// Close closes the server.
func (s *Server) Close() {
if !atomic.CompareAndSwapInt64(&s.isServing, 1, 0) {
// server is already closed
return
}
log.Info("closing server")
s.stopServerLoop()
if s.client != nil {
if err := s.client.Close(); err != nil {
log.Error("close etcd client meet error", errs.ZapError(errs.ErrCloseEtcdClient, err))
}
}
if s.httpClient != nil {
s.httpClient.CloseIdleConnections()
}
if s.member.Etcd() != nil {
s.member.Close()
}
if s.hbStreams != nil {
s.hbStreams.Close()
}
if err := s.storage.Close(); err != nil {
log.Error("close storage meet error", errs.ZapError(err))
}
if err := s.hotRegionStorage.Close(); err != nil {
log.Error("close hot region storage meet error", errs.ZapError(err))
}
// Run callbacks
for _, cb := range s.closeCallbacks {
cb()
}
log.Info("close server")
}
// IsClosed checks whether server is closed or not.
func (s *Server) IsClosed() bool {
return atomic.LoadInt64(&s.isServing) == 0
}
// Run runs the pd server.
func (s *Server) Run() error {
go systimemon.StartMonitor(s.ctx, time.Now, func() {
log.Error("system time jumps backward", errs.ZapError(errs.ErrIncorrectSystemTime))
timeJumpBackCounter.Inc()
})
if err := s.startEtcd(s.ctx); err != nil {
return err
}
if err := s.startServer(s.ctx); err != nil {
return err
}
s.startServerLoop(s.ctx)
return nil
}
// SetServiceAuditBackendForHTTP is used to register service audit config for HTTP.
func (s *Server) SetServiceAuditBackendForHTTP(route *mux.Route, labels ...string) {
if len(route.GetName()) == 0 {
return
}
if len(labels) > 0 {
s.SetServiceAuditBackendLabels(route.GetName(), labels)
}
}
// Context returns the context of server.
func (s *Server) Context() context.Context {
return s.ctx
}
// LoopContext returns the loop context of server.
func (s *Server) LoopContext() context.Context {
return s.serverLoopCtx
}
func (s *Server) startServerLoop(ctx context.Context) {
s.serverLoopCtx, s.serverLoopCancel = context.WithCancel(ctx)
s.serverLoopWg.Add(5)
go s.leaderLoop()
go s.etcdLeaderLoop()
go s.serverMetricsLoop()
go s.tsoAllocatorLoop()
go s.encryptionKeyManagerLoop()
}
func (s *Server) stopServerLoop() {
s.serverLoopCancel()
s.serverLoopWg.Wait()
}
func (s *Server) serverMetricsLoop() {
defer logutil.LogPanic()
defer s.serverLoopWg.Done()
ctx, cancel := context.WithCancel(s.serverLoopCtx)
defer cancel()
for {
select {
case <-time.After(serverMetricsInterval):
s.collectEtcdStateMetrics()
case <-ctx.Done():
log.Info("server is closed, exit metrics loop")
return
}
}
}
// tsoAllocatorLoop is used to run the TSO Allocator updating daemon.
func (s *Server) tsoAllocatorLoop() {
defer logutil.LogPanic()
defer s.serverLoopWg.Done()
ctx, cancel := context.WithCancel(s.serverLoopCtx)
defer cancel()
s.tsoAllocatorManager.AllocatorDaemon(ctx)
log.Info("server is closed, exit allocator loop")
}
// encryptionKeyManagerLoop is used to start monitor encryption key changes.
func (s *Server) encryptionKeyManagerLoop() {
defer logutil.LogPanic()
defer s.serverLoopWg.Done()
ctx, cancel := context.WithCancel(s.serverLoopCtx)
defer cancel()
s.encryptionKeyManager.StartBackgroundLoop(ctx)
log.Info("server is closed, exist encryption key manager loop")
}
func (s *Server) collectEtcdStateMetrics() {
etcdStateGauge.WithLabelValues("term").Set(float64(s.member.Etcd().Server.Term()))
etcdStateGauge.WithLabelValues("appliedIndex").Set(float64(s.member.Etcd().Server.AppliedIndex()))
etcdStateGauge.WithLabelValues("committedIndex").Set(float64(s.member.Etcd().Server.CommittedIndex()))
}
func (s *Server) bootstrapCluster(req *pdpb.BootstrapRequest) (*pdpb.BootstrapResponse, error) {
clusterID := s.clusterID
log.Info("try to bootstrap raft cluster",
zap.Uint64("cluster-id", clusterID),
zap.String("request", fmt.Sprintf("%v", req)))
if err := checkBootstrapRequest(clusterID, req); err != nil {
return nil, err
}
clusterMeta := metapb.Cluster{
Id: clusterID,
MaxPeerCount: uint32(s.persistOptions.GetMaxReplicas()),
}
// Set cluster meta
clusterValue, err := clusterMeta.Marshal()
if err != nil {
return nil, errors.WithStack(err)
}
clusterRootPath := endpoint.ClusterRootPath(s.rootPath)
var ops []clientv3.Op
ops = append(ops, clientv3.OpPut(clusterRootPath, string(clusterValue)))
// Set bootstrap time
// Because we will write the cluster meta into etcd directly,
// so we need to handle the root key path manually here.
bootstrapKey := endpoint.AppendToRootPath(s.rootPath, endpoint.ClusterBootstrapTimeKey())
nano := time.Now().UnixNano()
timeData := typeutil.Uint64ToBytes(uint64(nano))
ops = append(ops, clientv3.OpPut(bootstrapKey, string(timeData)))
// Set store meta
storeMeta := req.GetStore()
storePath := endpoint.AppendToRootPath(s.rootPath, endpoint.StorePath(storeMeta.GetId()))
storeValue, err := storeMeta.Marshal()
if err != nil {
return nil, errors.WithStack(err)
}
ops = append(ops, clientv3.OpPut(storePath, string(storeValue)))
regionValue, err := req.GetRegion().Marshal()
if err != nil {
return nil, errors.WithStack(err)
}
// Set region meta with region id.
regionPath := endpoint.AppendToRootPath(s.rootPath, endpoint.RegionPath(req.GetRegion().GetId()))
ops = append(ops, clientv3.OpPut(regionPath, string(regionValue)))
// TODO: we must figure out a better way to handle bootstrap failed, maybe intervene manually.
bootstrapCmp := clientv3.Compare(clientv3.CreateRevision(clusterRootPath), "=", 0)
resp, err := kv.NewSlowLogTxn(s.client).If(bootstrapCmp).Then(ops...).Commit()
if err != nil {
return nil, errs.ErrEtcdTxnInternal.Wrap(err).GenWithStackByCause()
}
if !resp.Succeeded {
log.Warn("cluster already bootstrapped", zap.Uint64("cluster-id", clusterID))
return nil, errs.ErrEtcdTxnConflict.FastGenByArgs()
}
log.Info("bootstrap cluster ok", zap.Uint64("cluster-id", clusterID))
err = s.storage.SaveRegion(req.GetRegion())
if err != nil {
log.Warn("save the bootstrap region failed", errs.ZapError(err))
}
err = s.storage.Flush()
if err != nil {
log.Warn("flush the bootstrap region failed", errs.ZapError(err))
}
if err := s.cluster.Start(s); err != nil {
return nil, err
}
return &pdpb.BootstrapResponse{
ReplicationStatus: s.cluster.GetReplicationMode().GetReplicationStatus(),
}, nil
}
func (s *Server) createRaftCluster() error {
if s.cluster.IsRunning() {
return nil
}
return s.cluster.Start(s)
}
func (s *Server) stopRaftCluster() {
failpoint.Inject("raftclusterIsBusy", func() {})
s.cluster.Stop()
}
// GetAddr returns the server urls for clients.
func (s *Server) GetAddr() string {
return s.cfg.AdvertiseClientUrls
}
// GetClientScheme returns the client URL scheme
func (s *Server) GetClientScheme() string {
if len(s.cfg.Security.CertPath) == 0 && len(s.cfg.Security.KeyPath) == 0 {
return "http"
}
return "https"
}
// GetMemberInfo returns the server member information.
func (s *Server) GetMemberInfo() *pdpb.Member {
return proto.Clone(s.member.Member()).(*pdpb.Member)
}
// GetHandler returns the handler for API.
func (s *Server) GetHandler() *Handler {
return s.handler
}
// GetEndpoints returns the etcd endpoints for outer use.
func (s *Server) GetEndpoints() []string {
return s.client.Endpoints()
}
// GetClient returns builtin etcd client.
func (s *Server) GetClient() *clientv3.Client {
return s.client
}
// GetHTTPClient returns builtin etcd client.
func (s *Server) GetHTTPClient() *http.Client {
return s.httpClient
}
// GetLeader returns the leader of PD cluster(i.e the PD leader).
func (s *Server) GetLeader() *pdpb.Member {
return s.member.GetLeader()
}
// GetMember returns the member of server.
func (s *Server) GetMember() *member.Member {
return s.member
}
// GetStorage returns the backend storage of server.
func (s *Server) GetStorage() storage.Storage {
return s.storage
}
// GetHistoryHotRegionStorage returns the backend storage of historyHotRegion.
func (s *Server) GetHistoryHotRegionStorage() *storage.HotRegionStorage {
return s.hotRegionStorage
}
// SetStorage changes the storage only for test purpose.
// When we use it, we should prevent calling GetStorage, otherwise, it may cause a data race problem.
func (s *Server) SetStorage(storage storage.Storage) {
s.storage = storage
}
// GetBasicCluster returns the basic cluster of server.
func (s *Server) GetBasicCluster() *core.BasicCluster {
return s.basicCluster
}
// GetPersistOptions returns the schedule option.
func (s *Server) GetPersistOptions() *config.PersistOptions {
return s.persistOptions
}
// GetServiceMiddlewarePersistOptions returns the service middleware persist option.
func (s *Server) GetServiceMiddlewarePersistOptions() *config.ServiceMiddlewarePersistOptions {
return s.serviceMiddlewarePersistOptions
}
// GetHBStreams returns the heartbeat streams.
func (s *Server) GetHBStreams() *hbstream.HeartbeatStreams {
return s.hbStreams
}
// GetAllocator returns the ID allocator of server.
func (s *Server) GetAllocator() id.Allocator {
return s.idAllocator
}
// GetTSOAllocatorManager returns the manager of TSO Allocator.
func (s *Server) GetTSOAllocatorManager() *tso.AllocatorManager {
return s.tsoAllocatorManager
}
// Name returns the unique etcd Name for this server in etcd cluster.
func (s *Server) Name() string {
return s.cfg.Name
}
// ClusterID returns the cluster ID of this server.
func (s *Server) ClusterID() uint64 {
return s.clusterID
}
// StartTimestamp returns the start timestamp of this server
func (s *Server) StartTimestamp() int64 {
return s.startTimestamp
}
// GetMembers returns PD server list.
func (s *Server) GetMembers() ([]*pdpb.Member, error) {
if s.IsClosed() {
return nil, errs.ErrServerNotStarted.FastGenByArgs()
}
members, err := cluster.GetMembers(s.GetClient())
return members, err
}
// GetServiceMiddlewareConfig gets the service middleware config information.
func (s *Server) GetServiceMiddlewareConfig() *config.ServiceMiddlewareConfig {
cfg := s.serviceMiddlewareCfg.Clone()
cfg.AuditConfig = *s.serviceMiddlewarePersistOptions.GetAuditConfig()
return cfg
}
// GetConfig gets the config information.
func (s *Server) GetConfig() *config.Config {
cfg := s.cfg.Clone()
cfg.Schedule = *s.persistOptions.GetScheduleConfig().Clone()
cfg.Replication = *s.persistOptions.GetReplicationConfig().Clone()
cfg.PDServerCfg = *s.persistOptions.GetPDServerConfig().Clone()
cfg.ReplicationMode = *s.persistOptions.GetReplicationModeConfig()
cfg.LabelProperty = s.persistOptions.GetLabelPropertyConfig().Clone()
cfg.ClusterVersion = *s.persistOptions.GetClusterVersion()
if s.storage == nil {
return cfg
}
sches, configs, err := s.storage.LoadAllScheduleConfig()
if err != nil {
return cfg
}
payload := make(map[string]interface{})
for i, sche := range sches {
var config interface{}
err := schedule.DecodeConfig([]byte(configs[i]), &config)
if err != nil {
log.Error("failed to decode scheduler config",
zap.String("config", configs[i]),
zap.String("scheduler", sche),
errs.ZapError(err))
continue
}
payload[sche] = config
}
cfg.Schedule.SchedulersPayload = payload
return cfg
}
// GetScheduleConfig gets the balance config information.
func (s *Server) GetScheduleConfig() *config.ScheduleConfig {
return s.persistOptions.GetScheduleConfig().Clone()
}
// SetScheduleConfig sets the balance config information.
func (s *Server) SetScheduleConfig(cfg config.ScheduleConfig) error {
if err := cfg.Validate(); err != nil {
return err
}
if err := cfg.Deprecated(); err != nil {
return err
}
old := s.persistOptions.GetScheduleConfig()
cfg.SchedulersPayload = nil
s.persistOptions.SetScheduleConfig(&cfg)
if err := s.persistOptions.Persist(s.storage); err != nil {
s.persistOptions.SetScheduleConfig(old)
log.Error("failed to update schedule config",
zap.Reflect("new", cfg),
zap.Reflect("old", old),
errs.ZapError(err))
return err
}
log.Info("schedule config is updated", zap.Reflect("new", cfg), zap.Reflect("old", old))
return nil
}
// GetReplicationConfig get the replication config.
func (s *Server) GetReplicationConfig() *config.ReplicationConfig {
return s.persistOptions.GetReplicationConfig().Clone()
}
// SetReplicationConfig sets the replication config.
func (s *Server) SetReplicationConfig(cfg config.ReplicationConfig) error {
if err := cfg.Validate(); err != nil {
return err
}
old := s.persistOptions.GetReplicationConfig()
if cfg.EnablePlacementRules != old.EnablePlacementRules {
raftCluster := s.GetRaftCluster()
if raftCluster == nil {
return errs.ErrNotBootstrapped.GenWithStackByArgs()
}
if cfg.EnablePlacementRules {
// initialize rule manager.
if err := raftCluster.GetRuleManager().Initialize(int(cfg.MaxReplicas), cfg.LocationLabels); err != nil {
return err
}
} else {
// NOTE: can be removed after placement rules feature is enabled by default.
for _, s := range raftCluster.GetStores() {
if !s.IsRemoved() && s.IsTiFlash() {
return errors.New("cannot disable placement rules with TiFlash nodes")
}
}
}
}
var rule *placement.Rule
if cfg.EnablePlacementRules {
// replication.MaxReplicas won't work when placement rule is enabled and not only have one default rule.
defaultRule := s.GetRaftCluster().GetRuleManager().GetRule("pd", "default")
CheckInDefaultRule := func() error {
// replication config won't work when placement rule is enabled and exceeds one default rule
if !(defaultRule != nil &&
len(defaultRule.StartKey) == 0 && len(defaultRule.EndKey) == 0) {
return errors.New("cannot update MaxReplicas or LocationLabels when placement rules feature is enabled and not only default rule exists, please update rule instead")
}
if !(defaultRule.Count == int(old.MaxReplicas) && typeutil.StringsEqual(defaultRule.LocationLabels, []string(old.LocationLabels))) {
return errors.New("cannot to update replication config, the default rules do not consistent with replication config, please update rule instead")
}
return nil
}
if !(cfg.MaxReplicas == old.MaxReplicas && typeutil.StringsEqual(cfg.LocationLabels, old.LocationLabels)) {
if err := CheckInDefaultRule(); err != nil {
return err
}
rule = defaultRule
}
}
if rule != nil {
rule.Count = int(cfg.MaxReplicas)
rule.LocationLabels = cfg.LocationLabels
if err := s.GetRaftCluster().GetRuleManager().SetRule(rule); err != nil {
log.Error("failed to update rule count",
errs.ZapError(err))
return err
}
}
s.persistOptions.SetReplicationConfig(&cfg)
if err := s.persistOptions.Persist(s.storage); err != nil {
s.persistOptions.SetReplicationConfig(old)
if rule != nil {
rule.Count = int(old.MaxReplicas)
if e := s.GetRaftCluster().GetRuleManager().SetRule(rule); e != nil {
log.Error("failed to roll back count of rule when update replication config", errs.ZapError(e))
}
}
log.Error("failed to update replication config",
zap.Reflect("new", cfg),
zap.Reflect("old", old),
errs.ZapError(err))
return err
}
log.Info("replication config is updated", zap.Reflect("new", cfg), zap.Reflect("old", old))
return nil
}
// GetAuditConfig gets the audit config information.
func (s *Server) GetAuditConfig() *config.AuditConfig {
return s.serviceMiddlewarePersistOptions.GetAuditConfig().Clone()
}
// SetAuditConfig sets the audit config.
func (s *Server) SetAuditConfig(cfg config.AuditConfig) error {
old := s.serviceMiddlewarePersistOptions.GetAuditConfig()
s.serviceMiddlewarePersistOptions.SetAuditConfig(&cfg)
if err := s.serviceMiddlewarePersistOptions.Persist(s.storage); err != nil {
s.serviceMiddlewarePersistOptions.SetAuditConfig(old)
log.Error("failed to update Audit config",
zap.Reflect("new", cfg),
zap.Reflect("old", old),
errs.ZapError(err))
return err
}
log.Info("Audit config is updated", zap.Reflect("new", cfg), zap.Reflect("old", old))
return nil
}
// GetPDServerConfig gets the balance config information.
func (s *Server) GetPDServerConfig() *config.PDServerConfig {
return s.persistOptions.GetPDServerConfig().Clone()
}
// SetPDServerConfig sets the server config.
func (s *Server) SetPDServerConfig(cfg config.PDServerConfig) error {
switch cfg.DashboardAddress {
case "auto":
case "none":
default:
if !strings.HasPrefix(cfg.DashboardAddress, "http") {