etcd.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829
  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. "runtime"
  25. "sort"
  26. "strconv"
  27. "sync"
  28. "time"
  29. "go.etcd.io/etcd/etcdserver"
  30. "go.etcd.io/etcd/etcdserver/api/etcdhttp"
  31. "go.etcd.io/etcd/etcdserver/api/rafthttp"
  32. "go.etcd.io/etcd/etcdserver/api/v2http"
  33. "go.etcd.io/etcd/etcdserver/api/v2v3"
  34. "go.etcd.io/etcd/etcdserver/api/v3client"
  35. "go.etcd.io/etcd/etcdserver/api/v3rpc"
  36. "go.etcd.io/etcd/pkg/debugutil"
  37. runtimeutil "go.etcd.io/etcd/pkg/runtime"
  38. "go.etcd.io/etcd/pkg/transport"
  39. "go.etcd.io/etcd/pkg/types"
  40. "go.etcd.io/etcd/version"
  41. "github.com/coreos/pkg/capnslog"
  42. grpc_prometheus "github.com/grpc-ecosystem/go-grpc-prometheus"
  43. "github.com/soheilhy/cmux"
  44. "go.uber.org/zap"
  45. "google.golang.org/grpc"
  46. "google.golang.org/grpc/keepalive"
  47. )
  48. var plog = capnslog.NewPackageLogger("go.etcd.io/etcd", "embed")
  49. const (
  50. // internal fd usage includes disk usage and transport usage.
  51. // To read/write snapshot, snap pkg needs 1. In normal case, wal pkg needs
  52. // at most 2 to read/lock/write WALs. One case that it needs to 2 is to
  53. // read all logs after some snapshot index, which locates at the end of
  54. // the second last and the head of the last. For purging, it needs to read
  55. // directory, so it needs 1. For fd monitor, it needs 1.
  56. // For transport, rafthttp builds two long-polling connections and at most
  57. // four temporary connections with each member. There are at most 9 members
  58. // in a cluster, so it should reserve 96.
  59. // For the safety, we set the total reserved number to 150.
  60. reservedInternalFDNum = 150
  61. )
  62. // Etcd contains a running etcd server and its listeners.
  63. type Etcd struct {
  64. Peers []*peerListener
  65. Clients []net.Listener
  66. // a map of contexts for the servers that serves client requests.
  67. sctxs map[string]*serveCtx
  68. metricsListeners []net.Listener
  69. Server *etcdserver.EtcdServer
  70. cfg Config
  71. stopc chan struct{}
  72. errc chan error
  73. closeOnce sync.Once
  74. }
  75. type peerListener struct {
  76. net.Listener
  77. serve func() error
  78. close func(context.Context) error
  79. }
  80. // StartEtcd launches the etcd server and HTTP handlers for client/server communication.
  81. // The returned Etcd.Server is not guaranteed to have joined the cluster. Wait
  82. // on the Etcd.Server.ReadyNotify() channel to know when it completes and is ready for use.
  83. func StartEtcd(inCfg *Config) (e *Etcd, err error) {
  84. if err = inCfg.Validate(); err != nil {
  85. return nil, err
  86. }
  87. serving := false
  88. e = &Etcd{cfg: *inCfg, stopc: make(chan struct{})}
  89. cfg := &e.cfg
  90. defer func() {
  91. if e == nil || err == nil {
  92. return
  93. }
  94. if !serving {
  95. // errored before starting gRPC server for serveCtx.serversC
  96. for _, sctx := range e.sctxs {
  97. close(sctx.serversC)
  98. }
  99. }
  100. e.Close()
  101. e = nil
  102. }()
  103. if e.cfg.logger != nil {
  104. e.cfg.logger.Info(
  105. "configuring peer listeners",
  106. zap.Strings("listen-peer-urls", e.cfg.getLPURLs()),
  107. )
  108. }
  109. if e.Peers, err = configurePeerListeners(cfg); err != nil {
  110. return e, err
  111. }
  112. if e.cfg.logger != nil {
  113. e.cfg.logger.Info(
  114. "configuring client listeners",
  115. zap.Strings("listen-client-urls", e.cfg.getLCURLs()),
  116. )
  117. }
  118. if e.sctxs, err = configureClientListeners(cfg); err != nil {
  119. return e, err
  120. }
  121. for _, sctx := range e.sctxs {
  122. e.Clients = append(e.Clients, sctx.l)
  123. }
  124. var (
  125. urlsmap types.URLsMap
  126. token string
  127. )
  128. memberInitialized := true
  129. if !isMemberInitialized(cfg) {
  130. memberInitialized = false
  131. urlsmap, token, err = cfg.PeerURLsMapAndToken("etcd")
  132. if err != nil {
  133. return e, fmt.Errorf("error setting up initial cluster: %v", err)
  134. }
  135. }
  136. // AutoCompactionRetention defaults to "0" if not set.
  137. if len(cfg.AutoCompactionRetention) == 0 {
  138. cfg.AutoCompactionRetention = "0"
  139. }
  140. autoCompactionRetention, err := parseCompactionRetention(cfg.AutoCompactionMode, cfg.AutoCompactionRetention)
  141. if err != nil {
  142. return e, err
  143. }
  144. backendFreelistType := parseBackendFreelistType(cfg.ExperimentalBackendFreelistType)
  145. srvcfg := etcdserver.ServerConfig{
  146. Name: cfg.Name,
  147. ClientURLs: cfg.ACUrls,
  148. PeerURLs: cfg.APUrls,
  149. DataDir: cfg.Dir,
  150. DedicatedWALDir: cfg.WalDir,
  151. SnapshotCount: cfg.SnapshotCount,
  152. SnapshotCatchUpEntries: cfg.SnapshotCatchUpEntries,
  153. MaxSnapFiles: cfg.MaxSnapFiles,
  154. MaxWALFiles: cfg.MaxWalFiles,
  155. InitialPeerURLsMap: urlsmap,
  156. InitialClusterToken: token,
  157. DiscoveryURL: cfg.Durl,
  158. DiscoveryProxy: cfg.Dproxy,
  159. NewCluster: cfg.IsNewCluster(),
  160. PeerTLSInfo: cfg.PeerTLSInfo,
  161. TickMs: cfg.TickMs,
  162. ElectionTicks: cfg.ElectionTicks(),
  163. InitialElectionTickAdvance: cfg.InitialElectionTickAdvance,
  164. AutoCompactionRetention: autoCompactionRetention,
  165. AutoCompactionMode: cfg.AutoCompactionMode,
  166. QuotaBackendBytes: cfg.QuotaBackendBytes,
  167. BackendBatchLimit: cfg.BackendBatchLimit,
  168. BackendFreelistType: backendFreelistType,
  169. BackendBatchInterval: cfg.BackendBatchInterval,
  170. MaxTxnOps: cfg.MaxTxnOps,
  171. MaxRequestBytes: cfg.MaxRequestBytes,
  172. StrictReconfigCheck: cfg.StrictReconfigCheck,
  173. ClientCertAuthEnabled: cfg.ClientTLSInfo.ClientCertAuth,
  174. AuthToken: cfg.AuthToken,
  175. BcryptCost: cfg.BcryptCost,
  176. CORS: cfg.CORS,
  177. HostWhitelist: cfg.HostWhitelist,
  178. InitialCorruptCheck: cfg.ExperimentalInitialCorruptCheck,
  179. CorruptCheckTime: cfg.ExperimentalCorruptCheckTime,
  180. PreVote: cfg.PreVote,
  181. Logger: cfg.logger,
  182. LoggerConfig: cfg.loggerConfig,
  183. LoggerCore: cfg.loggerCore,
  184. LoggerWriteSyncer: cfg.loggerWriteSyncer,
  185. Debug: cfg.Debug,
  186. ForceNewCluster: cfg.ForceNewCluster,
  187. EnableGRPCGateway: cfg.EnableGRPCGateway,
  188. EnableLeaseCheckpoint: cfg.ExperimentalEnableLeaseCheckpoint,
  189. CompactionBatchLimit: cfg.ExperimentalCompactionBatchLimit,
  190. }
  191. print(e.cfg.logger, *cfg, srvcfg, memberInitialized)
  192. if e.Server, err = etcdserver.NewServer(srvcfg); err != nil {
  193. return e, err
  194. }
  195. // buffer channel so goroutines on closed connections won't wait forever
  196. e.errc = make(chan error, len(e.Peers)+len(e.Clients)+2*len(e.sctxs))
  197. // newly started member ("memberInitialized==false")
  198. // does not need corruption check
  199. if memberInitialized {
  200. if err = e.Server.CheckInitialHashKV(); err != nil {
  201. // set "EtcdServer" to nil, so that it does not block on "EtcdServer.Close()"
  202. // (nothing to close since rafthttp transports have not been started)
  203. e.Server = nil
  204. return e, err
  205. }
  206. }
  207. e.Server.Start()
  208. if err = e.servePeers(); err != nil {
  209. return e, err
  210. }
  211. if err = e.serveClients(); err != nil {
  212. return e, err
  213. }
  214. if err = e.serveMetrics(); err != nil {
  215. return e, err
  216. }
  217. if e.cfg.logger != nil {
  218. e.cfg.logger.Info(
  219. "now serving peer/client/metrics",
  220. zap.String("local-member-id", e.Server.ID().String()),
  221. zap.Strings("initial-advertise-peer-urls", e.cfg.getAPURLs()),
  222. zap.Strings("listen-peer-urls", e.cfg.getLPURLs()),
  223. zap.Strings("advertise-client-urls", e.cfg.getACURLs()),
  224. zap.Strings("listen-client-urls", e.cfg.getLCURLs()),
  225. zap.Strings("listen-metrics-urls", e.cfg.getMetricsURLs()),
  226. )
  227. }
  228. serving = true
  229. return e, nil
  230. }
  231. func print(lg *zap.Logger, ec Config, sc etcdserver.ServerConfig, memberInitialized bool) {
  232. // TODO: remove this after dropping "capnslog"
  233. if lg == nil {
  234. plog.Infof("name = %s", ec.Name)
  235. if sc.ForceNewCluster {
  236. plog.Infof("force new cluster")
  237. }
  238. plog.Infof("data dir = %s", sc.DataDir)
  239. plog.Infof("member dir = %s", sc.MemberDir())
  240. if sc.DedicatedWALDir != "" {
  241. plog.Infof("dedicated WAL dir = %s", sc.DedicatedWALDir)
  242. }
  243. plog.Infof("heartbeat = %dms", sc.TickMs)
  244. plog.Infof("election = %dms", sc.ElectionTicks*int(sc.TickMs))
  245. plog.Infof("snapshot count = %d", sc.SnapshotCount)
  246. if len(sc.DiscoveryURL) != 0 {
  247. plog.Infof("discovery URL= %s", sc.DiscoveryURL)
  248. if len(sc.DiscoveryProxy) != 0 {
  249. plog.Infof("discovery proxy = %s", sc.DiscoveryProxy)
  250. }
  251. }
  252. plog.Infof("advertise client URLs = %s", sc.ClientURLs)
  253. if memberInitialized {
  254. plog.Infof("initial advertise peer URLs = %s", sc.PeerURLs)
  255. plog.Infof("initial cluster = %s", sc.InitialPeerURLsMap)
  256. }
  257. } else {
  258. cors := make([]string, 0, len(ec.CORS))
  259. for v := range ec.CORS {
  260. cors = append(cors, v)
  261. }
  262. sort.Strings(cors)
  263. hss := make([]string, 0, len(ec.HostWhitelist))
  264. for v := range ec.HostWhitelist {
  265. hss = append(hss, v)
  266. }
  267. sort.Strings(hss)
  268. quota := ec.QuotaBackendBytes
  269. if quota == 0 {
  270. quota = etcdserver.DefaultQuotaBytes
  271. }
  272. lg.Info(
  273. "starting an etcd server",
  274. zap.String("etcd-version", version.Version),
  275. zap.String("git-sha", version.GitSHA),
  276. zap.String("go-version", runtime.Version()),
  277. zap.String("go-os", runtime.GOOS),
  278. zap.String("go-arch", runtime.GOARCH),
  279. zap.Int("max-cpu-set", runtime.GOMAXPROCS(0)),
  280. zap.Int("max-cpu-available", runtime.NumCPU()),
  281. zap.Bool("member-initialized", memberInitialized),
  282. zap.String("name", sc.Name),
  283. zap.String("data-dir", sc.DataDir),
  284. zap.String("wal-dir", ec.WalDir),
  285. zap.String("wal-dir-dedicated", sc.DedicatedWALDir),
  286. zap.String("member-dir", sc.MemberDir()),
  287. zap.Bool("force-new-cluster", sc.ForceNewCluster),
  288. zap.String("heartbeat-interval", fmt.Sprintf("%v", time.Duration(sc.TickMs)*time.Millisecond)),
  289. zap.String("election-timeout", fmt.Sprintf("%v", time.Duration(sc.ElectionTicks*int(sc.TickMs))*time.Millisecond)),
  290. zap.Bool("initial-election-tick-advance", sc.InitialElectionTickAdvance),
  291. zap.Uint64("snapshot-count", sc.SnapshotCount),
  292. zap.Uint64("snapshot-catchup-entries", sc.SnapshotCatchUpEntries),
  293. zap.Strings("initial-advertise-peer-urls", ec.getAPURLs()),
  294. zap.Strings("listen-peer-urls", ec.getLPURLs()),
  295. zap.Strings("advertise-client-urls", ec.getACURLs()),
  296. zap.Strings("listen-client-urls", ec.getLCURLs()),
  297. zap.Strings("listen-metrics-urls", ec.getMetricsURLs()),
  298. zap.Strings("cors", cors),
  299. zap.Strings("host-whitelist", hss),
  300. zap.String("initial-cluster", sc.InitialPeerURLsMap.String()),
  301. zap.String("initial-cluster-state", ec.ClusterState),
  302. zap.String("initial-cluster-token", sc.InitialClusterToken),
  303. zap.Int64("quota-size-bytes", quota),
  304. zap.Bool("pre-vote", sc.PreVote),
  305. zap.Bool("initial-corrupt-check", sc.InitialCorruptCheck),
  306. zap.String("corrupt-check-time-interval", sc.CorruptCheckTime.String()),
  307. zap.String("auto-compaction-mode", sc.AutoCompactionMode),
  308. zap.Duration("auto-compaction-retention", sc.AutoCompactionRetention),
  309. zap.String("auto-compaction-interval", sc.AutoCompactionRetention.String()),
  310. zap.String("discovery-url", sc.DiscoveryURL),
  311. zap.String("discovery-proxy", sc.DiscoveryProxy),
  312. )
  313. }
  314. }
  315. // Config returns the current configuration.
  316. func (e *Etcd) Config() Config {
  317. return e.cfg
  318. }
  319. // Close gracefully shuts down all servers/listeners.
  320. // Client requests will be terminated with request timeout.
  321. // After timeout, enforce remaning requests be closed immediately.
  322. func (e *Etcd) Close() {
  323. fields := []zap.Field{
  324. zap.String("name", e.cfg.Name),
  325. zap.String("data-dir", e.cfg.Dir),
  326. zap.Strings("advertise-peer-urls", e.cfg.getAPURLs()),
  327. zap.Strings("advertise-client-urls", e.cfg.getACURLs()),
  328. }
  329. lg := e.GetLogger()
  330. if lg != nil {
  331. lg.Info("closing etcd server", fields...)
  332. }
  333. defer func() {
  334. if lg != nil {
  335. lg.Info("closed etcd server", fields...)
  336. lg.Sync()
  337. }
  338. }()
  339. e.closeOnce.Do(func() { close(e.stopc) })
  340. // close client requests with request timeout
  341. timeout := 2 * time.Second
  342. if e.Server != nil {
  343. timeout = e.Server.Cfg.ReqTimeout()
  344. }
  345. for _, sctx := range e.sctxs {
  346. for ss := range sctx.serversC {
  347. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  348. stopServers(ctx, ss)
  349. cancel()
  350. }
  351. }
  352. for _, sctx := range e.sctxs {
  353. sctx.cancel()
  354. }
  355. for i := range e.Clients {
  356. if e.Clients[i] != nil {
  357. e.Clients[i].Close()
  358. }
  359. }
  360. for i := range e.metricsListeners {
  361. e.metricsListeners[i].Close()
  362. }
  363. // close rafthttp transports
  364. if e.Server != nil {
  365. e.Server.Stop()
  366. }
  367. // close all idle connections in peer handler (wait up to 1-second)
  368. for i := range e.Peers {
  369. if e.Peers[i] != nil && e.Peers[i].close != nil {
  370. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  371. e.Peers[i].close(ctx)
  372. cancel()
  373. }
  374. }
  375. }
  376. func stopServers(ctx context.Context, ss *servers) {
  377. shutdownNow := func() {
  378. // first, close the http.Server
  379. ss.http.Shutdown(ctx)
  380. // then close grpc.Server; cancels all active RPCs
  381. ss.grpc.Stop()
  382. }
  383. // do not grpc.Server.GracefulStop with TLS enabled etcd server
  384. // See https://github.com/grpc/grpc-go/issues/1384#issuecomment-317124531
  385. // and https://github.com/etcd-io/etcd/issues/8916
  386. if ss.secure {
  387. shutdownNow()
  388. return
  389. }
  390. ch := make(chan struct{})
  391. go func() {
  392. defer close(ch)
  393. // close listeners to stop accepting new connections,
  394. // will block on any existing transports
  395. ss.grpc.GracefulStop()
  396. }()
  397. // wait until all pending RPCs are finished
  398. select {
  399. case <-ch:
  400. case <-ctx.Done():
  401. // took too long, manually close open transports
  402. // e.g. watch streams
  403. shutdownNow()
  404. // concurrent GracefulStop should be interrupted
  405. <-ch
  406. }
  407. }
  408. func (e *Etcd) Err() <-chan error { return e.errc }
  409. func configurePeerListeners(cfg *Config) (peers []*peerListener, err error) {
  410. if err = updateCipherSuites(&cfg.PeerTLSInfo, cfg.CipherSuites); err != nil {
  411. return nil, err
  412. }
  413. if err = cfg.PeerSelfCert(); err != nil {
  414. if cfg.logger != nil {
  415. cfg.logger.Fatal("failed to get peer self-signed certs", zap.Error(err))
  416. } else {
  417. plog.Fatalf("could not get certs (%v)", err)
  418. }
  419. }
  420. if !cfg.PeerTLSInfo.Empty() {
  421. if cfg.logger != nil {
  422. cfg.logger.Info(
  423. "starting with peer TLS",
  424. zap.String("tls-info", fmt.Sprintf("%+v", cfg.PeerTLSInfo)),
  425. zap.Strings("cipher-suites", cfg.CipherSuites),
  426. )
  427. } else {
  428. plog.Infof("peerTLS: %s", cfg.PeerTLSInfo)
  429. }
  430. }
  431. peers = make([]*peerListener, len(cfg.LPUrls))
  432. defer func() {
  433. if err == nil {
  434. return
  435. }
  436. for i := range peers {
  437. if peers[i] != nil && peers[i].close != nil {
  438. if cfg.logger != nil {
  439. cfg.logger.Warn(
  440. "closing peer listener",
  441. zap.String("address", cfg.LPUrls[i].String()),
  442. zap.Error(err),
  443. )
  444. } else {
  445. plog.Info("stopping listening for peers on ", cfg.LPUrls[i].String())
  446. }
  447. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  448. peers[i].close(ctx)
  449. cancel()
  450. }
  451. }
  452. }()
  453. for i, u := range cfg.LPUrls {
  454. if u.Scheme == "http" {
  455. if !cfg.PeerTLSInfo.Empty() {
  456. if cfg.logger != nil {
  457. cfg.logger.Warn("scheme is HTTP while key and cert files are present; ignoring key and cert files", zap.String("peer-url", u.String()))
  458. } else {
  459. plog.Warningf("The scheme of peer url %s is HTTP while peer key/cert files are presented. Ignored peer key/cert files.", u.String())
  460. }
  461. }
  462. if cfg.PeerTLSInfo.ClientCertAuth {
  463. if cfg.logger != nil {
  464. cfg.logger.Warn("scheme is HTTP while --peer-client-cert-auth is enabled; ignoring client cert auth for this URL", zap.String("peer-url", u.String()))
  465. } else {
  466. 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())
  467. }
  468. }
  469. }
  470. peers[i] = &peerListener{close: func(context.Context) error { return nil }}
  471. peers[i].Listener, err = rafthttp.NewListener(u, &cfg.PeerTLSInfo)
  472. if err != nil {
  473. return nil, err
  474. }
  475. // once serve, overwrite with 'http.Server.Shutdown'
  476. peers[i].close = func(context.Context) error {
  477. return peers[i].Listener.Close()
  478. }
  479. }
  480. return peers, nil
  481. }
  482. // configure peer handlers after rafthttp.Transport started
  483. func (e *Etcd) servePeers() (err error) {
  484. ph := etcdhttp.NewPeerHandler(e.GetLogger(), e.Server)
  485. var peerTLScfg *tls.Config
  486. if !e.cfg.PeerTLSInfo.Empty() {
  487. if peerTLScfg, err = e.cfg.PeerTLSInfo.ServerConfig(); err != nil {
  488. return err
  489. }
  490. }
  491. for _, p := range e.Peers {
  492. u := p.Listener.Addr().String()
  493. gs := v3rpc.Server(e.Server, peerTLScfg)
  494. m := cmux.New(p.Listener)
  495. go gs.Serve(m.Match(cmux.HTTP2()))
  496. srv := &http.Server{
  497. Handler: grpcHandlerFunc(gs, ph),
  498. ReadTimeout: 5 * time.Minute,
  499. ErrorLog: defaultLog.New(ioutil.Discard, "", 0), // do not log user error
  500. }
  501. go srv.Serve(m.Match(cmux.Any()))
  502. p.serve = func() error { return m.Serve() }
  503. p.close = func(ctx context.Context) error {
  504. // gracefully shutdown http.Server
  505. // close open listeners, idle connections
  506. // until context cancel or time-out
  507. if e.cfg.logger != nil {
  508. e.cfg.logger.Info(
  509. "stopping serving peer traffic",
  510. zap.String("address", u),
  511. )
  512. }
  513. stopServers(ctx, &servers{secure: peerTLScfg != nil, grpc: gs, http: srv})
  514. if e.cfg.logger != nil {
  515. e.cfg.logger.Info(
  516. "stopped serving peer traffic",
  517. zap.String("address", u),
  518. )
  519. }
  520. return nil
  521. }
  522. }
  523. // start peer servers in a goroutine
  524. for _, pl := range e.Peers {
  525. go func(l *peerListener) {
  526. u := l.Addr().String()
  527. if e.cfg.logger != nil {
  528. e.cfg.logger.Info(
  529. "serving peer traffic",
  530. zap.String("address", u),
  531. )
  532. } else {
  533. plog.Info("listening for peers on ", u)
  534. }
  535. e.errHandler(l.serve())
  536. }(pl)
  537. }
  538. return nil
  539. }
  540. func configureClientListeners(cfg *Config) (sctxs map[string]*serveCtx, err error) {
  541. if err = updateCipherSuites(&cfg.ClientTLSInfo, cfg.CipherSuites); err != nil {
  542. return nil, err
  543. }
  544. if err = cfg.ClientSelfCert(); err != nil {
  545. if cfg.logger != nil {
  546. cfg.logger.Fatal("failed to get client self-signed certs", zap.Error(err))
  547. } else {
  548. plog.Fatalf("could not get certs (%v)", err)
  549. }
  550. }
  551. if cfg.EnablePprof {
  552. if cfg.logger != nil {
  553. cfg.logger.Info("pprof is enabled", zap.String("path", debugutil.HTTPPrefixPProf))
  554. } else {
  555. plog.Infof("pprof is enabled under %s", debugutil.HTTPPrefixPProf)
  556. }
  557. }
  558. sctxs = make(map[string]*serveCtx)
  559. for _, u := range cfg.LCUrls {
  560. sctx := newServeCtx(cfg.logger)
  561. if u.Scheme == "http" || u.Scheme == "unix" {
  562. if !cfg.ClientTLSInfo.Empty() {
  563. if cfg.logger != nil {
  564. cfg.logger.Warn("scheme is HTTP while key and cert files are present; ignoring key and cert files", zap.String("client-url", u.String()))
  565. } else {
  566. plog.Warningf("The scheme of client url %s is HTTP while peer key/cert files are presented. Ignored key/cert files.", u.String())
  567. }
  568. }
  569. if cfg.ClientTLSInfo.ClientCertAuth {
  570. if cfg.logger != nil {
  571. cfg.logger.Warn("scheme is HTTP while --client-cert-auth is enabled; ignoring client cert auth for this URL", zap.String("client-url", u.String()))
  572. } else {
  573. 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())
  574. }
  575. }
  576. }
  577. if (u.Scheme == "https" || u.Scheme == "unixs") && cfg.ClientTLSInfo.Empty() {
  578. return nil, fmt.Errorf("TLS key/cert (--cert-file, --key-file) must be provided for client url %s with HTTPS scheme", u.String())
  579. }
  580. network := "tcp"
  581. addr := u.Host
  582. if u.Scheme == "unix" || u.Scheme == "unixs" {
  583. network = "unix"
  584. addr = u.Host + u.Path
  585. }
  586. sctx.network = network
  587. sctx.secure = u.Scheme == "https" || u.Scheme == "unixs"
  588. sctx.insecure = !sctx.secure
  589. if oldctx := sctxs[addr]; oldctx != nil {
  590. oldctx.secure = oldctx.secure || sctx.secure
  591. oldctx.insecure = oldctx.insecure || sctx.insecure
  592. continue
  593. }
  594. if sctx.l, err = net.Listen(network, addr); err != nil {
  595. return nil, err
  596. }
  597. // net.Listener will rewrite ipv4 0.0.0.0 to ipv6 [::], breaking
  598. // hosts that disable ipv6. So, use the address given by the user.
  599. sctx.addr = addr
  600. if fdLimit, fderr := runtimeutil.FDLimit(); fderr == nil {
  601. if fdLimit <= reservedInternalFDNum {
  602. if cfg.logger != nil {
  603. cfg.logger.Fatal(
  604. "file descriptor limit of etcd process is too low; please set higher",
  605. zap.Uint64("limit", fdLimit),
  606. zap.Int("recommended-limit", reservedInternalFDNum),
  607. )
  608. } else {
  609. 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)
  610. }
  611. }
  612. sctx.l = transport.LimitListener(sctx.l, int(fdLimit-reservedInternalFDNum))
  613. }
  614. if network == "tcp" {
  615. if sctx.l, err = transport.NewKeepAliveListener(sctx.l, network, nil); err != nil {
  616. return nil, err
  617. }
  618. }
  619. defer func() {
  620. if err == nil {
  621. return
  622. }
  623. sctx.l.Close()
  624. if cfg.logger != nil {
  625. cfg.logger.Warn(
  626. "closing peer listener",
  627. zap.String("address", u.Host),
  628. zap.Error(err),
  629. )
  630. } else {
  631. plog.Info("stopping listening for client requests on ", u.Host)
  632. }
  633. }()
  634. for k := range cfg.UserHandlers {
  635. sctx.userHandlers[k] = cfg.UserHandlers[k]
  636. }
  637. sctx.serviceRegister = cfg.ServiceRegister
  638. if cfg.EnablePprof || cfg.Debug {
  639. sctx.registerPprof()
  640. }
  641. if cfg.Debug {
  642. sctx.registerTrace()
  643. }
  644. sctxs[addr] = sctx
  645. }
  646. return sctxs, nil
  647. }
  648. func (e *Etcd) serveClients() (err error) {
  649. if !e.cfg.ClientTLSInfo.Empty() {
  650. if e.cfg.logger != nil {
  651. e.cfg.logger.Info(
  652. "starting with client TLS",
  653. zap.String("tls-info", fmt.Sprintf("%+v", e.cfg.ClientTLSInfo)),
  654. zap.Strings("cipher-suites", e.cfg.CipherSuites),
  655. )
  656. } else {
  657. plog.Infof("ClientTLS: %s", e.cfg.ClientTLSInfo)
  658. }
  659. }
  660. // Start a client server goroutine for each listen address
  661. var h http.Handler
  662. if e.Config().EnableV2 {
  663. if len(e.Config().ExperimentalEnableV2V3) > 0 {
  664. srv := v2v3.NewServer(e.cfg.logger, v3client.New(e.Server), e.cfg.ExperimentalEnableV2V3)
  665. h = v2http.NewClientHandler(e.GetLogger(), srv, e.Server.Cfg.ReqTimeout())
  666. } else {
  667. h = v2http.NewClientHandler(e.GetLogger(), e.Server, e.Server.Cfg.ReqTimeout())
  668. }
  669. } else {
  670. mux := http.NewServeMux()
  671. etcdhttp.HandleBasic(mux, e.Server)
  672. h = mux
  673. }
  674. gopts := []grpc.ServerOption{}
  675. if e.cfg.GRPCKeepAliveMinTime > time.Duration(0) {
  676. gopts = append(gopts, grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{
  677. MinTime: e.cfg.GRPCKeepAliveMinTime,
  678. PermitWithoutStream: false,
  679. }))
  680. }
  681. if e.cfg.GRPCKeepAliveInterval > time.Duration(0) &&
  682. e.cfg.GRPCKeepAliveTimeout > time.Duration(0) {
  683. gopts = append(gopts, grpc.KeepaliveParams(keepalive.ServerParameters{
  684. Time: e.cfg.GRPCKeepAliveInterval,
  685. Timeout: e.cfg.GRPCKeepAliveTimeout,
  686. }))
  687. }
  688. // start client servers in each goroutine
  689. for _, sctx := range e.sctxs {
  690. go func(s *serveCtx) {
  691. e.errHandler(s.serve(e.Server, &e.cfg.ClientTLSInfo, h, e.errHandler, gopts...))
  692. }(sctx)
  693. }
  694. return nil
  695. }
  696. func (e *Etcd) serveMetrics() (err error) {
  697. if e.cfg.Metrics == "extensive" {
  698. grpc_prometheus.EnableHandlingTimeHistogram()
  699. }
  700. if len(e.cfg.ListenMetricsUrls) > 0 {
  701. metricsMux := http.NewServeMux()
  702. etcdhttp.HandleMetricsHealth(metricsMux, e.Server)
  703. for _, murl := range e.cfg.ListenMetricsUrls {
  704. tlsInfo := &e.cfg.ClientTLSInfo
  705. if murl.Scheme == "http" {
  706. tlsInfo = nil
  707. }
  708. ml, err := transport.NewListener(murl.Host, murl.Scheme, tlsInfo)
  709. if err != nil {
  710. return err
  711. }
  712. e.metricsListeners = append(e.metricsListeners, ml)
  713. go func(u url.URL, ln net.Listener) {
  714. if e.cfg.logger != nil {
  715. e.cfg.logger.Info(
  716. "serving metrics",
  717. zap.String("address", u.String()),
  718. )
  719. } else {
  720. plog.Info("listening for metrics on ", u.String())
  721. }
  722. e.errHandler(http.Serve(ln, metricsMux))
  723. }(murl, ml)
  724. }
  725. }
  726. return nil
  727. }
  728. func (e *Etcd) errHandler(err error) {
  729. select {
  730. case <-e.stopc:
  731. return
  732. default:
  733. }
  734. select {
  735. case <-e.stopc:
  736. case e.errc <- err:
  737. }
  738. }
  739. // GetLogger returns the logger.
  740. func (e *Etcd) GetLogger() *zap.Logger {
  741. e.cfg.loggerMu.RLock()
  742. l := e.cfg.logger
  743. e.cfg.loggerMu.RUnlock()
  744. return l
  745. }
  746. func parseCompactionRetention(mode, retention string) (ret time.Duration, err error) {
  747. h, err := strconv.Atoi(retention)
  748. if err == nil {
  749. switch mode {
  750. case CompactorModeRevision:
  751. ret = time.Duration(int64(h))
  752. case CompactorModePeriodic:
  753. ret = time.Duration(int64(h)) * time.Hour
  754. }
  755. } else {
  756. // periodic compaction
  757. ret, err = time.ParseDuration(retention)
  758. if err != nil {
  759. return 0, fmt.Errorf("error parsing CompactionRetention: %v", err)
  760. }
  761. }
  762. return ret, nil
  763. }