global.go 2.1 KB

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