-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
82 lines (75 loc) · 2.05 KB
/
client.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
package etcdutil
import (
"crypto/tls"
"crypto/x509"
"errors"
"os"
"time"
clientv3 "go.etcd.io/etcd/client/v3"
"go.etcd.io/etcd/client/v3/namespace"
"google.golang.org/grpc"
)
// NewClient creates etcd client.
func NewClient(c *Config) (*clientv3.Client, error) {
timeout, err := time.ParseDuration(c.Timeout)
if err != nil {
return nil, err
}
cfg := clientv3.Config{
Endpoints: c.Endpoints,
DialTimeout: timeout,
//lint:ignore SA1019 etcd client requires to use grpc.WithBlocks()
// see https://etcd.io/docs/v3.4/upgrades/upgrade_3_4/#require-grpcwithblock-for-client-dial
DialOptions: []grpc.DialOption{grpc.WithBlock()},
DialKeepAliveTime: 10 * time.Second,
DialKeepAliveTimeout: 2 * timeout,
PermitWithoutStream: true,
Username: c.Username,
Password: c.Password,
}
tlsCfg := &tls.Config{}
if len(c.TLSCAFile) != 0 || len(c.TLSCA) != 0 {
var rootCACert []byte
if len(c.TLSCAFile) != 0 {
rootCACert, err = os.ReadFile(c.TLSCAFile)
if err != nil {
return nil, err
}
} else {
rootCACert = []byte(c.TLSCA)
}
rootCAs := x509.NewCertPool()
ok := rootCAs.AppendCertsFromPEM(rootCACert)
if !ok {
return nil, errors.New("failed to parse PEM file")
}
tlsCfg.RootCAs = rootCAs
cfg.TLS = tlsCfg
}
if (len(c.TLSCertFile) != 0 && len(c.TLSKeyFile) != 0) || (len(c.TLSCert) != 0 && len(c.TLSKey) != 0) {
var cert tls.Certificate
if len(c.TLSCertFile) != 0 && len(c.TLSKeyFile) != 0 {
cert, err = tls.LoadX509KeyPair(c.TLSCertFile, c.TLSKeyFile)
if err != nil {
return nil, err
}
} else {
cert, err = tls.X509KeyPair([]byte(c.TLSCert), []byte(c.TLSKey))
if err != nil {
return nil, err
}
}
tlsCfg.Certificates = []tls.Certificate{cert}
cfg.TLS = tlsCfg
}
client, err := clientv3.New(cfg)
if err != nil {
return nil, err
}
if c.Prefix != "" {
client.KV = namespace.NewKV(client.KV, c.Prefix)
client.Watcher = namespace.NewWatcher(client.Watcher, c.Prefix)
client.Lease = namespace.NewLease(client.Lease, c.Prefix)
}
return client, nil
}