config.go 2.0 KB

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