2018-08-28 10:52:17 -05:00
|
|
|
package etcd_tools
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/tls"
|
|
|
|
"crypto/x509"
|
|
|
|
"errors"
|
2019-04-17 14:37:43 -05:00
|
|
|
"log"
|
2018-08-28 10:52:17 -05:00
|
|
|
"time"
|
|
|
|
|
2019-05-08 16:55:31 -05:00
|
|
|
etcd "go.etcd.io/etcd/clientv3"
|
2018-08-28 10:52:17 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
type EasyConfig struct {
|
|
|
|
Endpoints []string
|
|
|
|
RootCACert string
|
|
|
|
ClientCert string
|
|
|
|
ClientKey string
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c EasyConfig) prepare() (etcd.Config, error) {
|
2019-04-17 14:37:43 -05:00
|
|
|
log.Println("enter prepare() for EasyConfig")
|
|
|
|
log.Printf("clientCert is '%s'", c.ClientCert)
|
2018-08-28 10:52:17 -05:00
|
|
|
cert, err := tls.X509KeyPair([]byte(c.ClientCert), []byte(c.ClientKey))
|
|
|
|
if err != nil {
|
2019-04-17 14:37:43 -05:00
|
|
|
log.Println("error building keypair")
|
2018-08-28 10:52:17 -05:00
|
|
|
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 {
|
2019-04-17 14:37:43 -05:00
|
|
|
log.Printf("can't connect to %s:%s", c.Endpoints[0], err)
|
2018-08-28 10:52:17 -05:00
|
|
|
return etcd.Config{}, err
|
|
|
|
}
|
|
|
|
defer conn.Close()
|
|
|
|
|
|
|
|
err = conn.Handshake()
|
|
|
|
if err != nil {
|
2019-04-17 14:37:43 -05:00
|
|
|
log.Printf("failed tls handshake with %s:%s", c.Endpoints[0], err)
|
2018-08-28 10:52:17 -05:00
|
|
|
return etcd.Config{}, err
|
|
|
|
}
|
|
|
|
|
|
|
|
r := etcd.Config{}
|
|
|
|
|
|
|
|
r.Endpoints = c.Endpoints
|
|
|
|
r.DialTimeout = 5 * time.Second
|
|
|
|
r.TLS = tc
|
|
|
|
|
|
|
|
return r, nil
|
|
|
|
}
|