github.com/pingcap/ticdc@v0.0.0-20220526033649-485a10ef2652/pkg/etcd/etcd.go (about) 1 // Copyright 2020 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 etcd 15 16 import ( 17 "net/url" 18 "time" 19 20 "github.com/pingcap/errors" 21 "github.com/tikv/pd/pkg/tempurl" 22 "go.etcd.io/etcd/embed" 23 ) 24 25 // getFreeListenURLs get free ports and localhost as url. 26 func getFreeListenURLs(n int) (urls []*url.URL, retErr error) { 27 for i := 0; i < n; i++ { 28 u, err := url.Parse(tempurl.Alloc()) 29 if err != nil { 30 retErr = errors.Trace(err) 31 return 32 } 33 urls = append(urls, u) 34 } 35 36 return 37 } 38 39 // SetupEmbedEtcd starts an embed etcd server 40 func SetupEmbedEtcd(dir string) (clientURL *url.URL, e *embed.Etcd, err error) { 41 cfg := embed.NewConfig() 42 cfg.Dir = dir 43 44 urls, err := getFreeListenURLs(2) 45 if err != nil { 46 return 47 } 48 cfg.LPUrls = []url.URL{*urls[0]} 49 cfg.LCUrls = []url.URL{*urls[1]} 50 cfg.Logger = "zap" 51 cfg.LogLevel = "error" 52 clientURL = urls[1] 53 54 e, err = embed.StartEtcd(cfg) 55 if err != nil { 56 return 57 } 58 59 select { 60 case <-e.Server.ReadyNotify(): 61 case <-time.After(60 * time.Second): 62 e.Server.Stop() // trigger a shutdown 63 err = errors.New("server took too long to start") 64 } 65 66 return 67 }