github.com/pingcap/tiflow@v0.0.0-20240520035814-5bf52d54e205/pkg/pdutil/utils.go (about) 1 // Copyright 2022 PingCAP, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 package pdutil 15 16 import ( 17 "context" 18 "strconv" 19 20 "github.com/pingcap/log" 21 "github.com/pingcap/tiflow/pkg/config" 22 cerror "github.com/pingcap/tiflow/pkg/errors" 23 pd "github.com/tikv/pd/client" 24 "go.uber.org/zap" 25 ) 26 27 const sourceIDName = "source_id" 28 29 // GetSourceID returns the source ID of the TiDB cluster that PD is belonged to. 30 func GetSourceID(ctx context.Context, pdClient pd.Client) (uint64, error) { 31 // only nil in test case 32 if pdClient == nil { 33 return config.DefaultTiDBSourceID, nil 34 } 35 // The default value of sourceID is 1, 36 // which means the sourceID is not changed by user. 37 sourceID := uint64(1) 38 sourceIDConfig, _, err := pdClient.LoadGlobalConfig(ctx, []string{sourceIDName}, "") 39 if err != nil { 40 return 0, cerror.WrapError(cerror.ErrPDEtcdAPIError, err) 41 } 42 if len(sourceIDConfig) != 0 && sourceIDConfig[0].Value != "" { 43 sourceID, err = strconv.ParseUint(sourceIDConfig[0].Value, 10, 64) 44 if err != nil { 45 log.Error("fail to parse sourceID from PD", 46 zap.String("sourceID", sourceIDConfig[0].Value), 47 zap.Error(err)) 48 return 0, cerror.WrapError(cerror.ErrPDEtcdAPIError, err) 49 } 50 } 51 return sourceID, nil 52 }