etcd.go 10 KB

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