etcd.go 9.5 KB

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