etcd_tools/easy_config.go

60 lines
1.1 KiB
Go
Raw Normal View History

2018-08-28 10:52:17 -05:00
package etcd_tools
import (
"crypto/tls"
"crypto/x509"
"errors"
"time"
etcd "github.com/coreos/etcd/clientv3"
)
type EasyConfig struct {
Endpoints []string
RootCACert string
ClientCert string
ClientKey string
}
func (c EasyConfig) prepare() (etcd.Config, error) {
cert, err := tls.X509KeyPair([]byte(c.ClientCert), []byte(c.ClientKey))
if err != nil {
return etcd.Config{}, err
}
pool := x509.NewCertPool()
if !pool.AppendCertsFromPEM([]byte(c.RootCACert)) {
return etcd.Config{}, errors.New("Could not append root CA.")
}
tc := &tls.Config{}
tc.Certificates = make([]tls.Certificate, 1)
tc.Certificates[0] = cert
tc.RootCAs = pool
tc.ClientCAs = pool
tc.ClientAuth = tls.RequireAndVerifyClientCert
2018-10-04 16:54:38 -05:00
if len(c.Endpoints) == 0 {
return etcd.Config{}, errors.New("No endpoints specified.")
}
conn, err := tls.Dial("tcp", c.Endpoints[0], tc)
2018-08-28 10:52:17 -05:00
if err != nil {
return etcd.Config{}, err
}
defer conn.Close()
err = conn.Handshake()
if err != nil {
return etcd.Config{}, err
}
r := etcd.Config{}
r.Endpoints = c.Endpoints
r.DialTimeout = 5 * time.Second
r.TLS = tc
return r, nil
}