etcd.go 14 KB

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