global.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Copyright 2015 CoreOS, Inc.
  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 command
  15. import (
  16. "time"
  17. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/spf13/cobra"
  18. "github.com/coreos/etcd/clientv3"
  19. "github.com/coreos/etcd/pkg/transport"
  20. )
  21. // GlobalFlags are flags that defined globally
  22. // and are inherited to all sub-commands.
  23. type GlobalFlags struct {
  24. Endpoints string
  25. TLS transport.TLSInfo
  26. }
  27. func mustClient(cmd *cobra.Command) *clientv3.Client {
  28. endpoint, err := cmd.Flags().GetString("endpoint")
  29. if err != nil {
  30. ExitWithError(ExitError, err)
  31. }
  32. // set tls if any one tls option set
  33. var cfgtls *transport.TLSInfo
  34. tls := transport.TLSInfo{}
  35. if tls.CertFile, err = cmd.Flags().GetString("cert"); err == nil {
  36. cfgtls = &tls
  37. }
  38. if tls.KeyFile, err = cmd.Flags().GetString("key"); err == nil {
  39. cfgtls = &tls
  40. }
  41. if tls.CAFile, err = cmd.Flags().GetString("cacert"); err == nil {
  42. cfgtls = &tls
  43. }
  44. cfg := clientv3.Config{
  45. Endpoints: []string{endpoint},
  46. TLS: cfgtls,
  47. DialTimeout: 20 * time.Second,
  48. }
  49. client, err := clientv3.New(cfg)
  50. if err != nil {
  51. ExitWithError(ExitBadConnection, err)
  52. }
  53. return client
  54. }