flag.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  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 flags
  15. import (
  16. "flag"
  17. "fmt"
  18. "net/url"
  19. "os"
  20. "strings"
  21. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/coreos/pkg/capnslog"
  22. "github.com/coreos/etcd/pkg/transport"
  23. )
  24. var (
  25. plog = capnslog.NewPackageLogger("github.com/coreos/etcd/pkg", "flags")
  26. )
  27. // DeprecatedFlag encapsulates a flag that may have been previously valid but
  28. // is now deprecated. If a DeprecatedFlag is set, an error occurs.
  29. type DeprecatedFlag struct {
  30. Name string
  31. }
  32. func (f *DeprecatedFlag) Set(_ string) error {
  33. return fmt.Errorf(`flag "-%s" is no longer supported.`, f.Name)
  34. }
  35. func (f *DeprecatedFlag) String() string {
  36. return ""
  37. }
  38. // IgnoredFlag encapsulates a flag that may have been previously valid but is
  39. // now ignored. If an IgnoredFlag is set, a warning is printed and
  40. // operation continues.
  41. type IgnoredFlag struct {
  42. Name string
  43. }
  44. // IsBoolFlag is defined to allow the flag to be defined without an argument
  45. func (f *IgnoredFlag) IsBoolFlag() bool {
  46. return true
  47. }
  48. func (f *IgnoredFlag) Set(s string) error {
  49. plog.Warningf(`flag "-%s" is no longer supported - ignoring.`, f.Name)
  50. return nil
  51. }
  52. func (f *IgnoredFlag) String() string {
  53. return ""
  54. }
  55. // SetFlagsFromEnv parses all registered flags in the given flagset,
  56. // and if they are not already set it attempts to set their values from
  57. // environment variables. Environment variables take the name of the flag but
  58. // are UPPERCASE, have the prefix "ETCD_", and any dashes are replaced by
  59. // underscores - for example: some-flag => ETCD_SOME_FLAG
  60. func SetFlagsFromEnv(fs *flag.FlagSet) error {
  61. var err error
  62. alreadySet := make(map[string]bool)
  63. fs.Visit(func(f *flag.Flag) {
  64. alreadySet[flagToEnv(f.Name)] = true
  65. })
  66. usedEnvKey := make(map[string]bool)
  67. fs.VisitAll(func(f *flag.Flag) {
  68. key := flagToEnv(f.Name)
  69. if !alreadySet[key] {
  70. val := os.Getenv(key)
  71. if val != "" {
  72. usedEnvKey[key] = true
  73. if serr := fs.Set(f.Name, val); serr != nil {
  74. err = fmt.Errorf("invalid value %q for %s: %v", val, key, serr)
  75. }
  76. plog.Infof("recognized and used environment variable %s=%s", key, val)
  77. }
  78. }
  79. })
  80. for _, env := range os.Environ() {
  81. kv := strings.SplitN(env, "=", 2)
  82. if len(kv) != 2 {
  83. plog.Warningf("found invalid env %s", env)
  84. }
  85. if usedEnvKey[kv[0]] {
  86. continue
  87. }
  88. if alreadySet[kv[0]] {
  89. plog.Infof("recognized environment variable %s, but unused: shadowed by corresponding flag ", kv[0])
  90. continue
  91. }
  92. if strings.HasPrefix(env, "ETCD_") {
  93. plog.Warningf("unrecognized environment variable %s", env)
  94. }
  95. }
  96. return err
  97. }
  98. func flagToEnv(name string) string {
  99. return "ETCD_" + strings.ToUpper(strings.Replace(name, "-", "_", -1))
  100. }
  101. // SetBindAddrFromAddr sets the value of bindAddr flag from the value
  102. // of addr flag. Both flags' Value must be of type IPAddressPort. If the
  103. // bindAddr flag is set and the addr flag is unset, it will set bindAddr to
  104. // [::]:port of addr. Otherwise, it keeps the original values.
  105. func SetBindAddrFromAddr(fs *flag.FlagSet, bindAddrFlagName, addrFlagName string) {
  106. if IsSet(fs, bindAddrFlagName) || !IsSet(fs, addrFlagName) {
  107. return
  108. }
  109. addr := *fs.Lookup(addrFlagName).Value.(*IPAddressPort)
  110. addr.IP = "::"
  111. if err := fs.Set(bindAddrFlagName, addr.String()); err != nil {
  112. plog.Panicf("unexpected flags set error: %v", err)
  113. }
  114. }
  115. // URLsFromFlags decides what URLs should be using two different flags
  116. // as datasources. The first flag's Value must be of type URLs, while
  117. // the second must be of type IPAddressPort. If both of these flags
  118. // are set, an error will be returned. If only the first flag is set,
  119. // the underlying url.URL objects will be returned unmodified. If the
  120. // second flag happens to be set, the underlying IPAddressPort will be
  121. // converted to a url.URL and returned. The Scheme of the returned
  122. // url.URL will be http unless the provided TLSInfo object is non-empty.
  123. // If neither of the flags have been explicitly set, the default value
  124. // of the first flag will be returned unmodified.
  125. func URLsFromFlags(fs *flag.FlagSet, urlsFlagName string, addrFlagName string, tlsInfo transport.TLSInfo) ([]url.URL, error) {
  126. visited := make(map[string]struct{})
  127. fs.Visit(func(f *flag.Flag) {
  128. visited[f.Name] = struct{}{}
  129. })
  130. _, urlsFlagIsSet := visited[urlsFlagName]
  131. _, addrFlagIsSet := visited[addrFlagName]
  132. if addrFlagIsSet {
  133. if urlsFlagIsSet {
  134. return nil, fmt.Errorf("Set only one of flags -%s and -%s", urlsFlagName, addrFlagName)
  135. }
  136. addr := *fs.Lookup(addrFlagName).Value.(*IPAddressPort)
  137. addrURL := url.URL{Scheme: "http", Host: addr.String()}
  138. if !tlsInfo.Empty() {
  139. addrURL.Scheme = "https"
  140. }
  141. return []url.URL{addrURL}, nil
  142. }
  143. return []url.URL(*fs.Lookup(urlsFlagName).Value.(*URLsValue)), nil
  144. }
  145. func IsSet(fs *flag.FlagSet, name string) bool {
  146. set := false
  147. fs.Visit(func(f *flag.Flag) {
  148. if f.Name == name {
  149. set = true
  150. }
  151. })
  152. return set
  153. }