config.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. "sigs.k8s.io/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. TrustedCAfile string `json:"trusted-ca-file"`
  31. // CAfile is being deprecated. Use 'TrustedCAfile' instead.
  32. // TODO: deprecate this in v4
  33. CAfile string `json:"ca-file"`
  34. }
  35. // NewConfig creates a new clientv3.Config from a yaml file.
  36. func NewConfig(fpath string) (*clientv3.Config, error) {
  37. b, err := ioutil.ReadFile(fpath)
  38. if err != nil {
  39. return nil, err
  40. }
  41. yc := &yamlConfig{}
  42. err = yaml.Unmarshal(b, yc)
  43. if err != nil {
  44. return nil, err
  45. }
  46. if yc.InsecureTransport {
  47. return &yc.Config, nil
  48. }
  49. var (
  50. cert *tls.Certificate
  51. cp *x509.CertPool
  52. )
  53. if yc.Certfile != "" && yc.Keyfile != "" {
  54. cert, err = tlsutil.NewCert(yc.Certfile, yc.Keyfile, nil)
  55. if err != nil {
  56. return nil, err
  57. }
  58. }
  59. if yc.CAfile != "" && yc.TrustedCAfile == "" {
  60. yc.TrustedCAfile = yc.CAfile
  61. }
  62. if yc.TrustedCAfile != "" {
  63. cp, err = tlsutil.NewCertPool([]string{yc.TrustedCAfile})
  64. if err != nil {
  65. return nil, err
  66. }
  67. }
  68. tlscfg := &tls.Config{
  69. MinVersion: tls.VersionTLS12,
  70. InsecureSkipVerify: yc.InsecureSkipTLSVerify,
  71. RootCAs: cp,
  72. }
  73. if cert != nil {
  74. tlscfg.Certificates = []tls.Certificate{*cert}
  75. }
  76. yc.Config.TLS = tlscfg
  77. return &yc.Config, nil
  78. }