etcd.go 14 KB

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