github.com/pingcap/tiflow@v0.0.0-20240520035814-5bf52d54e205/engine/pkg/meta/internal/etcdkv/connection.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 etcdkv 15 16 import ( 17 "sync" 18 19 metaModel "github.com/pingcap/tiflow/engine/pkg/meta/model" 20 "github.com/pingcap/tiflow/pkg/errors" 21 clientv3 "go.etcd.io/etcd/client/v3" 22 ) 23 24 // NewClientConnImpl return a new clientConnImpl 25 func NewClientConnImpl(storeConf *metaModel.StoreConfig) (*clientConnImpl, error) { 26 if storeConf == nil { 27 return nil, errors.ErrMetaParamsInvalid.GenWithStackByArgs("store config is nil") 28 } 29 30 if storeConf.StoreType != metaModel.StoreTypeEtcd { 31 return nil, errors.ErrMetaParamsInvalid.GenWithStack( 32 "etcd conn but get unmatch type:%s", storeConf.StoreType) 33 } 34 35 etcdCli, err := NewEtcdClient(storeConf) 36 if err != nil { 37 return nil, err 38 } 39 40 return &clientConnImpl{ 41 cli: etcdCli, 42 }, nil 43 } 44 45 type clientConnImpl struct { 46 rwLock sync.RWMutex 47 cli *clientv3.Client 48 } 49 50 // GetConn implements GetConn of ClientConn 51 func (cc *clientConnImpl) GetConn() (interface{}, error) { 52 cc.rwLock.RLock() 53 defer cc.rwLock.RUnlock() 54 55 if cc.cli == nil { 56 return nil, errors.ErrMetaOpFail.GenWithStackByArgs("connection is uninitialized") 57 } 58 59 return cc.cli, nil 60 } 61 62 // Close implements Close of ClientConn 63 func (cc *clientConnImpl) Close() error { 64 cc.rwLock.Lock() 65 defer cc.rwLock.Unlock() 66 67 if cc.cli != nil { 68 cc.cli.Close() 69 cc.cli = nil 70 } 71 72 return nil 73 } 74 75 // StoreType implements StoreType of ClientConn 76 func (cc *clientConnImpl) StoreType() metaModel.StoreType { 77 return metaModel.StoreTypeEtcd 78 } 79 80 // NewEtcdClient new a clientv3.Client.For easy test usage 81 func NewEtcdClient(storeConf *metaModel.StoreConfig) (*clientv3.Client, error) { 82 cli, err := clientv3.New(clientv3.Config{ 83 Endpoints: storeConf.Endpoints, 84 // [TODO] TLS, AUTH 85 // [TODO] LOG 86 }) 87 if err != nil { 88 return nil, errors.ErrMetaNewClientFail.Wrap(err) 89 } 90 91 return cli, err 92 }