config.go 12 KB

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