etcd.go 16 KB

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