config.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. package config
  2. import (
  3. "flag"
  4. "fmt"
  5. "io/ioutil"
  6. "math/rand"
  7. "net"
  8. "net/url"
  9. "os"
  10. "path/filepath"
  11. "reflect"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "github.com/coreos/etcd/third_party/github.com/BurntSushi/toml"
  16. "github.com/coreos/etcd/log"
  17. ustrings "github.com/coreos/etcd/pkg/strings"
  18. )
  19. // The default location for the etcd configuration file.
  20. const DefaultSystemConfigPath = "/etc/etcd/etcd.conf"
  21. // Config represents the server configuration.
  22. type Config struct {
  23. SystemPath string
  24. Addr string `toml:"addr" env:"ETCD_ADDR"`
  25. BindAddr string `toml:"bind_addr" env:"ETCD_BIND_ADDR"`
  26. CAFile string `toml:"ca_file" env:"ETCD_CA_FILE"`
  27. CertFile string `toml:"cert_file" env:"ETCD_CERT_FILE"`
  28. CPUProfileFile string
  29. CorsOrigins []string `toml:"cors" env:"ETCD_CORS"`
  30. DataDir string `toml:"data_dir" env:"ETCD_DATA_DIR"`
  31. Discovery string `toml:"discovery" env:"ETCD_DISCOVERY"`
  32. Force bool
  33. KeyFile string `toml:"key_file" env:"ETCD_KEY_FILE"`
  34. HTTPReadTimeout float64 `toml:"http_read_timeout" env:"ETCD_HTTP_READ_TIMEOUT"`
  35. HTTPWriteTimeout float64 `toml:"http_write_timeout" env:"ETCD_HTTP_WRITE_TIMEOUT"`
  36. Peers []string `toml:"peers" env:"ETCD_PEERS"`
  37. PeersFile string `toml:"peers_file" env:"ETCD_PEERS_FILE"`
  38. MaxResultBuffer int `toml:"max_result_buffer" env:"ETCD_MAX_RESULT_BUFFER"`
  39. MaxRetryAttempts int `toml:"max_retry_attempts" env:"ETCD_MAX_RETRY_ATTEMPTS"`
  40. RetryInterval float64 `toml:"retry_interval" env:"ETCD_RETRY_INTERVAL"`
  41. Name string `toml:"name" env:"ETCD_NAME"`
  42. Snapshot bool `toml:"snapshot" env:"ETCD_SNAPSHOT"`
  43. SnapshotCount int `toml:"snapshot_count" env:"ETCD_SNAPSHOTCOUNT"`
  44. ShowHelp bool
  45. ShowVersion bool
  46. Verbose bool `toml:"verbose" env:"ETCD_VERBOSE"`
  47. VeryVerbose bool `toml:"very_verbose" env:"ETCD_VERY_VERBOSE"`
  48. VeryVeryVerbose bool `toml:"very_very_verbose" env:"ETCD_VERY_VERY_VERBOSE"`
  49. Peer struct {
  50. Addr string `toml:"addr" env:"ETCD_PEER_ADDR"`
  51. BindAddr string `toml:"bind_addr" env:"ETCD_PEER_BIND_ADDR"`
  52. CAFile string `toml:"ca_file" env:"ETCD_PEER_CA_FILE"`
  53. CertFile string `toml:"cert_file" env:"ETCD_PEER_CERT_FILE"`
  54. KeyFile string `toml:"key_file" env:"ETCD_PEER_KEY_FILE"`
  55. HeartbeatInterval int `toml:"heartbeat_interval" env:"ETCD_PEER_HEARTBEAT_INTERVAL"`
  56. ElectionTimeout int `toml:"election_timeout" env:"ETCD_PEER_ELECTION_TIMEOUT"`
  57. }
  58. strTrace string `toml:"trace" env:"ETCD_TRACE"`
  59. GraphiteHost string `toml:"graphite_host" env:"ETCD_GRAPHITE_HOST"`
  60. Cluster struct {
  61. ActiveSize int `toml:"active_size" env:"ETCD_CLUSTER_ACTIVE_SIZE"`
  62. RemoveDelay float64 `toml:"remove_delay" env:"ETCD_CLUSTER_REMOVE_DELAY"`
  63. SyncInterval float64 `toml:"sync_interval" env:"ETCD_CLUSTER_SYNC_INTERVAL"`
  64. }
  65. }
  66. // New returns a Config initialized with default values.
  67. func New() *Config {
  68. c := new(Config)
  69. c.SystemPath = DefaultSystemConfigPath
  70. c.Addr = "127.0.0.1:4001"
  71. c.HTTPReadTimeout = DefaultReadTimeout
  72. c.HTTPWriteTimeout = DefaultWriteTimeout
  73. c.MaxResultBuffer = 1024
  74. c.MaxRetryAttempts = 3
  75. c.RetryInterval = 10.0
  76. c.Snapshot = true
  77. c.SnapshotCount = 10000
  78. c.Peer.Addr = "127.0.0.1:7001"
  79. c.Peer.HeartbeatInterval = DefaultHeartbeatInterval
  80. c.Peer.ElectionTimeout = DefaultElectionTimeout
  81. rand.Seed(time.Now().UTC().UnixNano())
  82. // Make maximum twice as minimum.
  83. c.RetryInterval = float64(50+rand.Int()%50) * DefaultHeartbeatInterval / 1000
  84. c.Cluster.ActiveSize = DefaultActiveSize
  85. c.Cluster.RemoveDelay = DefaultRemoveDelay
  86. c.Cluster.SyncInterval = DefaultSyncInterval
  87. return c
  88. }
  89. // Loads the configuration from the system config, command line config,
  90. // environment variables, and finally command line arguments.
  91. func (c *Config) Load(arguments []string) error {
  92. var path string
  93. f := flag.NewFlagSet("etcd", -1)
  94. f.SetOutput(ioutil.Discard)
  95. f.StringVar(&path, "config", "", "path to config file")
  96. f.Parse(arguments)
  97. // Load from system file.
  98. if err := c.LoadSystemFile(); err != nil {
  99. return err
  100. }
  101. // Load from config file specified in arguments.
  102. if path != "" {
  103. if err := c.LoadFile(path); err != nil {
  104. return err
  105. }
  106. }
  107. // Load from the environment variables next.
  108. if err := c.LoadEnv(); err != nil {
  109. return err
  110. }
  111. // Load from command line flags.
  112. if err := c.LoadFlags(arguments); err != nil {
  113. return err
  114. }
  115. // Loads peers if a peer file was specified.
  116. if err := c.LoadPeersFile(); err != nil {
  117. return err
  118. }
  119. return nil
  120. }
  121. // Loads from the system etcd configuration file if it exists.
  122. func (c *Config) LoadSystemFile() error {
  123. if _, err := os.Stat(c.SystemPath); os.IsNotExist(err) {
  124. return nil
  125. }
  126. return c.LoadFile(c.SystemPath)
  127. }
  128. // Loads configuration from a file.
  129. func (c *Config) LoadFile(path string) error {
  130. _, err := toml.DecodeFile(path, &c)
  131. return err
  132. }
  133. // LoadEnv loads the configuration via environment variables.
  134. func (c *Config) LoadEnv() error {
  135. if err := c.loadEnv(c); err != nil {
  136. return err
  137. }
  138. if err := c.loadEnv(&c.Peer); err != nil {
  139. return err
  140. }
  141. if err := c.loadEnv(&c.Cluster); err != nil {
  142. return err
  143. }
  144. return nil
  145. }
  146. func (c *Config) loadEnv(target interface{}) error {
  147. value := reflect.Indirect(reflect.ValueOf(target))
  148. typ := value.Type()
  149. for i := 0; i < typ.NumField(); i++ {
  150. field := typ.Field(i)
  151. // Retrieve environment variable.
  152. v := strings.TrimSpace(os.Getenv(field.Tag.Get("env")))
  153. if v == "" {
  154. continue
  155. }
  156. // Set the appropriate type.
  157. switch field.Type.Kind() {
  158. case reflect.Bool:
  159. value.Field(i).SetBool(v != "0" && v != "false")
  160. case reflect.Int:
  161. newValue, err := strconv.ParseInt(v, 10, 0)
  162. if err != nil {
  163. return fmt.Errorf("Parse error: %s: %s", field.Tag.Get("env"), err)
  164. }
  165. value.Field(i).SetInt(newValue)
  166. case reflect.String:
  167. value.Field(i).SetString(v)
  168. case reflect.Slice:
  169. value.Field(i).Set(reflect.ValueOf(ustrings.TrimSplit(v, ",")))
  170. case reflect.Float64:
  171. newValue, err := strconv.ParseFloat(v, 64)
  172. if err != nil {
  173. return fmt.Errorf("Parse error: %s: %s", field.Tag.Get("env"), err)
  174. }
  175. value.Field(i).SetFloat(newValue)
  176. }
  177. }
  178. return nil
  179. }
  180. // Loads configuration from command line flags.
  181. func (c *Config) LoadFlags(arguments []string) error {
  182. var peers, cors, path string
  183. f := flag.NewFlagSet(os.Args[0], flag.ContinueOnError)
  184. f.SetOutput(ioutil.Discard)
  185. f.BoolVar(&c.ShowHelp, "h", false, "")
  186. f.BoolVar(&c.ShowHelp, "help", false, "")
  187. f.BoolVar(&c.ShowVersion, "version", false, "")
  188. f.BoolVar(&c.Force, "f", false, "")
  189. f.BoolVar(&c.Force, "force", false, "")
  190. f.BoolVar(&c.Verbose, "v", c.Verbose, "")
  191. f.BoolVar(&c.VeryVerbose, "vv", c.VeryVerbose, "")
  192. f.BoolVar(&c.VeryVeryVerbose, "vvv", c.VeryVeryVerbose, "")
  193. f.StringVar(&peers, "peers", "", "")
  194. f.StringVar(&c.PeersFile, "peers-file", c.PeersFile, "")
  195. f.StringVar(&c.Name, "name", c.Name, "")
  196. f.StringVar(&c.Addr, "addr", c.Addr, "")
  197. f.StringVar(&c.Discovery, "discovery", c.Discovery, "")
  198. f.StringVar(&c.BindAddr, "bind-addr", c.BindAddr, "")
  199. f.StringVar(&c.Peer.Addr, "peer-addr", c.Peer.Addr, "")
  200. f.StringVar(&c.Peer.BindAddr, "peer-bind-addr", c.Peer.BindAddr, "")
  201. f.StringVar(&c.CAFile, "ca-file", c.CAFile, "")
  202. f.StringVar(&c.CertFile, "cert-file", c.CertFile, "")
  203. f.StringVar(&c.KeyFile, "key-file", c.KeyFile, "")
  204. f.StringVar(&c.Peer.CAFile, "peer-ca-file", c.Peer.CAFile, "")
  205. f.StringVar(&c.Peer.CertFile, "peer-cert-file", c.Peer.CertFile, "")
  206. f.StringVar(&c.Peer.KeyFile, "peer-key-file", c.Peer.KeyFile, "")
  207. f.Float64Var(&c.HTTPReadTimeout, "http-read-timeout", c.HTTPReadTimeout, "")
  208. f.Float64Var(&c.HTTPWriteTimeout, "http-write-timeout", c.HTTPReadTimeout, "")
  209. f.StringVar(&c.DataDir, "data-dir", c.DataDir, "")
  210. f.IntVar(&c.MaxResultBuffer, "max-result-buffer", c.MaxResultBuffer, "")
  211. f.IntVar(&c.MaxRetryAttempts, "max-retry-attempts", c.MaxRetryAttempts, "")
  212. f.Float64Var(&c.RetryInterval, "retry-interval", c.RetryInterval, "")
  213. f.IntVar(&c.Peer.HeartbeatInterval, "peer-heartbeat-interval", c.Peer.HeartbeatInterval, "")
  214. f.IntVar(&c.Peer.ElectionTimeout, "peer-election-timeout", c.Peer.ElectionTimeout, "")
  215. f.StringVar(&cors, "cors", "", "")
  216. f.BoolVar(&c.Snapshot, "snapshot", c.Snapshot, "")
  217. f.IntVar(&c.SnapshotCount, "snapshot-count", c.SnapshotCount, "")
  218. f.StringVar(&c.CPUProfileFile, "cpuprofile", "", "")
  219. f.StringVar(&c.strTrace, "trace", "", "")
  220. f.StringVar(&c.GraphiteHost, "graphite-host", "", "")
  221. f.IntVar(&c.Cluster.ActiveSize, "cluster-active-size", c.Cluster.ActiveSize, "")
  222. f.Float64Var(&c.Cluster.RemoveDelay, "cluster-remove-delay", c.Cluster.RemoveDelay, "")
  223. f.Float64Var(&c.Cluster.SyncInterval, "cluster-sync-interval", c.Cluster.SyncInterval, "")
  224. // BEGIN IGNORED FLAGS
  225. f.StringVar(&path, "config", "", "")
  226. // BEGIN IGNORED FLAGS
  227. if err := f.Parse(arguments); err != nil {
  228. return err
  229. }
  230. // Convert some parameters to lists.
  231. if peers != "" {
  232. c.Peers = ustrings.TrimSplit(peers, ",")
  233. }
  234. if cors != "" {
  235. c.CorsOrigins = ustrings.TrimSplit(cors, ",")
  236. }
  237. return nil
  238. }
  239. // LoadPeersFile loads the peers listed in the peers file.
  240. func (c *Config) LoadPeersFile() error {
  241. if c.PeersFile == "" {
  242. return nil
  243. }
  244. b, err := ioutil.ReadFile(c.PeersFile)
  245. if err != nil {
  246. return fmt.Errorf("Peers file error: %s", err)
  247. }
  248. c.Peers = ustrings.TrimSplit(string(b), ",")
  249. return nil
  250. }
  251. // DataDirFromName sets the data dir from a machine name and issue a warning
  252. // that etcd is guessing.
  253. func (c *Config) DataDirFromName() {
  254. c.DataDir = c.Name + ".etcd"
  255. log.Warnf("Using the directory %s as the etcd curation directory because a directory was not specified. ", c.DataDir)
  256. return
  257. }
  258. // NameFromHostname sets the machine name from the hostname. This is to help
  259. // people get started without thinking up a name.
  260. func (c *Config) NameFromHostname() {
  261. host, err := os.Hostname()
  262. if err != nil && host == "" {
  263. log.Fatal("Node name required and hostname not set. e.g. '-name=name'")
  264. }
  265. c.Name = host
  266. }
  267. // Reset removes all server configuration files.
  268. func (c *Config) Reset() error {
  269. if err := os.RemoveAll(filepath.Join(c.DataDir, "log")); err != nil {
  270. return err
  271. }
  272. if err := os.RemoveAll(filepath.Join(c.DataDir, "conf")); err != nil {
  273. return err
  274. }
  275. if err := os.RemoveAll(filepath.Join(c.DataDir, "snapshot")); err != nil {
  276. return err
  277. }
  278. if err := os.RemoveAll(filepath.Join(c.DataDir, "standby_info")); err != nil {
  279. return err
  280. }
  281. return nil
  282. }
  283. // Sanitize cleans the input fields.
  284. func (c *Config) Sanitize() error {
  285. var err error
  286. var url *url.URL
  287. // Sanitize the URLs first.
  288. if c.Addr, url, err = sanitizeURL(c.Addr, c.EtcdTLSInfo().Scheme()); err != nil {
  289. return fmt.Errorf("Advertised URL: %s", err)
  290. }
  291. if c.BindAddr, err = sanitizeBindAddr(c.BindAddr, url); err != nil {
  292. return fmt.Errorf("Listen Host: %s", err)
  293. }
  294. if c.Peer.Addr, url, err = sanitizeURL(c.Peer.Addr, c.PeerTLSInfo().Scheme()); err != nil {
  295. return fmt.Errorf("Peer Advertised URL: %s", err)
  296. }
  297. if c.Peer.BindAddr, err = sanitizeBindAddr(c.Peer.BindAddr, url); err != nil {
  298. return fmt.Errorf("Peer Listen Host: %s", err)
  299. }
  300. // Only guess the machine name if there is no data dir specified
  301. // because the info file should have our name
  302. if c.Name == "" && c.DataDir == "" {
  303. c.NameFromHostname()
  304. }
  305. if c.DataDir == "" && c.Name != "" && !c.ShowVersion && !c.ShowHelp {
  306. c.DataDirFromName()
  307. }
  308. return nil
  309. }
  310. // EtcdTLSInfo retrieves a TLSInfo object for the etcd server
  311. func (c *Config) EtcdTLSInfo() *TLSInfo {
  312. return &TLSInfo{
  313. CAFile: c.CAFile,
  314. CertFile: c.CertFile,
  315. KeyFile: c.KeyFile,
  316. }
  317. }
  318. // PeerRaftInfo retrieves a TLSInfo object for the peer server.
  319. func (c *Config) PeerTLSInfo() *TLSInfo {
  320. return &TLSInfo{
  321. CAFile: c.Peer.CAFile,
  322. CertFile: c.Peer.CertFile,
  323. KeyFile: c.Peer.KeyFile,
  324. }
  325. }
  326. // MetricsBucketName generates the name that should be used for a
  327. // corresponding MetricsBucket object
  328. func (c *Config) MetricsBucketName() string {
  329. return fmt.Sprintf("etcd.%s", c.Name)
  330. }
  331. // Trace determines if any trace-level information should be emitted
  332. func (c *Config) Trace() bool {
  333. return c.strTrace == "*"
  334. }
  335. func (c *Config) ClusterConfig() *ClusterConfig {
  336. return &ClusterConfig{
  337. ActiveSize: c.Cluster.ActiveSize,
  338. RemoveDelay: c.Cluster.RemoveDelay,
  339. SyncInterval: c.Cluster.SyncInterval,
  340. }
  341. }
  342. // sanitizeURL will cleanup a host string in the format hostname[:port] and
  343. // attach a schema.
  344. func sanitizeURL(host string, defaultScheme string) (string, *url.URL, error) {
  345. // Blank URLs are fine input, just return it
  346. if len(host) == 0 {
  347. return host, &url.URL{}, nil
  348. }
  349. p, err := url.Parse(host)
  350. if err != nil {
  351. return "", nil, err
  352. }
  353. // Make sure the host is in Host:Port format
  354. _, _, err = net.SplitHostPort(host)
  355. if err != nil {
  356. return "", nil, err
  357. }
  358. p = &url.URL{Host: host, Scheme: defaultScheme}
  359. return p.String(), p, nil
  360. }
  361. // sanitizeBindAddr cleans up the BindAddr parameter and appends a port
  362. // if necessary based on the advertised port.
  363. func sanitizeBindAddr(bindAddr string, aurl *url.URL) (string, error) {
  364. // If it is a valid host:port simply return with no further checks.
  365. bhost, bport, err := net.SplitHostPort(bindAddr)
  366. if err == nil && bhost != "" {
  367. return bindAddr, nil
  368. }
  369. // SplitHostPort makes the host optional, but we don't want that.
  370. if bhost == "" && bport != "" {
  371. return "", fmt.Errorf("IP required can't use a port only")
  372. }
  373. // bindAddr doesn't have a port if we reach here so take the port from the
  374. // advertised URL.
  375. _, aport, err := net.SplitHostPort(aurl.Host)
  376. if err != nil {
  377. return "", err
  378. }
  379. return net.JoinHostPort(bindAddr, aport), nil
  380. }