etcd.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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/filepath"
  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. InitialElectionTickAdvance: cfg.InitialElectionTickAdvance,
  106. AutoCompactionRetention: cfg.AutoCompactionRetention,
  107. QuotaBackendBytes: cfg.QuotaBackendBytes,
  108. StrictReconfigCheck: cfg.StrictReconfigCheck,
  109. ClientCertAuthEnabled: cfg.ClientTLSInfo.ClientCertAuth,
  110. }
  111. if e.Server, err = etcdserver.NewServer(srvcfg); err != nil {
  112. return
  113. }
  114. // buffer channel so goroutines on closed connections won't wait forever
  115. e.errc = make(chan error, len(e.Peers)+len(e.Clients)+2*len(e.sctxs))
  116. e.Server.Start()
  117. if err = e.serve(); err != nil {
  118. return
  119. }
  120. return
  121. }
  122. // Config returns the current configuration.
  123. func (e *Etcd) Config() Config {
  124. return e.cfg
  125. }
  126. func (e *Etcd) Close() {
  127. for _, sctx := range e.sctxs {
  128. sctx.cancel()
  129. }
  130. for i := range e.Peers {
  131. if e.Peers[i] != nil {
  132. e.Peers[i].Close()
  133. }
  134. }
  135. for i := range e.Clients {
  136. if e.Clients[i] != nil {
  137. e.Clients[i].Close()
  138. }
  139. }
  140. if e.Server != nil {
  141. e.Server.Stop()
  142. }
  143. }
  144. func (e *Etcd) Err() <-chan error { return e.errc }
  145. func startPeerListeners(cfg *Config) (plns []net.Listener, err error) {
  146. if cfg.PeerAutoTLS && cfg.PeerTLSInfo.Empty() {
  147. phosts := make([]string, len(cfg.LPUrls))
  148. for i, u := range cfg.LPUrls {
  149. phosts[i] = u.Host
  150. }
  151. cfg.PeerTLSInfo, err = transport.SelfCert(filepath.Join(cfg.Dir, "fixtures", "peer"), phosts)
  152. if err != nil {
  153. plog.Fatalf("could not get certs (%v)", err)
  154. }
  155. } else if cfg.PeerAutoTLS {
  156. plog.Warningf("ignoring peer auto TLS since certs given")
  157. }
  158. if !cfg.PeerTLSInfo.Empty() {
  159. plog.Infof("peerTLS: %s", cfg.PeerTLSInfo)
  160. }
  161. plns = make([]net.Listener, len(cfg.LPUrls))
  162. defer func() {
  163. if err == nil {
  164. return
  165. }
  166. for i := range plns {
  167. if plns[i] == nil {
  168. continue
  169. }
  170. plns[i].Close()
  171. plog.Info("stopping listening for peers on ", cfg.LPUrls[i].String())
  172. }
  173. }()
  174. for i, u := range cfg.LPUrls {
  175. var tlscfg *tls.Config
  176. if u.Scheme == "http" {
  177. if !cfg.PeerTLSInfo.Empty() {
  178. plog.Warningf("The scheme of peer url %s is HTTP while peer key/cert files are presented. Ignored peer key/cert files.", u.String())
  179. }
  180. if cfg.PeerTLSInfo.ClientCertAuth {
  181. 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())
  182. }
  183. }
  184. if !cfg.PeerTLSInfo.Empty() {
  185. if tlscfg, err = cfg.PeerTLSInfo.ServerConfig(); err != nil {
  186. return nil, err
  187. }
  188. }
  189. if plns[i], err = rafthttp.NewListener(u, tlscfg); err != nil {
  190. return nil, err
  191. }
  192. plog.Info("listening for peers on ", u.String())
  193. }
  194. return plns, nil
  195. }
  196. func startClientListeners(cfg *Config) (sctxs map[string]*serveCtx, err error) {
  197. if cfg.ClientAutoTLS && cfg.ClientTLSInfo.Empty() {
  198. chosts := make([]string, len(cfg.LCUrls))
  199. for i, u := range cfg.LCUrls {
  200. chosts[i] = u.Host
  201. }
  202. cfg.ClientTLSInfo, err = transport.SelfCert(filepath.Join(cfg.Dir, "fixtures", "client"), chosts)
  203. if err != nil {
  204. plog.Fatalf("could not get certs (%v)", err)
  205. }
  206. } else if cfg.ClientAutoTLS {
  207. plog.Warningf("ignoring client auto TLS since certs given")
  208. }
  209. if cfg.EnablePprof {
  210. plog.Infof("pprof is enabled under %s", pprofPrefix)
  211. }
  212. sctxs = make(map[string]*serveCtx)
  213. for _, u := range cfg.LCUrls {
  214. sctx := newServeCtx()
  215. if u.Scheme == "http" || u.Scheme == "unix" {
  216. if !cfg.ClientTLSInfo.Empty() {
  217. plog.Warningf("The scheme of client url %s is HTTP while peer key/cert files are presented. Ignored key/cert files.", u.String())
  218. }
  219. if cfg.ClientTLSInfo.ClientCertAuth {
  220. 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())
  221. }
  222. }
  223. if (u.Scheme == "https" || u.Scheme == "unixs") && cfg.ClientTLSInfo.Empty() {
  224. return nil, fmt.Errorf("TLS key/cert (--cert-file, --key-file) must be provided for client url %s with HTTPs scheme", u.String())
  225. }
  226. proto := "tcp"
  227. if u.Scheme == "unix" || u.Scheme == "unixs" {
  228. proto = "unix"
  229. }
  230. sctx.secure = u.Scheme == "https" || u.Scheme == "unixs"
  231. sctx.insecure = !sctx.secure
  232. if oldctx := sctxs[u.Host]; oldctx != nil {
  233. oldctx.secure = oldctx.secure || sctx.secure
  234. oldctx.insecure = oldctx.insecure || sctx.insecure
  235. continue
  236. }
  237. if sctx.l, err = net.Listen(proto, u.Host); err != nil {
  238. return nil, err
  239. }
  240. if fdLimit, fderr := runtimeutil.FDLimit(); fderr == nil {
  241. if fdLimit <= reservedInternalFDNum {
  242. 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)
  243. }
  244. sctx.l = transport.LimitListener(sctx.l, int(fdLimit-reservedInternalFDNum))
  245. }
  246. if proto == "tcp" {
  247. if sctx.l, err = transport.NewKeepAliveListener(sctx.l, "tcp", nil); err != nil {
  248. return nil, err
  249. }
  250. }
  251. plog.Info("listening for client requests on ", u.Host)
  252. defer func() {
  253. if err != nil {
  254. sctx.l.Close()
  255. plog.Info("stopping listening for client requests on ", u.Host)
  256. }
  257. }()
  258. for k := range cfg.UserHandlers {
  259. sctx.userHandlers[k] = cfg.UserHandlers[k]
  260. }
  261. if cfg.EnablePprof {
  262. sctx.registerPprof()
  263. }
  264. sctxs[u.Host] = sctx
  265. }
  266. return sctxs, nil
  267. }
  268. func (e *Etcd) serve() (err error) {
  269. var ctlscfg *tls.Config
  270. if !e.cfg.ClientTLSInfo.Empty() {
  271. plog.Infof("ClientTLS: %s", e.cfg.ClientTLSInfo)
  272. if ctlscfg, err = e.cfg.ClientTLSInfo.ServerConfig(); err != nil {
  273. return err
  274. }
  275. }
  276. if e.cfg.CorsInfo.String() != "" {
  277. plog.Infof("cors = %s", e.cfg.CorsInfo)
  278. }
  279. // Start the peer server in a goroutine
  280. ph := v2http.NewPeerHandler(e.Server)
  281. for _, l := range e.Peers {
  282. go func(l net.Listener) {
  283. e.errc <- servePeerHTTP(l, ph)
  284. }(l)
  285. }
  286. // Start a client server goroutine for each listen address
  287. ch := http.Handler(&cors.CORSHandler{
  288. Handler: v2http.NewClientHandler(e.Server, e.Server.Cfg.ReqTimeout()),
  289. Info: e.cfg.CorsInfo,
  290. })
  291. for _, sctx := range e.sctxs {
  292. // read timeout does not work with http close notify
  293. // TODO: https://github.com/golang/go/issues/9524
  294. go func(s *serveCtx) {
  295. e.errc <- s.serve(e.Server, ctlscfg, ch, e.errc)
  296. }(sctx)
  297. }
  298. return nil
  299. }