1// Copyright 2018 The etcd Authors
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// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package main
16
17import (
18	"context"
19	"fmt"
20	"io/ioutil"
21	"net/url"
22	"os"
23	"strings"
24	"time"
25
26	"go.etcd.io/etcd/clientv3"
27	"go.etcd.io/etcd/embed"
28
29	"go.uber.org/zap"
30)
31
32func newEmbedURLs(n int) (urls []url.URL) {
33	urls = make([]url.URL, n)
34	for i := 0; i < n; i++ {
35		u, _ := url.Parse(fmt.Sprintf("unix://localhost:%d%06d", os.Getpid(), i))
36		urls[i] = *u
37	}
38	return urls
39}
40
41func setupEmbedCfg(cfg *embed.Config, curls, purls, ics []url.URL) {
42	cfg.Logger = "zap"
43	cfg.LogOutputs = []string{"/dev/null"}
44	// []string{"stderr"} to enable server logging
45
46	var err error
47	cfg.Dir, err = ioutil.TempDir(os.TempDir(), fmt.Sprintf("%016X", time.Now().UnixNano()))
48	if err != nil {
49		panic(err)
50	}
51	os.RemoveAll(cfg.Dir)
52
53	cfg.ClusterState = "new"
54	cfg.LCUrls, cfg.ACUrls = curls, curls
55	cfg.LPUrls, cfg.APUrls = purls, purls
56
57	cfg.InitialCluster = ""
58	for i := range ics {
59		cfg.InitialCluster += fmt.Sprintf(",%d=%s", i, ics[i].String())
60	}
61	cfg.InitialCluster = cfg.InitialCluster[1:]
62}
63
64func getCommand(exec, name, dir, cURL, pURL, cluster string) string {
65	s := fmt.Sprintf("%s --name %s --data-dir %s --listen-client-urls %s --advertise-client-urls %s ",
66		exec, name, dir, cURL, cURL)
67	s += fmt.Sprintf("--listen-peer-urls %s --initial-advertise-peer-urls %s ", pURL, pURL)
68	s += fmt.Sprintf("--initial-cluster %s ", cluster)
69	return s + "--initial-cluster-token tkn --initial-cluster-state new"
70}
71
72func write(ep string) {
73	cli, err := clientv3.New(clientv3.Config{Endpoints: []string{strings.Replace(ep, "/metrics", "", 1)}})
74	if err != nil {
75		lg.Panic("failed to create client", zap.Error(err))
76	}
77	defer cli.Close()
78	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
79	defer cancel()
80	_, err = cli.Put(ctx, "____test", "")
81	if err != nil {
82		lg.Panic("failed to write test key", zap.Error(err))
83	}
84	_, err = cli.Get(ctx, "____test")
85	if err != nil {
86		lg.Panic("failed to read test key", zap.Error(err))
87	}
88	_, err = cli.Delete(ctx, "____test")
89	if err != nil {
90		lg.Panic("failed to delete test key", zap.Error(err))
91	}
92	cli.Watch(ctx, "____test", clientv3.WithCreatedNotify())
93}
94