etcd.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. // Copyright 2016 The etcd Authors
  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 embed
  15. import (
  16. "crypto/tls"
  17. "fmt"
  18. "net"
  19. "net/http"
  20. "path"
  21. "github.com/coreos/etcd/etcdserver"
  22. "github.com/coreos/etcd/etcdserver/api/v2http"
  23. "github.com/coreos/etcd/pkg/cors"
  24. runtimeutil "github.com/coreos/etcd/pkg/runtime"
  25. "github.com/coreos/etcd/pkg/transport"
  26. "github.com/coreos/etcd/rafthttp"
  27. "github.com/coreos/pkg/capnslog"
  28. )
  29. var plog = capnslog.NewPackageLogger("github.com/coreos/etcd", "embed")
  30. const (
  31. // internal fd usage includes disk usage and transport usage.
  32. // To read/write snapshot, snap pkg needs 1. In normal case, wal pkg needs
  33. // at most 2 to read/lock/write WALs. One case that it needs to 2 is to
  34. // read all logs after some snapshot index, which locates at the end of
  35. // the second last and the head of the last. For purging, it needs to read
  36. // directory, so it needs 1. For fd monitor, it needs 1.
  37. // For transport, rafthttp builds two long-polling connections and at most
  38. // four temporary connections with each member. There are at most 9 members
  39. // in a cluster, so it should reserve 96.
  40. // For the safety, we set the total reserved number to 150.
  41. reservedInternalFDNum = 150
  42. )
  43. // Etcd contains a running etcd server and its listeners.
  44. type Etcd struct {
  45. Peers []net.Listener
  46. Clients []net.Listener
  47. Server *etcdserver.EtcdServer
  48. cfg Config
  49. errc chan error
  50. sctxs map[string]*serveCtx
  51. }
  52. // StartEtcd launches the etcd server and HTTP handlers for client/server communication.
  53. func StartEtcd(inCfg *Config) (e *Etcd, err error) {
  54. if err = inCfg.Validate(); err != nil {
  55. return nil, err
  56. }
  57. e = &Etcd{cfg: *inCfg}
  58. cfg := &e.cfg
  59. defer func() {
  60. if err != nil {
  61. e.Close()
  62. e = nil
  63. }
  64. }()
  65. if e.Peers, err = startPeerListeners(cfg); err != nil {
  66. return
  67. }
  68. if e.sctxs, err = startClientListeners(cfg); err != nil {
  69. return
  70. }
  71. for _, sctx := range e.sctxs {
  72. e.Clients = append(e.Clients, sctx.l)
  73. }
  74. urlsmap, token, uerr := cfg.PeerURLsMapAndToken("etcd")
  75. if uerr != nil {
  76. err = fmt.Errorf("error setting up initial cluster: %v", uerr)
  77. return
  78. }
  79. srvcfg := &etcdserver.ServerConfig{
  80. Name: cfg.Name,
  81. ClientURLs: cfg.ACUrls,
  82. PeerURLs: cfg.APUrls,
  83. DataDir: cfg.Dir,
  84. DedicatedWALDir: cfg.WalDir,
  85. SnapCount: cfg.SnapCount,
  86. MaxSnapFiles: cfg.MaxSnapFiles,
  87. MaxWALFiles: cfg.MaxWalFiles,
  88. InitialPeerURLsMap: urlsmap,
  89. InitialClusterToken: token,
  90. DiscoveryURL: cfg.Durl,
  91. DiscoveryProxy: cfg.Dproxy,
  92. NewCluster: cfg.IsNewCluster(),
  93. ForceNewCluster: cfg.ForceNewCluster,
  94. PeerTLSInfo: cfg.PeerTLSInfo,
  95. TickMs: cfg.TickMs,
  96. ElectionTicks: cfg.ElectionTicks(),
  97. AutoCompactionRetention: cfg.AutoCompactionRetention,
  98. QuotaBackendBytes: cfg.QuotaBackendBytes,
  99. StrictReconfigCheck: cfg.StrictReconfigCheck,
  100. EnablePprof: cfg.EnablePprof,
  101. }
  102. if e.Server, err = etcdserver.NewServer(srvcfg); err != nil {
  103. return
  104. }
  105. // buffer channel so goroutines on closed connections won't wait forever
  106. e.errc = make(chan error, len(e.Peers)+len(e.Clients)+2*len(e.sctxs))
  107. e.Server.Start()
  108. e.serve()
  109. <-e.Server.ReadyNotify()
  110. return
  111. }
  112. func (e *Etcd) Close() {
  113. for _, sctx := range e.sctxs {
  114. sctx.cancel()
  115. }
  116. for i := range e.Peers {
  117. if e.Peers[i] != nil {
  118. e.Peers[i].Close()
  119. }
  120. }
  121. for i := range e.Clients {
  122. if e.Clients[i] != nil {
  123. e.Clients[i].Close()
  124. }
  125. }
  126. if e.Server != nil {
  127. e.Server.Stop()
  128. }
  129. }
  130. func (e *Etcd) Err() <-chan error { return e.errc }
  131. func startPeerListeners(cfg *Config) (plns []net.Listener, err error) {
  132. if cfg.PeerAutoTLS && cfg.PeerTLSInfo.Empty() {
  133. phosts := make([]string, len(cfg.LPUrls))
  134. for i, u := range cfg.LPUrls {
  135. phosts[i] = u.Host
  136. }
  137. cfg.PeerTLSInfo, err = transport.SelfCert(path.Join(cfg.Dir, "fixtures/peer"), phosts)
  138. if err != nil {
  139. plog.Fatalf("could not get certs (%v)", err)
  140. }
  141. } else if cfg.PeerAutoTLS {
  142. plog.Warningf("ignoring peer auto TLS since certs given")
  143. }
  144. if !cfg.PeerTLSInfo.Empty() {
  145. plog.Infof("peerTLS: %s", cfg.PeerTLSInfo)
  146. }
  147. plns = make([]net.Listener, len(cfg.LPUrls))
  148. defer func() {
  149. if err == nil {
  150. return
  151. }
  152. for i := range plns {
  153. if plns[i] == nil {
  154. continue
  155. }
  156. plns[i].Close()
  157. plog.Info("stopping listening for peers on ", cfg.LPUrls[i].String())
  158. }
  159. }()
  160. for i, u := range cfg.LPUrls {
  161. var tlscfg *tls.Config
  162. if u.Scheme == "http" {
  163. if !cfg.PeerTLSInfo.Empty() {
  164. plog.Warningf("The scheme of peer url %s is HTTP while peer key/cert files are presented. Ignored peer key/cert files.", u.String())
  165. }
  166. if cfg.PeerTLSInfo.ClientCertAuth {
  167. plog.Warningf("The scheme of peer url %s is HTTP while client cert auth (--peer-client-cert-auth) is enabled. Ignored client cert auth for this url.", u.String())
  168. }
  169. }
  170. if !cfg.PeerTLSInfo.Empty() {
  171. if tlscfg, err = cfg.PeerTLSInfo.ServerConfig(); err != nil {
  172. return nil, err
  173. }
  174. }
  175. if plns[i], err = rafthttp.NewListener(u, tlscfg); err != nil {
  176. return nil, err
  177. }
  178. plog.Info("listening for peers on ", u.String())
  179. }
  180. return plns, nil
  181. }
  182. func startClientListeners(cfg *Config) (sctxs map[string]*serveCtx, err error) {
  183. if cfg.ClientAutoTLS && cfg.ClientTLSInfo.Empty() {
  184. chosts := make([]string, len(cfg.LCUrls))
  185. for i, u := range cfg.LCUrls {
  186. chosts[i] = u.Host
  187. }
  188. cfg.ClientTLSInfo, err = transport.SelfCert(path.Join(cfg.Dir, "fixtures/client"), chosts)
  189. if err != nil {
  190. plog.Fatalf("could not get certs (%v)", err)
  191. }
  192. } else if cfg.ClientAutoTLS {
  193. plog.Warningf("ignoring client auto TLS since certs given")
  194. }
  195. sctxs = make(map[string]*serveCtx)
  196. for _, u := range cfg.LCUrls {
  197. sctx := newServeCtx()
  198. if u.Scheme == "http" {
  199. if !cfg.ClientTLSInfo.Empty() {
  200. plog.Warningf("The scheme of client url %s is HTTP while peer key/cert files are presented. Ignored key/cert files.", u.String())
  201. }
  202. if cfg.ClientTLSInfo.ClientCertAuth {
  203. plog.Warningf("The scheme of client url %s is HTTP while client cert auth (--client-cert-auth) is enabled. Ignored client cert auth for this url.", u.String())
  204. }
  205. }
  206. if u.Scheme == "https" && cfg.ClientTLSInfo.Empty() {
  207. return nil, fmt.Errorf("TLS key/cert (--cert-file, --key-file) must be provided for client url %s with HTTPs scheme", u.String())
  208. }
  209. sctx.secure = u.Scheme == "https"
  210. sctx.insecure = !sctx.secure
  211. if oldctx := sctxs[u.Host]; oldctx != nil {
  212. oldctx.secure = oldctx.secure || sctx.secure
  213. oldctx.insecure = oldctx.insecure || sctx.insecure
  214. continue
  215. }
  216. if sctx.l, err = net.Listen("tcp", u.Host); err != nil {
  217. return nil, err
  218. }
  219. if fdLimit, fderr := runtimeutil.FDLimit(); fderr == nil {
  220. if fdLimit <= reservedInternalFDNum {
  221. plog.Fatalf("file descriptor limit[%d] of etcd process is too low, and should be set higher than %d to ensure internal usage", fdLimit, reservedInternalFDNum)
  222. }
  223. sctx.l = transport.LimitListener(sctx.l, int(fdLimit-reservedInternalFDNum))
  224. }
  225. if sctx.l, err = transport.NewKeepAliveListener(sctx.l, "tcp", nil); err != nil {
  226. return nil, err
  227. }
  228. plog.Info("listening for client requests on ", u.Host)
  229. defer func() {
  230. if err != nil {
  231. sctx.l.Close()
  232. plog.Info("stopping listening for client requests on ", u.Host)
  233. }
  234. }()
  235. sctxs[u.Host] = sctx
  236. }
  237. return sctxs, nil
  238. }
  239. func (e *Etcd) serve() (err error) {
  240. var ctlscfg *tls.Config
  241. if !e.cfg.ClientTLSInfo.Empty() {
  242. plog.Infof("ClientTLS: %s", e.cfg.ClientTLSInfo)
  243. if ctlscfg, err = e.cfg.ClientTLSInfo.ServerConfig(); err != nil {
  244. return err
  245. }
  246. }
  247. if e.cfg.CorsInfo.String() != "" {
  248. plog.Infof("cors = %s", e.cfg.CorsInfo)
  249. }
  250. // Start the peer server in a goroutine
  251. ph := v2http.NewPeerHandler(e.Server)
  252. for _, l := range e.Peers {
  253. go func(l net.Listener) {
  254. e.errc <- servePeerHTTP(l, ph)
  255. }(l)
  256. }
  257. // Start a client server goroutine for each listen address
  258. ch := http.Handler(&cors.CORSHandler{
  259. Handler: v2http.NewClientHandler(e.Server, e.Server.Cfg.ReqTimeout()),
  260. Info: e.cfg.CorsInfo,
  261. })
  262. for _, sctx := range e.sctxs {
  263. // read timeout does not work with http close notify
  264. // TODO: https://github.com/golang/go/issues/9524
  265. go func(s *serveCtx) {
  266. e.errc <- s.serve(e.Server, ctlscfg, ch, e.errc)
  267. }(sctx)
  268. }
  269. return nil
  270. }