config.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // Copyright 2017 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. package yaml
  15. import (
  16. "crypto/tls"
  17. "crypto/x509"
  18. "io/ioutil"
  19. "github.com/ghodss/yaml"
  20. "github.com/coreos/etcd/clientv3"
  21. "github.com/coreos/etcd/pkg/tlsutil"
  22. )
  23. type yamlConfig struct {
  24. clientv3.Config
  25. InsecureTransport bool `json:"insecure-transport"`
  26. InsecureSkipTLSVerify bool `json:"insecure-skip-tls-verify"`
  27. Certfile string `json:"cert-file"`
  28. Keyfile string `json:"key-file"`
  29. CAfile string `json:"ca-file"`
  30. }
  31. // NewConfig creates a new clientv3.Config from a yaml file.
  32. func NewConfig(fpath string) (*clientv3.Config, error) {
  33. b, err := ioutil.ReadFile(fpath)
  34. if err != nil {
  35. return nil, err
  36. }
  37. yc := &yamlConfig{}
  38. err = yaml.Unmarshal(b, yc)
  39. if err != nil {
  40. return nil, err
  41. }
  42. if yc.InsecureTransport {
  43. return &yc.Config, nil
  44. }
  45. var (
  46. cert *tls.Certificate
  47. cp *x509.CertPool
  48. )
  49. if yc.Certfile != "" && yc.Keyfile != "" {
  50. cert, err = tlsutil.NewCert(yc.Certfile, yc.Keyfile, nil)
  51. if err != nil {
  52. return nil, err
  53. }
  54. }
  55. if yc.CAfile != "" {
  56. cp, err = tlsutil.NewCertPool([]string{yc.CAfile})
  57. if err != nil {
  58. return nil, err
  59. }
  60. }
  61. tlscfg := &tls.Config{
  62. MinVersion: tls.VersionTLS12,
  63. InsecureSkipVerify: yc.InsecureSkipTLSVerify,
  64. RootCAs: cp,
  65. }
  66. if cert != nil {
  67. tlscfg.Certificates = []tls.Certificate{*cert}
  68. }
  69. yc.Config.TLS = tlscfg
  70. return &yc.Config, nil
  71. }