-
Notifications
You must be signed in to change notification settings - Fork 6
/
etcdserver.go
81 lines (67 loc) · 1.67 KB
/
etcdserver.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
package testetcd
import (
"fmt"
"io/ioutil"
"math/rand"
"net/url"
"os"
"testing"
"time"
clientv3 "go.etcd.io/etcd/client/v3"
"go.etcd.io/etcd/server/v3/embed"
)
type Embedded struct {
Cfg *embed.Config
Etcd *embed.Etcd
tmpDir string
}
func NewEmbedded() *Embedded {
ecfg := embed.NewConfig()
ecfg.Logger = "zap"
ecfg.LogLevel = "error"
tmpDir, err := ioutil.TempDir("", "etcd_")
if err != nil {
panic(fmt.Sprintf("error making temp dir for embedded etcd: %v", err))
}
ecfg.Dir = tmpDir
clientPort := 1024 + rand.Intn(30000)
peerPort := 1024 + rand.Intn(30000)
ecfg.InitialCluster = fmt.Sprintf("default=http://localhost:%v", peerPort)
peerURL, _ := url.Parse(fmt.Sprintf("http://localhost:%v", peerPort))
ecfg.APUrls = []url.URL{*peerURL}
ecfg.LPUrls = []url.URL{*peerURL}
clientURL, _ := url.Parse(fmt.Sprintf("http://localhost:%v", clientPort))
ecfg.ACUrls = []url.URL{*clientURL}
ecfg.LCUrls = []url.URL{*clientURL}
e, err := embed.StartEtcd(ecfg)
if err != nil {
panic(fmt.Sprintf("failed to start embedded etcd: %v", err))
}
select {
case <-e.Server.ReadyNotify():
fmt.Printf("Started embedded etcd on url: %v\n", clientURL)
case <-time.After(10 * time.Second):
e.Server.Stop() // trigger a shutdown
panic("Embedded etcd server took too long to start!")
}
return &Embedded{
Cfg: ecfg,
Etcd: e,
tmpDir: tmpDir,
}
}
func (e *Embedded) Close() {
os.RemoveAll(e.tmpDir)
e.Etcd.Close()
}
func StartAndConnect(t testing.TB, endpoints []string) *clientv3.Client {
cfg := clientv3.Config{
Endpoints: endpoints,
DialTimeout: time.Second,
}
etcd, err := clientv3.New(cfg)
if err != nil {
t.Fatal(err)
}
return etcd
}