config.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. package server
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "flag"
  6. "io/ioutil"
  7. "net"
  8. "net/url"
  9. "os"
  10. "path/filepath"
  11. "reflect"
  12. "strconv"
  13. "strings"
  14. "github.com/BurntSushi/toml"
  15. )
  16. // The default location for the etcd configuration file.
  17. const DefaultSystemConfigPath = "/etc/etcd/etcd.conf"
  18. // Config represents the server configuration.
  19. type Config struct {
  20. SystemPath string
  21. AdvertisedUrl string `toml:"advertised_url" env:"ETCD_ADVERTISED_URL"`
  22. CAFile string `toml:"ca_file" env:"ETCD_CA_FILE"`
  23. CertFile string `toml:"cert_file" env:"ETCD_CERT_FILE"`
  24. Cors []string `toml:"cors" env:"ETCD_CORS"`
  25. DataDir string `toml:"datadir" env:"ETCD_DATADIR"`
  26. KeyFile string `toml:"key_file" env:"ETCD_KEY_FILE"`
  27. ListenHost string `toml:"listen_host" env:"ETCD_LISTEN_HOST"`
  28. Machines []string `toml:"machines" env:"ETCD_MACHINES"`
  29. MachinesFile string `toml:"machines_file" env:"ETCD_MACHINES_FILE"`
  30. MaxClusterSize int `toml:"max_cluster_size" env:"ETCD_MAX_CLUSTER_SIZE"`
  31. MaxResultBuffer int `toml:"max_result_buffer" env:"ETCD_MAX_RESULT_BUFFER"`
  32. MaxRetryAttempts int `toml:"max_retry_attempts" env:"ETCD_MAX_RETRY_ATTEMPTS"`
  33. Name string `toml:"name" env:"ETCD_NAME"`
  34. Snapshot bool `toml:"snapshot" env:"ETCD_SNAPSHOT"`
  35. Verbose bool `toml:"verbose" env:"ETCD_VERBOSE"`
  36. VeryVerbose bool `toml:"very_verbose" env:"ETCD_VERY_VERBOSE"`
  37. WebURL string `toml:"web_url" env:"ETCD_WEB_URL"`
  38. Peer struct {
  39. AdvertisedUrl string `toml:"advertised_url" env:"ETCD_PEER_ADVERTISED_URL"`
  40. CAFile string `toml:"ca_file" env:"ETCD_PEER_CA_FILE"`
  41. CertFile string `toml:"cert_file" env:"ETCD_PEER_CERT_FILE"`
  42. KeyFile string `toml:"key_file" env:"ETCD_PEER_KEY_FILE"`
  43. ListenHost string `toml:"listen_host" env:"ETCD_PEER_LISTEN_HOST"`
  44. }
  45. }
  46. // NewConfig returns a Config initialized with default values.
  47. func NewConfig() *Config {
  48. c := new(Config)
  49. c.SystemPath = DefaultSystemConfigPath
  50. c.AdvertisedUrl = "127.0.0.1:4001"
  51. c.AdvertisedUrl = "127.0.0.1:4001"
  52. c.DataDir = "."
  53. c.MaxClusterSize = 9
  54. c.MaxResultBuffer = 1024
  55. c.MaxRetryAttempts = 3
  56. c.Peer.AdvertisedUrl = "127.0.0.1:7001"
  57. return c
  58. }
  59. // Loads the configuration from the system config, command line config,
  60. // environment variables, and finally command line arguments.
  61. func (c *Config) Load(arguments []string) error {
  62. var path string
  63. f := flag.NewFlagSet("etcd", -1)
  64. f.SetOutput(ioutil.Discard)
  65. f.StringVar(&path, "config", "", "path to config file")
  66. f.Parse(arguments)
  67. // Load from system file.
  68. if err := c.LoadSystemFile(); err != nil {
  69. return err
  70. }
  71. // Load from config file specified in arguments.
  72. if path != "" {
  73. if err := c.LoadFile(path); err != nil {
  74. return err
  75. }
  76. }
  77. // Load from the environment variables next.
  78. if err := c.LoadEnv(); err != nil {
  79. return err
  80. }
  81. // Load from command line flags.
  82. if err := c.LoadFlags(arguments); err != nil {
  83. return err
  84. }
  85. // Loads machines if a machine file was specified.
  86. if err := c.LoadMachineFile(); err != nil {
  87. return err
  88. }
  89. // Sanitize all the input fields.
  90. if err := c.Sanitize(); err != nil {
  91. return fmt.Errorf("sanitize:", err)
  92. }
  93. return nil
  94. }
  95. // Loads from the system etcd configuration file if it exists.
  96. func (c *Config) LoadSystemFile() error {
  97. if _, err := os.Stat(c.SystemPath); os.IsNotExist(err) {
  98. return nil
  99. }
  100. return c.LoadFile(c.SystemPath)
  101. }
  102. // Loads configuration from a file.
  103. func (c *Config) LoadFile(path string) error {
  104. _, err := toml.DecodeFile(path, &c)
  105. return err
  106. }
  107. // LoadEnv loads the configuration via environment variables.
  108. func (c *Config) LoadEnv() error {
  109. if err := c.loadEnv(c); err != nil {
  110. return err
  111. }
  112. if err := c.loadEnv(&c.Peer); err != nil {
  113. return err
  114. }
  115. return nil
  116. }
  117. func (c *Config) loadEnv(target interface{}) error {
  118. value := reflect.Indirect(reflect.ValueOf(target))
  119. typ := value.Type()
  120. for i := 0; i < typ.NumField(); i++ {
  121. field := typ.Field(i)
  122. // Retrieve environment variable.
  123. v := strings.TrimSpace(os.Getenv(field.Tag.Get("env")))
  124. if v == "" {
  125. continue
  126. }
  127. // Set the appropriate type.
  128. switch field.Type.Kind() {
  129. case reflect.Bool:
  130. value.Field(i).SetBool(v != "0" && v != "false")
  131. case reflect.Int:
  132. newValue, err := strconv.ParseInt(v, 10, 0)
  133. if err != nil {
  134. return fmt.Errorf("Parse error: %s: %s", field.Tag.Get("env"), err)
  135. }
  136. value.Field(i).SetInt(newValue)
  137. case reflect.String:
  138. value.Field(i).SetString(v)
  139. case reflect.Slice:
  140. value.Field(i).Set(reflect.ValueOf(trimsplit(v, ",")))
  141. }
  142. }
  143. return nil
  144. }
  145. // Loads configuration from command line flags.
  146. func (c *Config) LoadFlags(arguments []string) error {
  147. var machines, cors string
  148. var force bool
  149. f := flag.NewFlagSet(os.Args[0], flag.ContinueOnError)
  150. f.BoolVar(&force, "f", false, "force new node configuration if existing is found (WARNING: data loss!)")
  151. f.BoolVar(&c.Verbose, "v", c.Verbose, "verbose logging")
  152. f.BoolVar(&c.VeryVerbose, "vv", c.Verbose, "very verbose logging")
  153. f.StringVar(&machines, "C", "", "the ip address and port of a existing machines in the cluster, sepearate by comma")
  154. f.StringVar(&c.MachinesFile, "CF", c.MachinesFile, "the file contains a list of existing machines in the cluster, seperate by comma")
  155. f.StringVar(&c.Name, "n", c.Name, "the node name (required)")
  156. f.StringVar(&c.AdvertisedUrl, "c", c.AdvertisedUrl, "the advertised public hostname:port for etcd client communication")
  157. f.StringVar(&c.Peer.AdvertisedUrl, "s", c.Peer.AdvertisedUrl, "the advertised public hostname:port for raft server communication")
  158. f.StringVar(&c.ListenHost, "cl", c.ListenHost, "the listening hostname for etcd client communication (defaults to advertised ip)")
  159. f.StringVar(&c.Peer.ListenHost, "sl", c.Peer.ListenHost, "the listening hostname for raft server communication (defaults to advertised ip)")
  160. f.StringVar(&c.WebURL, "w", c.WebURL, "the hostname:port of web interface")
  161. f.StringVar(&c.Peer.CAFile, "serverCAFile", c.Peer.CAFile, "the path of the CAFile")
  162. f.StringVar(&c.Peer.CertFile, "serverCert", c.Peer.CertFile, "the cert file of the server")
  163. f.StringVar(&c.Peer.KeyFile, "serverKey", c.Peer.KeyFile, "the key file of the server")
  164. f.StringVar(&c.CAFile, "clientCAFile", c.CAFile, "the path of the client CAFile")
  165. f.StringVar(&c.CertFile, "clientCert", c.CertFile, "the cert file of the client")
  166. f.StringVar(&c.KeyFile, "clientKey", c.KeyFile, "the key file of the client")
  167. f.StringVar(&c.DataDir, "d", c.DataDir, "the directory to store log and snapshot")
  168. f.BoolVar(&c.Snapshot, "snapshot", c.Snapshot, "open or close snapshot")
  169. f.IntVar(&c.MaxResultBuffer, "m", c.MaxResultBuffer, "the max size of result buffer")
  170. f.IntVar(&c.MaxRetryAttempts, "r", c.MaxRetryAttempts, "the max retry attempts when trying to join a cluster")
  171. f.IntVar(&c.MaxClusterSize, "maxsize", c.MaxClusterSize, "the max size of the cluster")
  172. f.StringVar(&cors, "cors", "", "whitelist origins for cross-origin resource sharing (e.g. '*' or 'http://localhost:8001,etc')")
  173. // These flags are ignored since they were already parsed.
  174. var path string
  175. f.StringVar(&path, "config", "", "path to config file")
  176. f.Parse(arguments)
  177. // Convert some parameters to lists.
  178. if machines != "" {
  179. c.Machines = trimsplit(machines, ",")
  180. }
  181. if cors != "" {
  182. c.Cors = trimsplit(cors, ",")
  183. }
  184. // Force remove server configuration if specified.
  185. if force {
  186. c.Reset()
  187. }
  188. return nil
  189. }
  190. // LoadMachineFile loads the machines listed in the machine file.
  191. func (c *Config) LoadMachineFile() error {
  192. if c.MachinesFile == "" {
  193. return nil
  194. }
  195. b, err := ioutil.ReadFile(c.MachinesFile)
  196. if err != nil {
  197. return fmt.Errorf("Machines file error: %s", err)
  198. }
  199. c.Machines = trimsplit(string(b), ",")
  200. return nil
  201. }
  202. // Reset removes all server configuration files.
  203. func (c *Config) Reset() error {
  204. if err := os.RemoveAll(filepath.Join(c.DataDir, "info")); err != nil {
  205. return err
  206. }
  207. if err := os.RemoveAll(filepath.Join(c.DataDir, "log")); err != nil {
  208. return err
  209. }
  210. if err := os.RemoveAll(filepath.Join(c.DataDir, "conf")); err != nil {
  211. return err
  212. }
  213. if err := os.RemoveAll(filepath.Join(c.DataDir, "snapshot")); err != nil {
  214. return err
  215. }
  216. return nil
  217. }
  218. // Reads the info file from the file system or initializes it based on the config.
  219. func (c *Config) Info() (*Info, error) {
  220. info := &Info{}
  221. path := filepath.Join(c.DataDir, "info")
  222. // Open info file and read it out.
  223. f, err := os.Open(path)
  224. if err != nil && !os.IsNotExist(err) {
  225. return nil, err
  226. } else if f != nil {
  227. defer f.Close()
  228. if err := json.NewDecoder(f).Decode(&info); err != nil {
  229. return nil, err
  230. }
  231. return info, nil
  232. }
  233. // If the file doesn't exist then initialize it.
  234. info.Name = strings.TrimSpace(c.Name)
  235. info.EtcdURL = c.AdvertisedUrl
  236. info.EtcdListenHost = c.ListenHost
  237. info.RaftURL = c.Peer.AdvertisedUrl
  238. info.RaftListenHost = c.Peer.ListenHost
  239. info.WebURL = c.WebURL
  240. info.EtcdTLS = c.TLSInfo()
  241. info.RaftTLS = c.PeerTLSInfo()
  242. // Write to file.
  243. f, err = os.Create(path)
  244. if err != nil {
  245. return nil, err
  246. }
  247. defer f.Close()
  248. if err := json.NewEncoder(f).Encode(info); err != nil {
  249. return nil, err
  250. }
  251. return info, nil
  252. }
  253. // Sanitize cleans the input fields.
  254. func (c *Config) Sanitize() error {
  255. tlsConfig, err := c.TLSConfig()
  256. if err != nil {
  257. return err
  258. }
  259. peerTlsConfig, err := c.PeerTLSConfig()
  260. if err != nil {
  261. return err
  262. }
  263. // Sanitize the URLs first.
  264. if c.AdvertisedUrl, err = sanitizeURL(c.AdvertisedUrl, tlsConfig.Scheme); err != nil {
  265. return fmt.Errorf("Advertised URL: %s", err)
  266. }
  267. if c.ListenHost, err = sanitizeListenHost(c.ListenHost, c.AdvertisedUrl); err != nil {
  268. return fmt.Errorf("Listen Host: %s", err)
  269. }
  270. if c.WebURL, err = sanitizeURL(c.WebURL, "http"); err != nil {
  271. return fmt.Errorf("Web URL: %s", err)
  272. }
  273. if c.Peer.AdvertisedUrl, err = sanitizeURL(c.Peer.AdvertisedUrl, peerTlsConfig.Scheme); err != nil {
  274. return fmt.Errorf("Peer Advertised URL: %s", err)
  275. }
  276. if c.Peer.ListenHost, err = sanitizeListenHost(c.Peer.ListenHost, c.Peer.AdvertisedUrl); err != nil {
  277. return fmt.Errorf("Peer Listen Host: %s", err)
  278. }
  279. return nil
  280. }
  281. // TLSInfo retrieves a TLSInfo object for the client server.
  282. func (c *Config) TLSInfo() TLSInfo {
  283. return TLSInfo{
  284. CAFile: c.CAFile,
  285. CertFile: c.CertFile,
  286. KeyFile: c.KeyFile,
  287. }
  288. }
  289. // ClientTLSConfig generates the TLS configuration for the client server.
  290. func (c *Config) TLSConfig() (TLSConfig, error) {
  291. return c.TLSInfo().Config()
  292. }
  293. // PeerTLSInfo retrieves a TLSInfo object for the peer server.
  294. func (c *Config) PeerTLSInfo() TLSInfo {
  295. return TLSInfo{
  296. CAFile: c.Peer.CAFile,
  297. CertFile: c.Peer.CertFile,
  298. KeyFile: c.Peer.KeyFile,
  299. }
  300. }
  301. // PeerTLSConfig generates the TLS configuration for the peer server.
  302. func (c *Config) PeerTLSConfig() (TLSConfig, error) {
  303. return c.PeerTLSInfo().Config()
  304. }
  305. // sanitizeURL will cleanup a host string in the format hostname:port and
  306. // attach a schema.
  307. func sanitizeURL(host string, defaultScheme string) (string, error) {
  308. // Blank URLs are fine input, just return it
  309. if len(host) == 0 {
  310. return host, nil
  311. }
  312. p, err := url.Parse(host)
  313. if err != nil {
  314. return "", err
  315. }
  316. // Make sure the host is in Host:Port format
  317. _, _, err = net.SplitHostPort(host)
  318. if err != nil {
  319. return "", err
  320. }
  321. p = &url.URL{Host: host, Scheme: defaultScheme}
  322. return p.String(), nil
  323. }
  324. // sanitizeListenHost cleans up the ListenHost parameter and appends a port
  325. // if necessary based on the advertised port.
  326. func sanitizeListenHost(listen string, advertised string) (string, error) {
  327. aurl, err := url.Parse(advertised)
  328. if err != nil {
  329. return "", err
  330. }
  331. ahost, aport, err := net.SplitHostPort(aurl.Host)
  332. if err != nil {
  333. return "", err
  334. }
  335. // If the listen host isn't set use the advertised host
  336. if listen == "" {
  337. listen = ahost
  338. }
  339. return net.JoinHostPort(listen, aport), nil
  340. }