etcd.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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. "context"
  17. "crypto/tls"
  18. "fmt"
  19. "io/ioutil"
  20. defaultLog "log"
  21. "net"
  22. "net/http"
  23. "net/url"
  24. "sync"
  25. "time"
  26. "github.com/coreos/etcd/etcdserver"
  27. "github.com/coreos/etcd/etcdserver/api/etcdhttp"
  28. "github.com/coreos/etcd/etcdserver/api/v2http"
  29. "github.com/coreos/etcd/etcdserver/api/v3rpc"
  30. "github.com/coreos/etcd/pkg/cors"
  31. "github.com/coreos/etcd/pkg/debugutil"
  32. runtimeutil "github.com/coreos/etcd/pkg/runtime"
  33. "github.com/coreos/etcd/pkg/transport"
  34. "github.com/coreos/etcd/pkg/types"
  35. "github.com/coreos/etcd/rafthttp"
  36. "github.com/coreos/pkg/capnslog"
  37. "github.com/soheilhy/cmux"
  38. "google.golang.org/grpc"
  39. )
  40. var plog = capnslog.NewPackageLogger("github.com/coreos/etcd", "embed")
  41. const (
  42. // internal fd usage includes disk usage and transport usage.
  43. // To read/write snapshot, snap pkg needs 1. In normal case, wal pkg needs
  44. // at most 2 to read/lock/write WALs. One case that it needs to 2 is to
  45. // read all logs after some snapshot index, which locates at the end of
  46. // the second last and the head of the last. For purging, it needs to read
  47. // directory, so it needs 1. For fd monitor, it needs 1.
  48. // For transport, rafthttp builds two long-polling connections and at most
  49. // four temporary connections with each member. There are at most 9 members
  50. // in a cluster, so it should reserve 96.
  51. // For the safety, we set the total reserved number to 150.
  52. reservedInternalFDNum = 150
  53. )
  54. // Etcd contains a running etcd server and its listeners.
  55. type Etcd struct {
  56. Peers []*peerListener
  57. Clients []net.Listener
  58. metricsListeners []net.Listener
  59. Server *etcdserver.EtcdServer
  60. cfg Config
  61. stopc chan struct{}
  62. errc chan error
  63. sctxs map[string]*serveCtx
  64. closeOnce sync.Once
  65. }
  66. type peerListener struct {
  67. net.Listener
  68. serve func() error
  69. close func(context.Context) error
  70. }
  71. // StartEtcd launches the etcd server and HTTP handlers for client/server communication.
  72. // The returned Etcd.Server is not guaranteed to have joined the cluster. Wait
  73. // on the Etcd.Server.ReadyNotify() channel to know when it completes and is ready for use.
  74. func StartEtcd(inCfg *Config) (e *Etcd, err error) {
  75. if err = inCfg.Validate(); err != nil {
  76. return nil, err
  77. }
  78. serving := false
  79. e = &Etcd{cfg: *inCfg, stopc: make(chan struct{})}
  80. cfg := &e.cfg
  81. defer func() {
  82. if e == nil || err == nil {
  83. return
  84. }
  85. if !serving {
  86. // errored before starting gRPC server for serveCtx.grpcServerC
  87. for _, sctx := range e.sctxs {
  88. close(sctx.grpcServerC)
  89. }
  90. }
  91. e.Close()
  92. e = nil
  93. }()
  94. if e.Peers, err = startPeerListeners(cfg); err != nil {
  95. return
  96. }
  97. if e.sctxs, err = startClientListeners(cfg); err != nil {
  98. return
  99. }
  100. for _, sctx := range e.sctxs {
  101. e.Clients = append(e.Clients, sctx.l)
  102. }
  103. var (
  104. urlsmap types.URLsMap
  105. token string
  106. )
  107. if !isMemberInitialized(cfg) {
  108. urlsmap, token, err = cfg.PeerURLsMapAndToken("etcd")
  109. if err != nil {
  110. return e, fmt.Errorf("error setting up initial cluster: %v", err)
  111. }
  112. }
  113. srvcfg := etcdserver.ServerConfig{
  114. Name: cfg.Name,
  115. ClientURLs: cfg.ACUrls,
  116. PeerURLs: cfg.APUrls,
  117. DataDir: cfg.Dir,
  118. DedicatedWALDir: cfg.WalDir,
  119. SnapCount: cfg.SnapCount,
  120. MaxSnapFiles: cfg.MaxSnapFiles,
  121. MaxWALFiles: cfg.MaxWalFiles,
  122. InitialPeerURLsMap: urlsmap,
  123. InitialClusterToken: token,
  124. DiscoveryURL: cfg.Durl,
  125. DiscoveryProxy: cfg.Dproxy,
  126. NewCluster: cfg.IsNewCluster(),
  127. ForceNewCluster: cfg.ForceNewCluster,
  128. PeerTLSInfo: cfg.PeerTLSInfo,
  129. TickMs: cfg.TickMs,
  130. ElectionTicks: cfg.ElectionTicks(),
  131. AutoCompactionRetention: cfg.AutoCompactionRetention,
  132. AutoCompactionMode: cfg.AutoCompactionMode,
  133. QuotaBackendBytes: cfg.QuotaBackendBytes,
  134. MaxTxnOps: cfg.MaxTxnOps,
  135. MaxRequestBytes: cfg.MaxRequestBytes,
  136. StrictReconfigCheck: cfg.StrictReconfigCheck,
  137. ClientCertAuthEnabled: cfg.ClientTLSInfo.ClientCertAuth,
  138. AuthToken: cfg.AuthToken,
  139. CorruptCheckTime: cfg.ExperimentalCorruptCheckTime,
  140. }
  141. if e.Server, err = etcdserver.NewServer(srvcfg); err != nil {
  142. return
  143. }
  144. // buffer channel so goroutines on closed connections won't wait forever
  145. e.errc = make(chan error, len(e.Peers)+len(e.Clients)+2*len(e.sctxs))
  146. e.Server.Start()
  147. // configure peer handlers after rafthttp.Transport started
  148. ph := etcdhttp.NewPeerHandler(e.Server)
  149. var peerTLScfg *tls.Config
  150. if !cfg.PeerTLSInfo.Empty() {
  151. if peerTLScfg, err = cfg.PeerTLSInfo.ServerConfig(); err != nil {
  152. return
  153. }
  154. }
  155. for _, p := range e.Peers {
  156. gs := v3rpc.Server(e.Server, peerTLScfg)
  157. m := cmux.New(p.Listener)
  158. go gs.Serve(m.Match(cmux.HTTP2()))
  159. srv := &http.Server{
  160. Handler: grpcHandlerFunc(gs, ph),
  161. ReadTimeout: 5 * time.Minute,
  162. ErrorLog: defaultLog.New(ioutil.Discard, "", 0), // do not log user error
  163. }
  164. go srv.Serve(m.Match(cmux.Any()))
  165. p.serve = func() error { return m.Serve() }
  166. p.close = func(ctx context.Context) error {
  167. // gracefully shutdown http.Server
  168. // close open listeners, idle connections
  169. // until context cancel or time-out
  170. e.stopGRPCServer(gs)
  171. return srv.Shutdown(ctx)
  172. }
  173. }
  174. if err = e.serve(); err != nil {
  175. return
  176. }
  177. serving = true
  178. return
  179. }
  180. // Config returns the current configuration.
  181. func (e *Etcd) Config() Config {
  182. return e.cfg
  183. }
  184. func (e *Etcd) Close() {
  185. e.closeOnce.Do(func() { close(e.stopc) })
  186. for _, sctx := range e.sctxs {
  187. for gs := range sctx.grpcServerC {
  188. e.stopGRPCServer(gs)
  189. }
  190. }
  191. for _, sctx := range e.sctxs {
  192. sctx.cancel()
  193. }
  194. for i := range e.Clients {
  195. if e.Clients[i] != nil {
  196. e.Clients[i].Close()
  197. }
  198. }
  199. for i := range e.metricsListeners {
  200. e.metricsListeners[i].Close()
  201. }
  202. // close rafthttp transports
  203. if e.Server != nil {
  204. e.Server.Stop()
  205. }
  206. // close all idle connections in peer handler (wait up to 1-second)
  207. for i := range e.Peers {
  208. if e.Peers[i] != nil && e.Peers[i].close != nil {
  209. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  210. e.Peers[i].close(ctx)
  211. cancel()
  212. }
  213. }
  214. }
  215. func (e *Etcd) stopGRPCServer(gs *grpc.Server) {
  216. timeout := 2 * time.Second
  217. if e.Server != nil {
  218. timeout = e.Server.Cfg.ReqTimeout()
  219. }
  220. ch := make(chan struct{})
  221. go func() {
  222. defer close(ch)
  223. // close listeners to stop accepting new connections,
  224. // will block on any existing transports
  225. gs.GracefulStop()
  226. }()
  227. // wait until all pending RPCs are finished
  228. select {
  229. case <-ch:
  230. case <-time.After(timeout):
  231. // took too long, manually close open transports
  232. // e.g. watch streams
  233. gs.Stop()
  234. // concurrent GracefulStop should be interrupted
  235. <-ch
  236. }
  237. }
  238. func (e *Etcd) Err() <-chan error { return e.errc }
  239. func startPeerListeners(cfg *Config) (peers []*peerListener, err error) {
  240. if err = cfg.PeerSelfCert(); err != nil {
  241. plog.Fatalf("could not get certs (%v)", err)
  242. }
  243. if !cfg.PeerTLSInfo.Empty() {
  244. plog.Infof("peerTLS: %s", cfg.PeerTLSInfo)
  245. }
  246. peers = make([]*peerListener, len(cfg.LPUrls))
  247. defer func() {
  248. if err == nil {
  249. return
  250. }
  251. for i := range peers {
  252. if peers[i] != nil && peers[i].close != nil {
  253. plog.Info("stopping listening for peers on ", cfg.LPUrls[i].String())
  254. peers[i].close(context.Background())
  255. }
  256. }
  257. }()
  258. for i, u := range cfg.LPUrls {
  259. if u.Scheme == "http" {
  260. if !cfg.PeerTLSInfo.Empty() {
  261. plog.Warningf("The scheme of peer url %s is HTTP while peer key/cert files are presented. Ignored peer key/cert files.", u.String())
  262. }
  263. if cfg.PeerTLSInfo.ClientCertAuth {
  264. 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())
  265. }
  266. }
  267. peers[i] = &peerListener{close: func(context.Context) error { return nil }}
  268. peers[i].Listener, err = rafthttp.NewListener(u, &cfg.PeerTLSInfo)
  269. if err != nil {
  270. return nil, err
  271. }
  272. // once serve, overwrite with 'http.Server.Shutdown'
  273. peers[i].close = func(context.Context) error {
  274. return peers[i].Listener.Close()
  275. }
  276. plog.Info("listening for peers on ", u.String())
  277. }
  278. return peers, nil
  279. }
  280. func startClientListeners(cfg *Config) (sctxs map[string]*serveCtx, err error) {
  281. if err = cfg.ClientSelfCert(); err != nil {
  282. plog.Fatalf("could not get certs (%v)", err)
  283. }
  284. if cfg.EnablePprof {
  285. plog.Infof("pprof is enabled under %s", debugutil.HTTPPrefixPProf)
  286. }
  287. sctxs = make(map[string]*serveCtx)
  288. for _, u := range cfg.LCUrls {
  289. sctx := newServeCtx()
  290. if u.Scheme == "http" || u.Scheme == "unix" {
  291. if !cfg.ClientTLSInfo.Empty() {
  292. plog.Warningf("The scheme of client url %s is HTTP while peer key/cert files are presented. Ignored key/cert files.", u.String())
  293. }
  294. if cfg.ClientTLSInfo.ClientCertAuth {
  295. 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())
  296. }
  297. }
  298. if (u.Scheme == "https" || u.Scheme == "unixs") && cfg.ClientTLSInfo.Empty() {
  299. return nil, fmt.Errorf("TLS key/cert (--cert-file, --key-file) must be provided for client url %s with HTTPs scheme", u.String())
  300. }
  301. proto := "tcp"
  302. addr := u.Host
  303. if u.Scheme == "unix" || u.Scheme == "unixs" {
  304. proto = "unix"
  305. addr = u.Host + u.Path
  306. }
  307. sctx.secure = u.Scheme == "https" || u.Scheme == "unixs"
  308. sctx.insecure = !sctx.secure
  309. if oldctx := sctxs[addr]; oldctx != nil {
  310. oldctx.secure = oldctx.secure || sctx.secure
  311. oldctx.insecure = oldctx.insecure || sctx.insecure
  312. continue
  313. }
  314. if sctx.l, err = net.Listen(proto, addr); err != nil {
  315. return nil, err
  316. }
  317. // net.Listener will rewrite ipv4 0.0.0.0 to ipv6 [::], breaking
  318. // hosts that disable ipv6. So, use the address given by the user.
  319. sctx.addr = addr
  320. if fdLimit, fderr := runtimeutil.FDLimit(); fderr == nil {
  321. if fdLimit <= reservedInternalFDNum {
  322. 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)
  323. }
  324. sctx.l = transport.LimitListener(sctx.l, int(fdLimit-reservedInternalFDNum))
  325. }
  326. if proto == "tcp" {
  327. if sctx.l, err = transport.NewKeepAliveListener(sctx.l, "tcp", nil); err != nil {
  328. return nil, err
  329. }
  330. }
  331. plog.Info("listening for client requests on ", u.Host)
  332. defer func() {
  333. if err != nil {
  334. sctx.l.Close()
  335. plog.Info("stopping listening for client requests on ", u.Host)
  336. }
  337. }()
  338. for k := range cfg.UserHandlers {
  339. sctx.userHandlers[k] = cfg.UserHandlers[k]
  340. }
  341. sctx.serviceRegister = cfg.ServiceRegister
  342. if cfg.EnablePprof || cfg.Debug {
  343. sctx.registerPprof()
  344. }
  345. if cfg.Debug {
  346. sctx.registerTrace()
  347. }
  348. sctxs[addr] = sctx
  349. }
  350. return sctxs, nil
  351. }
  352. func (e *Etcd) serve() (err error) {
  353. if !e.cfg.ClientTLSInfo.Empty() {
  354. plog.Infof("ClientTLS: %s", e.cfg.ClientTLSInfo)
  355. }
  356. if e.cfg.CorsInfo.String() != "" {
  357. plog.Infof("cors = %s", e.cfg.CorsInfo)
  358. }
  359. // Start the peer server in a goroutine
  360. for _, pl := range e.Peers {
  361. go func(l *peerListener) {
  362. e.errHandler(l.serve())
  363. }(pl)
  364. }
  365. // Start a client server goroutine for each listen address
  366. var h http.Handler
  367. if e.Config().EnableV2 {
  368. h = v2http.NewClientHandler(e.Server, e.Server.Cfg.ReqTimeout())
  369. } else {
  370. mux := http.NewServeMux()
  371. etcdhttp.HandleBasic(mux, e.Server)
  372. h = mux
  373. }
  374. h = http.Handler(&cors.CORSHandler{Handler: h, Info: e.cfg.CorsInfo})
  375. for _, sctx := range e.sctxs {
  376. go func(s *serveCtx) {
  377. e.errHandler(s.serve(e.Server, &e.cfg.ClientTLSInfo, h, e.errHandler))
  378. }(sctx)
  379. }
  380. if len(e.cfg.ListenMetricsUrls) > 0 {
  381. metricsMux := http.NewServeMux()
  382. etcdhttp.HandleMetricsHealth(metricsMux, e.Server)
  383. for _, murl := range e.cfg.ListenMetricsUrls {
  384. tlsInfo := &e.cfg.ClientTLSInfo
  385. if murl.Scheme == "http" {
  386. tlsInfo = nil
  387. }
  388. ml, err := transport.NewListener(murl.Host, murl.Scheme, tlsInfo)
  389. if err != nil {
  390. return err
  391. }
  392. e.metricsListeners = append(e.metricsListeners, ml)
  393. go func(u url.URL, ln net.Listener) {
  394. plog.Info("listening for metrics on ", u.String())
  395. e.errHandler(http.Serve(ln, metricsMux))
  396. }(murl, ml)
  397. }
  398. }
  399. return nil
  400. }
  401. func (e *Etcd) errHandler(err error) {
  402. select {
  403. case <-e.stopc:
  404. return
  405. default:
  406. }
  407. select {
  408. case <-e.stopc:
  409. case e.errc <- err:
  410. }
  411. }