flag.go 5.4 KB

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