etcd.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  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. "sort"
  25. "strconv"
  26. "sync"
  27. "time"
  28. "github.com/coreos/etcd/etcdserver"
  29. "github.com/coreos/etcd/etcdserver/api/etcdhttp"
  30. "github.com/coreos/etcd/etcdserver/api/v2http"
  31. "github.com/coreos/etcd/etcdserver/api/v2v3"
  32. "github.com/coreos/etcd/etcdserver/api/v3client"
  33. "github.com/coreos/etcd/etcdserver/api/v3rpc"
  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. PeerTLSInfo: cfg.PeerTLSInfo,
  144. TickMs: cfg.TickMs,
  145. ElectionTicks: cfg.ElectionTicks(),
  146. AutoCompactionRetention: autoCompactionRetention,
  147. AutoCompactionMode: cfg.AutoCompactionMode,
  148. QuotaBackendBytes: cfg.QuotaBackendBytes,
  149. MaxTxnOps: cfg.MaxTxnOps,
  150. MaxRequestBytes: cfg.MaxRequestBytes,
  151. StrictReconfigCheck: cfg.StrictReconfigCheck,
  152. ClientCertAuthEnabled: cfg.ClientTLSInfo.ClientCertAuth,
  153. AuthToken: cfg.AuthToken,
  154. CORS: cfg.CORS,
  155. HostWhitelist: cfg.HostWhitelist,
  156. InitialCorruptCheck: cfg.ExperimentalInitialCorruptCheck,
  157. CorruptCheckTime: cfg.ExperimentalCorruptCheckTime,
  158. PreVote: cfg.PreVote,
  159. Debug: cfg.Debug,
  160. ForceNewCluster: cfg.ForceNewCluster,
  161. }
  162. if e.Server, err = etcdserver.NewServer(srvcfg); err != nil {
  163. return e, err
  164. }
  165. if len(e.cfg.CORS) > 0 {
  166. ss := make([]string, 0, len(e.cfg.CORS))
  167. for v := range e.cfg.CORS {
  168. ss = append(ss, v)
  169. }
  170. sort.Strings(ss)
  171. plog.Infof("%s starting with cors %q", e.Server.ID(), ss)
  172. }
  173. if len(e.cfg.HostWhitelist) > 0 {
  174. ss := make([]string, 0, len(e.cfg.HostWhitelist))
  175. for v := range e.cfg.HostWhitelist {
  176. ss = append(ss, v)
  177. }
  178. sort.Strings(ss)
  179. plog.Infof("%s starting with host whitelist %q", e.Server.ID(), ss)
  180. }
  181. // buffer channel so goroutines on closed connections won't wait forever
  182. e.errc = make(chan error, len(e.Peers)+len(e.Clients)+2*len(e.sctxs))
  183. // newly started member ("memberInitialized==false")
  184. // does not need corruption check
  185. if memberInitialized {
  186. if err = e.Server.CheckInitialHashKV(); err != nil {
  187. // set "EtcdServer" to nil, so that it does not block on "EtcdServer.Close()"
  188. // (nothing to close since rafthttp transports have not been started)
  189. e.Server = nil
  190. return e, err
  191. }
  192. }
  193. e.Server.Start()
  194. if err = e.servePeers(); err != nil {
  195. return e, err
  196. }
  197. if err = e.serveClients(); err != nil {
  198. return e, err
  199. }
  200. if err = e.serveMetrics(); err != nil {
  201. return e, err
  202. }
  203. serving = true
  204. return e, nil
  205. }
  206. // Config returns the current configuration.
  207. func (e *Etcd) Config() Config {
  208. return e.cfg
  209. }
  210. // Close gracefully shuts down all servers/listeners.
  211. // Client requests will be terminated with request timeout.
  212. // After timeout, enforce remaning requests be closed immediately.
  213. func (e *Etcd) Close() {
  214. e.closeOnce.Do(func() { close(e.stopc) })
  215. // close client requests with request timeout
  216. timeout := 2 * time.Second
  217. if e.Server != nil {
  218. timeout = e.Server.Cfg.ReqTimeout()
  219. }
  220. for _, sctx := range e.sctxs {
  221. for ss := range sctx.serversC {
  222. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  223. stopServers(ctx, ss)
  224. cancel()
  225. }
  226. }
  227. for _, sctx := range e.sctxs {
  228. sctx.cancel()
  229. }
  230. for i := range e.Clients {
  231. if e.Clients[i] != nil {
  232. e.Clients[i].Close()
  233. }
  234. }
  235. for i := range e.metricsListeners {
  236. e.metricsListeners[i].Close()
  237. }
  238. // close rafthttp transports
  239. if e.Server != nil {
  240. e.Server.Stop()
  241. }
  242. // close all idle connections in peer handler (wait up to 1-second)
  243. for i := range e.Peers {
  244. if e.Peers[i] != nil && e.Peers[i].close != nil {
  245. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  246. e.Peers[i].close(ctx)
  247. cancel()
  248. }
  249. }
  250. }
  251. func stopServers(ctx context.Context, ss *servers) {
  252. shutdownNow := func() {
  253. // first, close the http.Server
  254. ss.http.Shutdown(ctx)
  255. // then close grpc.Server; cancels all active RPCs
  256. ss.grpc.Stop()
  257. }
  258. // do not grpc.Server.GracefulStop with TLS enabled etcd server
  259. // See https://github.com/grpc/grpc-go/issues/1384#issuecomment-317124531
  260. // and https://github.com/coreos/etcd/issues/8916
  261. if ss.secure {
  262. shutdownNow()
  263. return
  264. }
  265. ch := make(chan struct{})
  266. go func() {
  267. defer close(ch)
  268. // close listeners to stop accepting new connections,
  269. // will block on any existing transports
  270. ss.grpc.GracefulStop()
  271. }()
  272. // wait until all pending RPCs are finished
  273. select {
  274. case <-ch:
  275. case <-ctx.Done():
  276. // took too long, manually close open transports
  277. // e.g. watch streams
  278. shutdownNow()
  279. // concurrent GracefulStop should be interrupted
  280. <-ch
  281. }
  282. }
  283. func (e *Etcd) Err() <-chan error { return e.errc }
  284. func startPeerListeners(cfg *Config) (peers []*peerListener, err error) {
  285. if err = cfg.PeerSelfCert(); err != nil {
  286. plog.Fatalf("could not get certs (%v)", err)
  287. }
  288. if !cfg.PeerTLSInfo.Empty() {
  289. plog.Infof("peerTLS: %s", cfg.PeerTLSInfo)
  290. }
  291. peers = make([]*peerListener, len(cfg.LPUrls))
  292. defer func() {
  293. if err == nil {
  294. return
  295. }
  296. for i := range peers {
  297. if peers[i] != nil && peers[i].close != nil {
  298. plog.Info("stopping listening for peers on ", cfg.LPUrls[i].String())
  299. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  300. peers[i].close(ctx)
  301. cancel()
  302. }
  303. }
  304. }()
  305. for i, u := range cfg.LPUrls {
  306. if u.Scheme == "http" {
  307. if !cfg.PeerTLSInfo.Empty() {
  308. plog.Warningf("The scheme of peer url %s is HTTP while peer key/cert files are presented. Ignored peer key/cert files.", u.String())
  309. }
  310. if cfg.PeerTLSInfo.ClientCertAuth {
  311. 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())
  312. }
  313. }
  314. peers[i] = &peerListener{close: func(context.Context) error { return nil }}
  315. peers[i].Listener, err = rafthttp.NewListener(u, &cfg.PeerTLSInfo)
  316. if err != nil {
  317. return nil, err
  318. }
  319. // once serve, overwrite with 'http.Server.Shutdown'
  320. peers[i].close = func(context.Context) error {
  321. return peers[i].Listener.Close()
  322. }
  323. plog.Info("listening for peers on ", u.String())
  324. }
  325. return peers, nil
  326. }
  327. // configure peer handlers after rafthttp.Transport started
  328. func (e *Etcd) servePeers() (err error) {
  329. ph := etcdhttp.NewPeerHandler(e.Server)
  330. var peerTLScfg *tls.Config
  331. if !e.cfg.PeerTLSInfo.Empty() {
  332. if peerTLScfg, err = e.cfg.PeerTLSInfo.ServerConfig(); err != nil {
  333. return err
  334. }
  335. }
  336. for _, p := range e.Peers {
  337. gs := v3rpc.Server(e.Server, peerTLScfg)
  338. m := cmux.New(p.Listener)
  339. go gs.Serve(m.Match(cmux.HTTP2()))
  340. srv := &http.Server{
  341. Handler: grpcHandlerFunc(gs, ph),
  342. ReadTimeout: 5 * time.Minute,
  343. ErrorLog: defaultLog.New(ioutil.Discard, "", 0), // do not log user error
  344. }
  345. go srv.Serve(m.Match(cmux.Any()))
  346. p.serve = func() error { return m.Serve() }
  347. p.close = func(ctx context.Context) error {
  348. // gracefully shutdown http.Server
  349. // close open listeners, idle connections
  350. // until context cancel or time-out
  351. stopServers(ctx, &servers{secure: peerTLScfg != nil, grpc: gs, http: srv})
  352. return nil
  353. }
  354. }
  355. // start peer servers in a goroutine
  356. for _, pl := range e.Peers {
  357. go func(l *peerListener) {
  358. e.errHandler(l.serve())
  359. }(pl)
  360. }
  361. return nil
  362. }
  363. func startClientListeners(cfg *Config) (sctxs map[string]*serveCtx, err error) {
  364. if err = cfg.ClientSelfCert(); err != nil {
  365. plog.Fatalf("could not get certs (%v)", err)
  366. }
  367. if cfg.EnablePprof {
  368. plog.Infof("pprof is enabled under %s", debugutil.HTTPPrefixPProf)
  369. }
  370. sctxs = make(map[string]*serveCtx)
  371. for _, u := range cfg.LCUrls {
  372. sctx := newServeCtx()
  373. if u.Scheme == "http" || u.Scheme == "unix" {
  374. if !cfg.ClientTLSInfo.Empty() {
  375. plog.Warningf("The scheme of client url %s is HTTP while peer key/cert files are presented. Ignored key/cert files.", u.String())
  376. }
  377. if cfg.ClientTLSInfo.ClientCertAuth {
  378. 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())
  379. }
  380. }
  381. if (u.Scheme == "https" || u.Scheme == "unixs") && cfg.ClientTLSInfo.Empty() {
  382. return nil, fmt.Errorf("TLS key/cert (--cert-file, --key-file) must be provided for client url %s with HTTPs scheme", u.String())
  383. }
  384. proto := "tcp"
  385. addr := u.Host
  386. if u.Scheme == "unix" || u.Scheme == "unixs" {
  387. proto = "unix"
  388. addr = u.Host + u.Path
  389. }
  390. sctx.secure = u.Scheme == "https" || u.Scheme == "unixs"
  391. sctx.insecure = !sctx.secure
  392. if oldctx := sctxs[addr]; oldctx != nil {
  393. oldctx.secure = oldctx.secure || sctx.secure
  394. oldctx.insecure = oldctx.insecure || sctx.insecure
  395. continue
  396. }
  397. if sctx.l, err = net.Listen(proto, addr); err != nil {
  398. return nil, err
  399. }
  400. // net.Listener will rewrite ipv4 0.0.0.0 to ipv6 [::], breaking
  401. // hosts that disable ipv6. So, use the address given by the user.
  402. sctx.addr = addr
  403. if fdLimit, fderr := runtimeutil.FDLimit(); fderr == nil {
  404. if fdLimit <= reservedInternalFDNum {
  405. 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)
  406. }
  407. sctx.l = transport.LimitListener(sctx.l, int(fdLimit-reservedInternalFDNum))
  408. }
  409. if proto == "tcp" {
  410. if sctx.l, err = transport.NewKeepAliveListener(sctx.l, "tcp", nil); err != nil {
  411. return nil, err
  412. }
  413. }
  414. plog.Info("listening for client requests on ", u.Host)
  415. defer func() {
  416. if err != nil {
  417. sctx.l.Close()
  418. plog.Info("stopping listening for client requests on ", u.Host)
  419. }
  420. }()
  421. for k := range cfg.UserHandlers {
  422. sctx.userHandlers[k] = cfg.UserHandlers[k]
  423. }
  424. sctx.serviceRegister = cfg.ServiceRegister
  425. if cfg.EnablePprof || cfg.Debug {
  426. sctx.registerPprof()
  427. }
  428. if cfg.Debug {
  429. sctx.registerTrace()
  430. }
  431. sctxs[addr] = sctx
  432. }
  433. return sctxs, nil
  434. }
  435. func (e *Etcd) serveClients() (err error) {
  436. if !e.cfg.ClientTLSInfo.Empty() {
  437. plog.Infof("ClientTLS: %s", e.cfg.ClientTLSInfo)
  438. }
  439. // Start a client server goroutine for each listen address
  440. var h http.Handler
  441. if e.Config().EnableV2 {
  442. if len(e.Config().ExperimentalEnableV2V3) > 0 {
  443. srv := v2v3.NewServer(v3client.New(e.Server), e.cfg.ExperimentalEnableV2V3)
  444. h = v2http.NewClientHandler(srv, e.Server.Cfg.ReqTimeout())
  445. } else {
  446. h = v2http.NewClientHandler(e.Server, e.Server.Cfg.ReqTimeout())
  447. }
  448. } else {
  449. mux := http.NewServeMux()
  450. etcdhttp.HandleBasic(mux, e.Server)
  451. h = mux
  452. }
  453. gopts := []grpc.ServerOption{}
  454. if e.cfg.GRPCKeepAliveMinTime > time.Duration(0) {
  455. gopts = append(gopts, grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{
  456. MinTime: e.cfg.GRPCKeepAliveMinTime,
  457. PermitWithoutStream: false,
  458. }))
  459. }
  460. if e.cfg.GRPCKeepAliveInterval > time.Duration(0) &&
  461. e.cfg.GRPCKeepAliveTimeout > time.Duration(0) {
  462. gopts = append(gopts, grpc.KeepaliveParams(keepalive.ServerParameters{
  463. Time: e.cfg.GRPCKeepAliveInterval,
  464. Timeout: e.cfg.GRPCKeepAliveTimeout,
  465. }))
  466. }
  467. // start client servers in a goroutine
  468. for _, sctx := range e.sctxs {
  469. go func(s *serveCtx) {
  470. e.errHandler(s.serve(e.Server, &e.cfg.ClientTLSInfo, h, e.errHandler, gopts...))
  471. }(sctx)
  472. }
  473. return nil
  474. }
  475. func (e *Etcd) serveMetrics() (err error) {
  476. if e.cfg.Metrics == "extensive" {
  477. grpc_prometheus.EnableHandlingTimeHistogram()
  478. }
  479. if len(e.cfg.ListenMetricsUrls) > 0 {
  480. metricsMux := http.NewServeMux()
  481. etcdhttp.HandleMetricsHealth(metricsMux, e.Server)
  482. for _, murl := range e.cfg.ListenMetricsUrls {
  483. tlsInfo := &e.cfg.ClientTLSInfo
  484. if murl.Scheme == "http" {
  485. tlsInfo = nil
  486. }
  487. ml, err := transport.NewListener(murl.Host, murl.Scheme, tlsInfo)
  488. if err != nil {
  489. return err
  490. }
  491. e.metricsListeners = append(e.metricsListeners, ml)
  492. go func(u url.URL, ln net.Listener) {
  493. plog.Info("listening for metrics on ", u.String())
  494. e.errHandler(http.Serve(ln, metricsMux))
  495. }(murl, ml)
  496. }
  497. }
  498. return nil
  499. }
  500. func (e *Etcd) errHandler(err error) {
  501. select {
  502. case <-e.stopc:
  503. return
  504. default:
  505. }
  506. select {
  507. case <-e.stopc:
  508. case e.errc <- err:
  509. }
  510. }
  511. func parseCompactionRetention(mode, retention string) (ret time.Duration, err error) {
  512. h, err := strconv.Atoi(retention)
  513. if err == nil {
  514. switch mode {
  515. case CompactorModeRevision:
  516. ret = time.Duration(int64(h))
  517. case CompactorModePeriodic:
  518. ret = time.Duration(int64(h)) * time.Hour
  519. }
  520. } else {
  521. // periodic compaction
  522. ret, err = time.ParseDuration(retention)
  523. if err != nil {
  524. return 0, fmt.Errorf("error parsing CompactionRetention: %v", err)
  525. }
  526. }
  527. return ret, nil
  528. }