Debian Codegraph @

e2e/etcd.go

raw symbols SCIP
1 package e2e
2
3 import (
4 "fmt"
5 "io/ioutil"
6 "net/url"
7 "os"
8 "strings"
9 "sync/atomic"
10 "time"
11
12 "github.com/coreos/etcd/pkg/expect"
13 )
14
15 type etcdProcessClusterConfig struct {
16 execPath string
17 keepDataDir bool
18 clusterSize int
19 initialToken string
20 discoveryToken string
21 }
22
23 type etcdProcessConfig struct {
24 execPath string
25 args []string
26
27 dataDirPath string
28 keepDataDir bool
29
30 name string
31 curl url.URL
32 purl url.URL
33
34 initialToken string
35 initialCluster string
36 discoveryToken string
37 }
38
39 type etcdProcess struct {
40 cfg *etcdProcessConfig
41 proc *expect.ExpectProcess
42 donec chan struct{} // closed when Interact() terminates
43 }
44
45 type etcdProcessCluster struct {
46 cfg *etcdProcessClusterConfig
47 procs []*etcdProcess
48 }
49
50 var etcdBasePort int32 = 20000
51
52 // NewEtcdProcessCluster generates a new 'etcdProcessCluster'.
53 func (cfg *etcdProcessClusterConfig) NewEtcdProcessCluster() (*etcdProcessCluster, error) {
54 cport := int(atomic.LoadInt32(&etcdBasePort))
55 atomic.AddInt32(&etcdBasePort, int32(3*cfg.clusterSize))
56
57 epc := &etcdProcessCluster{
58 cfg: cfg,
59 procs: make([]*etcdProcess, cfg.clusterSize),
60 }
61
62 ics := make([]string, cfg.clusterSize)
63 for i := 0; i < cfg.clusterSize; i++ {
64 name := fmt.Sprintf("test%d%d.etcd", cport, i)
65 curl := url.URL{Scheme: "http", Host: fmt.Sprintf("localhost:%d", cport+2*i)}
66 purl := url.URL{Scheme: "http", Host: fmt.Sprintf("localhost:%d", cport+2*i+1)}
67 dataDirPath, err := ioutil.TempDir(os.TempDir(), name)
68 if err != nil {
69 return nil, err
70 }
71 ics[i] = fmt.Sprintf("%s=%s", name, purl.String())
72
73 epc.procs[i] = &etcdProcess{
74 cfg: &etcdProcessConfig{
75 execPath: cfg.execPath,
76 args: []string{
77 "--name", name,
78 "--listen-client-urls", curl.String(),
79 "--advertise-client-urls", curl.String(),
80 "--listen-peer-urls", purl.String(),
81 "--initial-advertise-peer-urls", purl.String(),
82 "--initial-cluster-token", cfg.initialToken,
83 "--data-dir", dataDirPath,
84 },
85
86 dataDirPath: dataDirPath,
87 keepDataDir: cfg.keepDataDir,
88
89 name: name,
90 curl: curl,
91 purl: purl,
92
93 initialToken: cfg.initialToken,
94 initialCluster: "",
95 discoveryToken: cfg.discoveryToken,
96 },
97 }
98 }
99
100 for i := 0; i < cfg.clusterSize; i++ {
101 if epc.procs[i].cfg.discoveryToken == "" {
102 cs := strings.Join(ics, ",")
103 epc.procs[i].cfg.initialCluster = cs
104 epc.procs[i].cfg.args = append(epc.procs[i].cfg.args, "--initial-cluster", cs)
105 } else {
106 epc.procs[i].cfg.args = append(epc.procs[i].cfg.args, "--discovery", epc.procs[i].cfg.discoveryToken)
107 }
108 }
109 return epc, nil
110 }
111
112 func (ep *etcdProcess) Stop() error {
113 if ep == nil {
114 return nil
115 }
116 if err := ep.proc.Stop(); err != nil {
117 return err
118 }
119 <-ep.donec
120 return nil
121 }
122
123 func (epc *etcdProcessCluster) ClientEndpoints() []string {
124 eps := make([]string, epc.cfg.clusterSize)
125 for i, ep := range epc.procs {
126 eps[i] = ep.cfg.curl.String()
127 }
128 return eps
129 }
130
131 func (epc *etcdProcessCluster) GRPCEndpoints() []string {
132 eps := make([]string, epc.cfg.clusterSize)
133 for i, ep := range epc.procs {
134 eps[i] = ep.cfg.curl.Host
135 }
136 return eps
137 }
138
139 func (epc *etcdProcessCluster) Stop(d time.Duration) (err error) {
140 errc := make(chan error, 1)
141 go func() { errc <- epc.stop() }()
142 select {
143 case err := <-errc:
144 return err
145 case <-time.After(d):
146 return fmt.Errorf("took longer than %v to Stop cluster", d)
147 }
148 }
149
150 func (epc *etcdProcessCluster) stop() (err error) {
151 for _, p := range epc.procs {
152 if p == nil {
153 continue
154 }
155 if curErr := p.Stop(); curErr != nil {
156 if err != nil {
157 err = fmt.Errorf("%v; %v", err, curErr)
158 } else {
159 err = curErr
160 }
161 }
162 if !p.cfg.keepDataDir {
163 os.RemoveAll(p.cfg.dataDirPath)
164 }
165 }
166 return err
167 }
168
169 func (epc *etcdProcessCluster) Start() error {
170 for i := 0; i < epc.cfg.clusterSize; i++ {
171 cfg := epc.procs[i].cfg
172 if !cfg.keepDataDir {
173 os.RemoveAll(cfg.dataDirPath)
174 }
175 }
176
177 for i := 0; i < epc.cfg.clusterSize; i++ {
178 child, err := expect.NewExpect(epc.procs[i].cfg.execPath, epc.procs[i].cfg.args...)
179 if err != nil {
180 return err
181 }
182 epc.procs[i].proc = child
183 epc.procs[i].donec = make(chan struct{})
184 }
185
186 readyC := make(chan error, epc.cfg.clusterSize)
187 for i := range epc.procs {
188 go func(n int) {
189 readyC <- epc.procs[n].waitReady()
190 }(i)
191 }
192 for range epc.procs {
193 if err := <-readyC; err != nil {
194 epc.Stop(10 * time.Second)
195 return err
196 }
197 }
198 return nil
199 }
200
201 func (ep *etcdProcess) waitReady() error {
202 defer close(ep.donec)
203 return waitReadyExpectProc(ep.proc)
204 }
205
206 func waitReadyExpectProc(exproc *expect.ExpectProcess) error {
207 readyStrs := []string{"enabled capabilities for version", "published"}
208 c := 0
209 matchSet := func(l string) bool {
210 for _, s := range readyStrs {
211 if strings.Contains(l, s) {
212 c++
213 break
214 }
215 }
216 return c == len(readyStrs)
217 }
218 _, err := exproc.ExpectFunc(matchSet)
219 return err
220 }
221
222 type etcdctlCtl struct {
223 api int
224 execPath string
225 endpoints []string
226 dialTimeout time.Duration
227 }
228
229 func (ctl etcdctlCtl) PrefixArgs() []string {
230 cmdArgs := []string{ctl.execPath}
231 switch ctl.api {
232 case 2:
233 cmdArgs = append(cmdArgs, fmt.Sprintf("--total-timeout=%s", ctl.dialTimeout))
234 case 3:
235 cmdArgs = append(cmdArgs, fmt.Sprintf("--dial-timeout=%s", ctl.dialTimeout))
236 default:
237 panic(fmt.Errorf("unknown API version %d", ctl.api))
238 }
239 cmdArgs = append(cmdArgs, fmt.Sprintf("--endpoints=%s", strings.Join(ctl.endpoints, ",")))
240 return cmdArgs
241 }
242
243 func (ctl etcdctlCtl) Put(k, v string) error {
244 cmdArgs := ctl.PrefixArgs()
245 var exp string
246 switch ctl.api {
247 case 2:
248 cmdArgs = append(cmdArgs, "set", k, fmt.Sprintf("%q", v))
249 exp = v
250 case 3:
251 os.Setenv("ETCDCTL_API", "3")
252 defer os.Unsetenv("ETCDCTL_API")
253 cmdArgs = append(cmdArgs, "put", k, fmt.Sprintf("%q", v))
254 exp = "OK"
255 }
256 return spawnWithExpects(cmdArgs, exp)
257 }
258
259 func (ctl etcdctlCtl) Delete(key, val string, num int) error {
260 cmdArgs := ctl.PrefixArgs()
261 var exp string
262 switch ctl.api {
263 case 2:
264 cmdArgs = append(cmdArgs, "rm", key)
265 exp = fmt.Sprintf("PrevNode.Value: %s", val)
266 case 3:
267 os.Setenv("ETCDCTL_API", "3")
268 defer os.Unsetenv("ETCDCTL_API")
269 cmdArgs = append(cmdArgs, "del", key)
270 exp = fmt.Sprintf("%d", num)
271 }
272 return spawnWithExpects(cmdArgs, exp)
273 }
274
275 // KV is key-value pair.
276 type KV struct {
277 Key, Val string
278 }
279
280 func (ctl etcdctlCtl) Get(consistency string, kv KV) error {
281 cmdArgs := ctl.PrefixArgs()
282 var lines []string
283 switch ctl.api {
284 case 2:
285 cmdArgs = append(cmdArgs, "get", kv.Key)
286 if consistency == "l" {
287 cmdArgs = append(cmdArgs, "--quorum")
288 }
289 lines = append(lines, kv.Val)
290 case 3:
291 os.Setenv("ETCDCTL_API", "3")
292 defer os.Unsetenv("ETCDCTL_API")
293 cmdArgs = append(cmdArgs, "get", kv.Key)
294 cmdArgs = append(cmdArgs, fmt.Sprintf("--consistency=%s", consistency))
295 lines = append(lines, kv.Key, kv.Val)
296 }
297 return spawnWithExpects(cmdArgs, lines...)
298 }
299
300 const noOutputLineCount = 2 // cov-enabled binaries emit PASS and coverage count lines
301
302 func spawnWithExpects(args []string, xs ...string) error {
303 proc, err := expect.NewExpect(args[0], args[1:]...)
304 if err != nil {
305 return err
306 }
307 // process until either stdout or stderr contains
308 // the expected string
309 var (
310 lines []string
311 lineFunc = func(txt string) bool { return true }
312 )
313 for _, txt := range xs {
314 for {
315 l, lerr := proc.ExpectFunc(lineFunc)
316 if lerr != nil {
317 proc.Close()
318 return fmt.Errorf("%v (expected %q, got %q)", lerr, txt, lines)
319 }
320 lines = append(lines, l)
321 if strings.Contains(l, txt) {
322 break
323 }
324 }
325 }
326 perr := proc.Close()
327 if len(xs) == 0 && proc.LineCount() != noOutputLineCount { // expect no output
328 return fmt.Errorf("unexpected output (got lines %q, line count %d)", lines, proc.LineCount())
329 }
330 return perr
331 }