This repository has been archived by the owner on Jun 12, 2023. It is now read-only.
forked from etcd-io/etcd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
336 lines (287 loc) · 7.65 KB
/
util.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
// Copyright 2015 The etcd Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package command
import (
"errors"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/url"
"os"
"strings"
"syscall"
"time"
"github.com/bgentry/speakeasy"
"github.com/coreos/etcd/client"
"github.com/coreos/etcd/pkg/transport"
"github.com/urfave/cli"
"golang.org/x/net/context"
)
var (
ErrNoAvailSrc = errors.New("no available argument and stdin")
// the maximum amount of time a dial will wait for a connection to setup.
// 30s is long enough for most of the network conditions.
defaultDialTimeout = 30 * time.Second
)
func argOrStdin(args []string, stdin io.Reader, i int) (string, error) {
if i < len(args) {
return args[i], nil
}
bytes, err := ioutil.ReadAll(stdin)
if string(bytes) == "" || err != nil {
return "", ErrNoAvailSrc
}
return string(bytes), nil
}
func getPeersFlagValue(c *cli.Context) []string {
peerstr := c.GlobalString("endpoints")
if peerstr == "" {
peerstr = os.Getenv("ETCDCTL_ENDPOINTS")
}
if peerstr == "" {
peerstr = c.GlobalString("endpoint")
}
if peerstr == "" {
peerstr = os.Getenv("ETCDCTL_ENDPOINT")
}
if peerstr == "" {
peerstr = c.GlobalString("peers")
}
if peerstr == "" {
peerstr = os.Getenv("ETCDCTL_PEERS")
}
// If we still don't have peers, use a default
if peerstr == "" {
peerstr = "http://127.0.0.1:2379,http://127.0.0.1:4001"
}
return strings.Split(peerstr, ",")
}
func getDomainDiscoveryFlagValue(c *cli.Context) ([]string, error) {
domainstr, insecure := getDiscoveryDomain(c)
// If we still don't have domain discovery, return nothing
if domainstr == "" {
return []string{}, nil
}
discoverer := client.NewSRVDiscover()
eps, err := discoverer.Discover(domainstr)
if err != nil {
return nil, err
}
if insecure {
return eps, err
}
// strip insecure connections
ret := []string{}
for _, ep := range eps {
if strings.HasPrefix("http://", ep) {
fmt.Fprintf(os.Stderr, "ignoring discovered insecure endpoint %q\n", ep)
continue
}
ret = append(ret, ep)
}
return ret, err
}
func getDiscoveryDomain(c *cli.Context) (domainstr string, insecure bool) {
domainstr = c.GlobalString("discovery-srv")
// Use an environment variable if nothing was supplied on the
// command line
if domainstr == "" {
domainstr = os.Getenv("ETCDCTL_DISCOVERY_SRV")
}
insecure = c.GlobalBool("insecure-discovery") || (os.Getenv("ETCDCTL_INSECURE_DISCOVERY") != "")
return domainstr, insecure
}
func getEndpoints(c *cli.Context) ([]string, error) {
eps, err := getDomainDiscoveryFlagValue(c)
if err != nil {
return nil, err
}
// If domain discovery returns no endpoints, check peer flag
if len(eps) == 0 {
eps = getPeersFlagValue(c)
}
for i, ep := range eps {
u, err := url.Parse(ep)
if err != nil {
return nil, err
}
if u.Scheme == "" {
u.Scheme = "http"
}
eps[i] = u.String()
}
return eps, nil
}
func getTransport(c *cli.Context) (*http.Transport, error) {
cafile := c.GlobalString("ca-file")
certfile := c.GlobalString("cert-file")
keyfile := c.GlobalString("key-file")
// Use an environment variable if nothing was supplied on the
// command line
if cafile == "" {
cafile = os.Getenv("ETCDCTL_CA_FILE")
}
if certfile == "" {
certfile = os.Getenv("ETCDCTL_CERT_FILE")
}
if keyfile == "" {
keyfile = os.Getenv("ETCDCTL_KEY_FILE")
}
discoveryDomain, insecure := getDiscoveryDomain(c)
if insecure {
discoveryDomain = ""
}
tls := transport.TLSInfo{
CAFile: cafile,
CertFile: certfile,
KeyFile: keyfile,
ServerName: discoveryDomain,
}
dialTimeout := defaultDialTimeout
totalTimeout := c.GlobalDuration("total-timeout")
if totalTimeout != 0 && totalTimeout < dialTimeout {
dialTimeout = totalTimeout
}
return transport.NewTransport(tls, dialTimeout)
}
func getUsernamePasswordFromFlag(usernameFlag string) (username string, password string, err error) {
return getUsernamePassword("Password: ", usernameFlag)
}
func getUsernamePassword(prompt, usernameFlag string) (username string, password string, err error) {
colon := strings.Index(usernameFlag, ":")
if colon == -1 {
username = usernameFlag
// Prompt for the password.
password, err = speakeasy.Ask(prompt)
if err != nil {
return "", "", err
}
} else {
username = usernameFlag[:colon]
password = usernameFlag[colon+1:]
}
return username, password, nil
}
func mustNewKeyAPI(c *cli.Context) client.KeysAPI {
return client.NewKeysAPI(mustNewClient(c))
}
func mustNewMembersAPI(c *cli.Context) client.MembersAPI {
return client.NewMembersAPI(mustNewClient(c))
}
func mustNewClient(c *cli.Context) client.Client {
hc, err := newClient(c)
if err != nil {
fmt.Fprintln(os.Stderr, err.Error())
os.Exit(1)
}
debug := c.GlobalBool("debug")
if debug {
client.EnablecURLDebug()
}
if !c.GlobalBool("no-sync") {
if debug {
fmt.Fprintf(os.Stderr, "start to sync cluster using endpoints(%s)\n", strings.Join(hc.Endpoints(), ","))
}
ctx, cancel := contextWithTotalTimeout(c)
err := hc.Sync(ctx)
cancel()
if err != nil {
if err == client.ErrNoEndpoints {
fmt.Fprintf(os.Stderr, "etcd cluster has no published client endpoints.\n")
fmt.Fprintf(os.Stderr, "Try '--no-sync' if you want to access non-published client endpoints(%s).\n", strings.Join(hc.Endpoints(), ","))
handleError(c, ExitServerError, err)
}
if isConnectionError(err) {
handleError(c, ExitBadConnection, err)
}
}
if debug {
fmt.Fprintf(os.Stderr, "got endpoints(%s) after sync\n", strings.Join(hc.Endpoints(), ","))
}
}
if debug {
fmt.Fprintf(os.Stderr, "Cluster-Endpoints: %s\n", strings.Join(hc.Endpoints(), ", "))
}
return hc
}
func isConnectionError(err error) bool {
switch t := err.(type) {
case *client.ClusterError:
for _, cerr := range t.Errors {
if !isConnectionError(cerr) {
return false
}
}
return true
case *net.OpError:
if t.Op == "dial" || t.Op == "read" {
return true
}
return isConnectionError(t.Err)
case net.Error:
if t.Timeout() {
return true
}
case syscall.Errno:
if t == syscall.ECONNREFUSED {
return true
}
}
return false
}
func mustNewClientNoSync(c *cli.Context) client.Client {
hc, err := newClient(c)
if err != nil {
fmt.Fprintln(os.Stderr, err.Error())
os.Exit(1)
}
if c.GlobalBool("debug") {
fmt.Fprintf(os.Stderr, "Cluster-Endpoints: %s\n", strings.Join(hc.Endpoints(), ", "))
client.EnablecURLDebug()
}
return hc
}
func newClient(c *cli.Context) (client.Client, error) {
eps, err := getEndpoints(c)
if err != nil {
return nil, err
}
tr, err := getTransport(c)
if err != nil {
return nil, err
}
cfg := client.Config{
Transport: tr,
Endpoints: eps,
HeaderTimeoutPerRequest: c.GlobalDuration("timeout"),
}
uFlag := c.GlobalString("username")
if uFlag == "" {
uFlag = os.Getenv("ETCDCTL_USERNAME")
}
if uFlag != "" {
username, password, err := getUsernamePasswordFromFlag(uFlag)
if err != nil {
return nil, err
}
cfg.Username = username
cfg.Password = password
}
return client.New(cfg)
}
func contextWithTotalTimeout(c *cli.Context) (context.Context, context.CancelFunc) {
return context.WithTimeout(context.Background(), c.GlobalDuration("total-timeout"))
}