main.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. /*
  2. Copyright 2014 CoreOS, Inc.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package main
  14. import (
  15. "flag"
  16. "fmt"
  17. "log"
  18. "net/http"
  19. "os"
  20. "strings"
  21. "github.com/coreos/etcd/etcdserver"
  22. "github.com/coreos/etcd/etcdserver/etcdhttp"
  23. "github.com/coreos/etcd/pkg"
  24. flagtypes "github.com/coreos/etcd/pkg/flags"
  25. "github.com/coreos/etcd/pkg/transport"
  26. "github.com/coreos/etcd/proxy"
  27. )
  28. const (
  29. // the owner can make/remove files inside the directory
  30. privateDirMode = 0700
  31. version = "0.5.0-alpha"
  32. )
  33. var (
  34. name = flag.String("name", "default", "Unique human-readable name for this node")
  35. dir = flag.String("data-dir", "", "Path to the data directory")
  36. durl = flag.String("discovery", "", "Discovery service used to bootstrap the cluster")
  37. snapCount = flag.Uint64("snapshot-count", etcdserver.DefaultSnapCount, "Number of committed transactions to trigger a snapshot")
  38. printVersion = flag.Bool("version", false, "Print the version and exit")
  39. cluster = &etcdserver.Cluster{}
  40. clusterState = new(etcdserver.ClusterState)
  41. cors = &pkg.CORSInfo{}
  42. proxyFlag = new(flagtypes.Proxy)
  43. clientTLSInfo = transport.TLSInfo{}
  44. peerTLSInfo = transport.TLSInfo{}
  45. ignored = []string{
  46. "cluster-active-size",
  47. "cluster-remove-delay",
  48. "cluster-sync-interval",
  49. "config",
  50. "force",
  51. "max-result-buffer",
  52. "max-retry-attempts",
  53. "peer-heartbeat-interval",
  54. "peer-election-timeout",
  55. "retry-interval",
  56. "snapshot",
  57. "v",
  58. "vv",
  59. }
  60. )
  61. func init() {
  62. flag.Var(cluster, "initial-cluster", "Initial cluster configuration for bootstrapping")
  63. if err := cluster.Set("default=http://localhost:2380,default=http://localhost:7001"); err != nil {
  64. // Should never happen
  65. log.Panic(err)
  66. }
  67. flag.Var(clusterState, "initial-cluster-state", "Initial cluster configuration for bootstrapping")
  68. clusterState.Set(etcdserver.ClusterStateValueNew)
  69. flag.Var(flagtypes.NewURLsValue("http://localhost:2380,http://localhost:7001"), "advertise-peer-urls", "List of this member's peer URLs to advertise to the rest of the cluster")
  70. flag.Var(flagtypes.NewURLsValue("http://localhost:2379,http://localhost:4001"), "advertise-client-urls", "List of this member's client URLs to advertise to the rest of the cluster")
  71. flag.Var(flagtypes.NewURLsValue("http://localhost:2380,http://localhost:7001"), "listen-peer-urls", "List of URLs to listen on for peer traffic")
  72. flag.Var(flagtypes.NewURLsValue("http://localhost:2379,http://localhost:4001"), "listen-client-urls", "List of URLs to listen on for client traffic")
  73. flag.Var(cors, "cors", "Comma-separated white list of origins for CORS (cross-origin resource sharing).")
  74. flag.Var(proxyFlag, "proxy", fmt.Sprintf("Valid values include %s", strings.Join(flagtypes.ProxyValues, ", ")))
  75. proxyFlag.Set(flagtypes.ProxyValueOff)
  76. flag.StringVar(&clientTLSInfo.CAFile, "ca-file", "", "Path to the client server TLS CA file.")
  77. flag.StringVar(&clientTLSInfo.CertFile, "cert-file", "", "Path to the client server TLS cert file.")
  78. flag.StringVar(&clientTLSInfo.KeyFile, "key-file", "", "Path to the client server TLS key file.")
  79. flag.StringVar(&peerTLSInfo.CAFile, "peer-ca-file", "", "Path to the peer server TLS CA file.")
  80. flag.StringVar(&peerTLSInfo.CertFile, "peer-cert-file", "", "Path to the peer server TLS cert file.")
  81. flag.StringVar(&peerTLSInfo.KeyFile, "peer-key-file", "", "Path to the peer server TLS key file.")
  82. // backwards-compatibility with v0.4.6
  83. flag.Var(&flagtypes.IPAddressPort{}, "addr", "DEPRECATED: Use -advertise-client-urls instead.")
  84. flag.Var(&flagtypes.IPAddressPort{}, "bind-addr", "DEPRECATED: Use -listen-client-urls instead.")
  85. flag.Var(&flagtypes.IPAddressPort{}, "peer-addr", "DEPRECATED: Use -advertise-peer-urls instead.")
  86. flag.Var(&flagtypes.IPAddressPort{}, "peer-bind-addr", "DEPRECATED: Use -listen-peer-urls instead.")
  87. for _, f := range ignored {
  88. flag.Var(&pkg.IgnoredFlag{f}, f, "")
  89. }
  90. flag.Var(&pkg.DeprecatedFlag{"peers"}, "peers", "DEPRECATED: Use -initial-cluster instead")
  91. flag.Var(&pkg.DeprecatedFlag{"peers-file"}, "peers-file", "DEPRECATED: Use -initial-cluster instead")
  92. }
  93. func main() {
  94. flag.Usage = pkg.UsageWithIgnoredFlagsFunc(flag.CommandLine, ignored)
  95. flag.Parse()
  96. if *printVersion {
  97. fmt.Println("etcd version", version)
  98. os.Exit(0)
  99. }
  100. pkg.SetFlagsFromEnv(flag.CommandLine)
  101. if err := setClusterForDiscovery(); err != nil {
  102. log.Fatalf("etcd: %v", err)
  103. }
  104. if string(*proxyFlag) == flagtypes.ProxyValueOff {
  105. startEtcd()
  106. } else {
  107. startProxy()
  108. }
  109. // Block indefinitely
  110. <-make(chan struct{})
  111. }
  112. // startEtcd launches the etcd server and HTTP handlers for client/server communication.
  113. func startEtcd() {
  114. if *dir == "" {
  115. *dir = fmt.Sprintf("%v_etcd_data", *name)
  116. log.Printf("etcd: no data-dir provided, using default data-dir ./%s", *dir)
  117. }
  118. if err := os.MkdirAll(*dir, privateDirMode); err != nil {
  119. log.Fatalf("etcd: cannot create data directory: %v", err)
  120. }
  121. pt, err := transport.NewTransport(peerTLSInfo)
  122. if err != nil {
  123. log.Fatal(err)
  124. }
  125. acurls, err := pkg.URLsFromFlags(flag.CommandLine, "advertise-client-urls", "addr", clientTLSInfo)
  126. if err != nil {
  127. log.Fatal(err.Error())
  128. }
  129. cfg := &etcdserver.ServerConfig{
  130. Name: *name,
  131. ClientURLs: acurls,
  132. DataDir: *dir,
  133. SnapCount: *snapCount,
  134. Cluster: cluster,
  135. DiscoveryURL: *durl,
  136. ClusterState: *clusterState,
  137. Transport: pt,
  138. }
  139. s := etcdserver.NewServer(cfg)
  140. s.Start()
  141. ch := &pkg.CORSHandler{
  142. Handler: etcdhttp.NewClientHandler(s),
  143. Info: cors,
  144. }
  145. ph := etcdhttp.NewPeerHandler(s)
  146. lpurls, err := pkg.URLsFromFlags(flag.CommandLine, "listen-peer-urls", "peer-bind-addr", peerTLSInfo)
  147. if err != nil {
  148. log.Fatal(err.Error())
  149. }
  150. for _, u := range lpurls {
  151. l, err := transport.NewListener(u.Host, peerTLSInfo)
  152. if err != nil {
  153. log.Fatal(err)
  154. }
  155. // Start the peer server in a goroutine
  156. urlStr := u.String()
  157. go func() {
  158. log.Print("Listening for peers on ", urlStr)
  159. log.Fatal(http.Serve(l, ph))
  160. }()
  161. }
  162. lcurls, err := pkg.URLsFromFlags(flag.CommandLine, "listen-client-urls", "bind-addr", clientTLSInfo)
  163. if err != nil {
  164. log.Fatal(err.Error())
  165. }
  166. // Start a client server goroutine for each listen address
  167. for _, u := range lcurls {
  168. l, err := transport.NewListener(u.Host, clientTLSInfo)
  169. if err != nil {
  170. log.Fatal(err)
  171. }
  172. urlStr := u.String()
  173. go func() {
  174. log.Print("Listening for client requests on ", urlStr)
  175. log.Fatal(http.Serve(l, ch))
  176. }()
  177. }
  178. }
  179. // startProxy launches an HTTP proxy for client communication which proxies to other etcd nodes.
  180. func startProxy() {
  181. pt, err := transport.NewTransport(clientTLSInfo)
  182. if err != nil {
  183. log.Fatal(err)
  184. }
  185. ph, err := proxy.NewHandler(pt, (*cluster).PeerURLs())
  186. if err != nil {
  187. log.Fatal(err)
  188. }
  189. ph = &pkg.CORSHandler{
  190. Handler: ph,
  191. Info: cors,
  192. }
  193. if string(*proxyFlag) == flagtypes.ProxyValueReadonly {
  194. ph = proxy.NewReadonlyHandler(ph)
  195. }
  196. lcurls, err := pkg.URLsFromFlags(flag.CommandLine, "listen-client-urls", "bind-addr", clientTLSInfo)
  197. if err != nil {
  198. log.Fatal(err.Error())
  199. }
  200. // Start a proxy server goroutine for each listen address
  201. for _, u := range lcurls {
  202. l, err := transport.NewListener(u.Host, clientTLSInfo)
  203. if err != nil {
  204. log.Fatal(err)
  205. }
  206. host := u.Host
  207. go func() {
  208. log.Print("Listening for client requests on ", host)
  209. log.Fatal(http.Serve(l, ph))
  210. }()
  211. }
  212. }
  213. // setClusterForDiscovery sets cluster to a temporary value if you are using
  214. // the discovery.
  215. func setClusterForDiscovery() error {
  216. set := make(map[string]bool)
  217. flag.Visit(func(f *flag.Flag) {
  218. set[f.Name] = true
  219. })
  220. if set["discovery"] && set["initial-cluster"] {
  221. return fmt.Errorf("both discovery and initial-cluster are set")
  222. }
  223. if set["discovery"] {
  224. apurls, err := pkg.URLsFromFlags(flag.CommandLine, "advertise-peer-urls", "peer-addr", peerTLSInfo)
  225. if err != nil {
  226. return err
  227. }
  228. addrs := make([]string, len(apurls))
  229. for i := range apurls {
  230. addrs[i] = fmt.Sprintf("%s=%s", *name, apurls[i].String())
  231. }
  232. if err := cluster.Set(strings.Join(addrs, ",")); err != nil {
  233. return err
  234. }
  235. }
  236. return nil
  237. }